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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Calisma7")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Calisma7")] [assembly: System.Reflection.AssemblyTitleAttribute("Calisma7")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.652174
80
0.64385
[ "MIT" ]
aleynazengin/CSharp101_Patika
Calisma7/obj/Debug/net5.0/Calisma7.AssemblyInfo.cs
935
C#
namespace TwitchLeecher.Gui.ViewModels { public class VideosLoadingViewVM : ViewModelBase { // Data Template Marker } }
20
52
0.685714
[ "MIT" ]
dstftw/TwitchLeecher
TwitchLeecher/TwitchLeecher.Gui/ViewModels/VideosLoadingViewVM.cs
142
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02.Creating Constructors")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02.Creating Constructors")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ac56236c-6202-4388-a10f-fa26c73cd48c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.27027
84
0.749294
[ "MIT" ]
ewgeni-dinew/04.Databases_Advanced-Entity_Framework
01.Defining Classes/02.Creating Constructors/Properties/AssemblyInfo.cs
1,419
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("06. BinarySearchTreeDemo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("06. BinarySearchTreeDemo")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("36ed23e3-7896-418d-9401-6fb7912cefaf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.405405
84
0.746657
[ "MIT" ]
vic-alexiev/TelerikAcademy
OOP/Homework Assignments/6. Common Type System/06. BinarySearchTreeDemo/Properties/AssemblyInfo.cs
1,424
C#
using CadEditor; using System; //css_include shared_settings/BlockUtils.cs; //css_include shared_settings/SharedUtils.cs; public class Data { public OffsetRec getScreensOffset() { return new OffsetRec(0x10010, 21, 16*16, 16, 16); } public bool isBigBlockEditorEnabled() { return false; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return SharedUtils.fakeVideoAddr(); } public GetVideoChunkFunc getVideoChunkFunc() { return SharedUtils.getVideoChunk(new[] {"chr1-6.bin"}); } public SetVideoChunkFunc setVideoChunkFunc() { return null; } public bool isBuildScreenFromSmallBlocks() { return true; } public OffsetRec getBlocksOffset() { return new OffsetRec(0x11a10, 1 , 0x1000); } public int getBlocksCount() { return 256; } public int getBigBlocksCount() { return 256; } public GetBlocksFunc getBlocksFunc() { return BlockUtils.getBlocksFromAlignedArrays;} public SetBlocksFunc setBlocksFunc() { return BlockUtils.setBlocksToAlignedArrays;} public GetPalFunc getPalFunc() { return SharedUtils.readPalFromBin(new[] {"pal1-6.bin"}); } public SetPalFunc setPalFunc() { return null;} }
49.37037
113
0.706677
[ "MIT" ]
spiiin/CadEditor
CadEditor/settings_nes/tiny_toon_adventures_6/Settings_TinyToonAdventures6-1-6.cs
1,333
C#
using Nirvana.CQRS; using Nirvana.Data; using Nirvana.Mediation; using Nirvana.Util.Tine; using TechFu.Nirvana.EventStoreSample.Domain.Domain.Security; using TechFu.Nirvana.EventStoreSample.Services.Shared; using TechFu.Nirvana.EventStoreSample.Services.Shared.Services.Security.Command; using TechFu.Nirvana.EventStoreSample.Services.Shared.Services.Security.Events; namespace TechFu.Nirvana.EventStoreSample.Domain.Handlers.Security.Commands { public class CreateAnonymousUserHandler : BaseNoOpCommandHandler<CreateAnonymousUserCommand> { private readonly IRepository<SecurityRoot> _repository; public CreateAnonymousUserHandler(IRepository<SecurityRoot> repository, IChildMediatorFactory mediator) : base(mediator) { _repository = repository; } public override CommandResponse<Nop> Handle(CreateAnonymousUserCommand task) { var user = _repository.Get<SiteUser>(task.SessionId); if (user != null) return CommandResponse.Succeeded(Nop.NoValue, "User already existed"); user = new SiteUser { Id = task.SessionId, IsAnonomous = true, LastLogin = new SystemTime().UtcNow(), LoginCount = 1, Name = "" }; _repository.SaveOrUpdate(user); Mediator.InternalEvent(new UserCreatedEvent { UserId = user.Id }); return CommandResponse.Succeeded(Nop.NoValue); } } }
36.72093
111
0.652312
[ "MIT" ]
nirvana-framework/Samples
src/EventStore/TechFu.Nirvana.EventStoreSample.Domain/Handlers/Security/Commands/CreateAnonymousUserHandler.cs
1,579
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Luis; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.AI.QnA.Dialogs; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Solutions; using Microsoft.Bot.Builder.Solutions.Dialogs; using Microsoft.Bot.Builder.Solutions.Extensions; using Microsoft.Bot.Builder.Solutions.Proactive; using Microsoft.Bot.Builder.Solutions.Responses; using Microsoft.Bot.Builder.Solutions.Skills; using Microsoft.Bot.Builder.Solutions.Skills.Dialogs; using Microsoft.Bot.Builder.Solutions.Util; using Microsoft.Bot.Connector.Authentication; using Microsoft.Bot.Schema; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using VirtualAssistantSample.Models; using VirtualAssistantSample.Services; namespace VirtualAssistantSample.Dialogs { // Dialog providing activity routing and message/event processing. public class MainDialog : ActivityHandlerDialog { private BotServices _services; private BotSettings _settings; private OnboardingDialog _onboardingDialog; private SwitchSkillDialog _switchSkillDialog; private LocaleTemplateEngineManager _templateEngine; private IStatePropertyAccessor<SkillContext> _skillContext; private IStatePropertyAccessor<UserProfileState> _userProfileState; private IStatePropertyAccessor<List<Activity>> _previousResponseAccessor; private MicrosoftAppCredentials _appCredentials; private IStatePropertyAccessor<ProactiveModel> _proactiveStateAccessor; public MainDialog( IServiceProvider serviceProvider, IBotTelemetryClient telemetryClient, MicrosoftAppCredentials appCredentials, ProactiveState proactiveState) : base(nameof(MainDialog), telemetryClient) { _services = serviceProvider.GetService<BotServices>(); _settings = serviceProvider.GetService<BotSettings>(); _templateEngine = serviceProvider.GetService<LocaleTemplateEngineManager>(); TelemetryClient = telemetryClient; // Create user state properties var userState = serviceProvider.GetService<UserState>(); _userProfileState = userState.CreateProperty<UserProfileState>(nameof(UserProfileState)); _skillContext = userState.CreateProperty<SkillContext>(nameof(SkillContext)); // Create conversation state properties var conversationState = serviceProvider.GetService<ConversationState>(); _previousResponseAccessor = conversationState.CreateProperty<List<Activity>>(StateProperties.PreviousBotResponse); // SAMPLE: Create proactive state properties _appCredentials = appCredentials; _proactiveStateAccessor = proactiveState.CreateProperty<ProactiveModel>(nameof(ProactiveModel)); // Register dialogs _onboardingDialog = serviceProvider.GetService<OnboardingDialog>(); _switchSkillDialog = serviceProvider.GetService<SwitchSkillDialog>(); AddDialog(_onboardingDialog); AddDialog(_switchSkillDialog); // Register a QnAMakerDialog for each registered knowledgebase and ensure localised responses are provided. var localizedServices = _services.GetCognitiveModels(); foreach (var knowledgebase in localizedServices.QnAConfiguration) { var qnaDialog = new QnAMakerDialog( knowledgeBaseId: knowledgebase.Value.KnowledgeBaseId, endpointKey: knowledgebase.Value.EndpointKey, hostName: knowledgebase.Value.Host, noAnswer: _templateEngine.GenerateActivityForLocale("UnsupportedMessage"), activeLearningCardTitle: _templateEngine.GenerateActivityForLocale("QnaMakerAdaptiveLearningCardTitle").Text, cardNoMatchText: _templateEngine.GenerateActivityForLocale("QnaMakerNoMatchText").Text) { Id = knowledgebase.Key }; AddDialog(qnaDialog); } // Register skill dialogs var skillDialogs = serviceProvider.GetServices<SkillDialog>(); foreach (var dialog in skillDialogs) { AddDialog(dialog); } } // Runs on every turn of the conversation. protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default) { if (innerDc.Context.Activity.Type == ActivityTypes.Message) { // Get cognitive models for the current locale. var localizedServices = _services.GetCognitiveModels(); // Run LUIS recognition and store result in turn state. var dispatchResult = await localizedServices.DispatchService.RecognizeAsync<DispatchLuis>(innerDc.Context, cancellationToken); innerDc.Context.TurnState.Add(StateProperties.DispatchResult, dispatchResult); if (dispatchResult.TopIntent().intent == DispatchLuis.Intent.l_General) { // Run LUIS recognition on General model and store result in turn state. var generalResult = await localizedServices.LuisServices["General"].RecognizeAsync<GeneralLuis>(innerDc.Context, cancellationToken); innerDc.Context.TurnState.Add(StateProperties.GeneralResult, generalResult); } } // Set up response caching for "repeat" functionality. innerDc.Context.OnSendActivities(StoreOutgoingActivities); return await base.OnContinueDialogAsync(innerDc, cancellationToken); } // Runs on every turn of the conversation to check if the conversation should be interrupted. protected override async Task<InterruptionAction> OnInterruptDialogAsync(DialogContext dc, CancellationToken cancellationToken) { var activity = dc.Context.Activity; var userProfile = await _userProfileState.GetAsync(dc.Context, () => new UserProfileState()); var dialog = dc.ActiveDialog?.Id != null ? dc.FindDialog(dc.ActiveDialog?.Id) : null; if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text)) { // Check if the active dialog is a skill for conditional interruption. var isSkill = dialog is SkillDialog; // Get Dispatch LUIS result from turn state. var dispatchResult = dc.Context.TurnState.Get<DispatchLuis>(StateProperties.DispatchResult); (var dispatchIntent, var dispatchScore) = dispatchResult.TopIntent(); // Check if we need to switch skills. if (isSkill) { if (dispatchIntent.ToString() != dialog.Id && dispatchScore > 0.9) { var identifiedSkill = SkillRouter.IsSkill(_settings.Skills, dispatchResult.TopIntent().intent.ToString()); if (identifiedSkill != null) { var prompt = _templateEngine.GenerateActivityForLocale("SkillSwitchPrompt", new { Skill = identifiedSkill.Name }); await dc.BeginDialogAsync(_switchSkillDialog.Id, new SwitchSkillDialogOptions(prompt, identifiedSkill)); return InterruptionAction.Waiting; } } } if (dispatchIntent == DispatchLuis.Intent.l_General) { // Get connected LUIS result from turn state. var generalResult = dc.Context.TurnState.Get<GeneralLuis>(StateProperties.GeneralResult); (var generalIntent, var generalScore) = generalResult.TopIntent(); if (generalScore > 0.5) { switch (generalIntent) { case GeneralLuis.Intent.Cancel: { // Suppress completion message for utility functions. dc.SuppressCompletionMessage(true); await dc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("CancelledMessage", userProfile)); await dc.CancelAllDialogsAsync(); return InterruptionAction.End; } case GeneralLuis.Intent.Escalate: { await dc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("EscalateMessage", userProfile)); return InterruptionAction.Resume; } case GeneralLuis.Intent.Help: { // Suppress completion message for utility functions. dc.SuppressCompletionMessage(true); if (isSkill) { // If current dialog is a skill, allow it to handle its own help intent. await dc.ContinueDialogAsync(cancellationToken); break; } else { await dc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("HelpCard", userProfile)); return InterruptionAction.Resume; } } case GeneralLuis.Intent.Logout: { // Suppress completion message for utility functions. dc.SuppressCompletionMessage(true); // Log user out of all accounts. await LogUserOut(dc); await dc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("LogoutMessage", userProfile)); return InterruptionAction.End; } case GeneralLuis.Intent.Repeat: { // No need to send the usual dialog completion message for utility capabilities such as these. dc.SuppressCompletionMessage(true); // Sends the activities since the last user message again. var previousResponse = await _previousResponseAccessor.GetAsync(dc.Context, () => new List<Activity>()); foreach (var response in previousResponse) { // Reset id of original activity so it can be processed by the channel. response.Id = string.Empty; await dc.Context.SendActivityAsync(response); } return InterruptionAction.Waiting; } case GeneralLuis.Intent.StartOver: { // Suppresss completion message for utility functions. dc.SuppressCompletionMessage(true); await dc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("StartOverMessage", userProfile)); // Cancel all dialogs on the stack. await dc.CancelAllDialogsAsync(); return InterruptionAction.End; } case GeneralLuis.Intent.Stop: { // Use this intent to send an event to your device that can turn off the microphone in speech scenarios. break; } } } } } return InterruptionAction.NoAction; } // Runs when the dialog stack is empty, and a new member is added to the conversation. Can be used to send an introduction activity. protected override async Task OnMembersAddedAsync(DialogContext innerDc, CancellationToken cancellationToken = default) { var userProfile = await _userProfileState.GetAsync(innerDc.Context, () => new UserProfileState()); if (string.IsNullOrEmpty(userProfile.Name)) { // Send new user intro card. await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("NewUserIntroCard", userProfile)); // Start onboarding dialog. await innerDc.BeginDialogAsync(nameof(OnboardingDialog)); } else { // Send returning user intro card. await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("ReturningUserIntroCard", userProfile)); } // Suppress completion message. innerDc.SuppressCompletionMessage(true); } // Runs when the dialog stack is empty, and a new message activity comes in. protected override async Task OnMessageActivityAsync(DialogContext innerDc, CancellationToken cancellationToken = default) { var activity = innerDc.Context.Activity.AsMessageActivity(); var userProfile = await _userProfileState.GetAsync(innerDc.Context, () => new UserProfileState()); if (!string.IsNullOrEmpty(activity.Text)) { // Get current cognitive models for the current locale. CognitiveModelSet localizedServices = _services.GetCognitiveModels(); // Get dispatch result from turn state. var dispatchResult = innerDc.Context.TurnState.Get<DispatchLuis>(StateProperties.DispatchResult); (var dispatchIntent, var dispatchScore) = dispatchResult.TopIntent(); // Check if the dispatch intent maps to a skill. var identifiedSkill = SkillRouter.IsSkill(_settings.Skills, dispatchIntent.ToString()); if (identifiedSkill != null) { // Start the skill dialog. await innerDc.BeginDialogAsync(identifiedSkill.Id); } else if (dispatchIntent == DispatchLuis.Intent.q_Faq) { await innerDc.BeginDialogAsync("Faq"); } else if (dispatchIntent == DispatchLuis.Intent.q_Chitchat) { innerDc.SuppressCompletionMessage(true); await innerDc.BeginDialogAsync("Chitchat"); } else if (dispatchIntent == DispatchLuis.Intent.q_HRBenefits) { innerDc.SuppressCompletionMessage(true); await innerDc.BeginDialogAsync("HRBenefits"); } else { innerDc.SuppressCompletionMessage(true); await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("UnsupportedMessage", userProfile)); } } } // Runs when a new event activity comes in. protected override async Task OnEventActivityAsync(DialogContext innerDc, CancellationToken cancellationToken = default) { var ev = innerDc.Context.Activity.AsEventActivity(); var value = ev.Value?.ToString(); switch (ev.Name) { case Events.Location: { var locationObj = new JObject(); locationObj.Add(StateProperties.Location, JToken.FromObject(value)); // Store location for use by skills. var skillContext = await _skillContext.GetAsync(innerDc.Context, () => new SkillContext()); skillContext[StateProperties.Location] = locationObj; await _skillContext.SetAsync(innerDc.Context, skillContext); break; } case Events.TimeZone: { try { var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(value); var timeZoneObj = new JObject(); timeZoneObj.Add(StateProperties.TimeZone, JToken.FromObject(timeZoneInfo)); // Store location for use by skills. var skillContext = await _skillContext.GetAsync(innerDc.Context, () => new SkillContext()); skillContext[StateProperties.TimeZone] = timeZoneObj; await _skillContext.SetAsync(innerDc.Context, skillContext); } catch { await innerDc.Context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Received time zone could not be parsed. Property not set.")); } break; } case Events.Broadcast: { var eventData = JsonConvert.DeserializeObject<EventData>(innerDc.Context.Activity.Value.ToString()); var proactiveModel = await _proactiveStateAccessor.GetAsync(innerDc.Context, () => new ProactiveModel()); var hashedUserId = MD5Util.ComputeHash(eventData.UserId); var conversationReference = proactiveModel[hashedUserId].Conversation; await innerDc.Context.Adapter.ContinueConversationAsync(_appCredentials.MicrosoftAppId, conversationReference, ContinueConversationCallback(innerDc.Context, eventData.Message), cancellationToken); break; } case TokenEvents.TokenResponseEventName: { // Forward the token response activity to the dialog waiting on the stack. await innerDc.ContinueDialogAsync(); break; } default: { await innerDc.Context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Unknown Event '{ev.Name ?? "undefined"}' was received but not processed.")); break; } } } // Runs when an activity with an unknown type is received. protected override async Task OnUnhandledActivityTypeAsync(DialogContext innerDc, CancellationToken cancellationToken = default) { await innerDc.Context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Unknown activity was received but not processed.")); } // Runs when the dialog stack completes. protected override async Task OnDialogCompleteAsync(DialogContext outerDc, object result, CancellationToken cancellationToken = default) { var userProfile = await _userProfileState.GetAsync(outerDc.Context, () => new UserProfileState()); // Only send a completion message if the user sent a message activity. if (outerDc.Context.Activity.Type == ActivityTypes.Message && !outerDc.SuppressCompletionMessage()) { await outerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("CompletedMessage", userProfile)); } } private async Task LogUserOut(DialogContext dc) { IUserTokenProvider tokenProvider; var supported = dc.Context.Adapter is IUserTokenProvider; if (supported) { tokenProvider = (IUserTokenProvider)dc.Context.Adapter; // Sign out user var tokens = await tokenProvider.GetTokenStatusAsync(dc.Context, dc.Context.Activity.From.Id); foreach (var token in tokens) { await tokenProvider.SignOutUserAsync(dc.Context, token.ConnectionName); } // Cancel all active dialogs await dc.CancelAllDialogsAsync(); } else { throw new InvalidOperationException("OAuthPrompt.SignOutUser(): not supported by the current adapter"); } } private async Task<ResourceResponse[]> StoreOutgoingActivities(ITurnContext turnContext, List<Activity> activities, Func<Task<ResourceResponse[]>> next) { var messageActivities = activities .Where(a => a.Type == ActivityTypes.Message) .ToList(); // If the bot is sending message activities to the user (as opposed to trace activities) if (messageActivities.Any()) { var botResponse = await _previousResponseAccessor.GetAsync(turnContext, () => new List<Activity>()); // Get only the activities sent in response to last user message botResponse = botResponse .Concat(messageActivities) .Where(a => a.ReplyToId == turnContext.Activity.Id) .ToList(); await _previousResponseAccessor.SetAsync(turnContext, botResponse); } return await next(); } /// <summary> /// Continue the conversation callback. /// </summary> /// <param name="context">Turn context.</param> /// <param name="message">Activity text.</param> /// <returns>Bot Callback Handler.</returns> private BotCallbackHandler ContinueConversationCallback(ITurnContext context, string message) { return async (turnContext, cancellationToken) => { var activity = turnContext.Activity.CreateReply(message); EnsureActivity(activity); await turnContext.SendActivityAsync(activity); }; } /// <summary> /// This method is required for proactive notifications to work in Web Chat. /// </summary> /// <param name="activity">Proactive Activity.</param> private void EnsureActivity(Activity activity) { if (activity != null) { if (activity.From != null) { activity.From.Name = "User"; activity.From.Properties["role"] = "user"; } if (activity.Recipient != null) { activity.Recipient.Id = "1"; activity.Recipient.Name = "Bot"; activity.Recipient.Properties["role"] = "bot"; } } } private class Events { public const string Location = "VA.Location"; public const string TimeZone = "VA.Timezone"; public const string Broadcast = "BroadcastEvent"; } private class StateProperties { public const string DispatchResult = "dispatchResult"; public const string GeneralResult = "generalResult"; public const string PreviousBotResponse = "previousBotResponse"; public const string Location = "location"; public const string TimeZone = "timezone"; } } }
47.705769
220
0.566655
[ "MIT" ]
christian7877/botframework-solutions
samples/csharp/assistants/enterprise-assistant/VirtualAssistantSample/Dialogs/MainDialog.cs
24,809
C#
namespace eQuantic.Core.Data.Repository.Sql { public interface ISqlRepository<TEntity, TKey> : IRepository<IQueryableUnitOfWork, TEntity, TKey> where TEntity : class, IEntity, new() { } }
33.333333
139
0.735
[ "MIT" ]
eQuantic/core-data
src/Repository/Sql/ISqlRepository.cs
202
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("UnoBunch.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("EXFO Inc.")] [assembly: AssemblyProduct("UnoBunch.iOS")] [assembly: AssemblyCopyright("Copyright © EXFO Inc. 2019")] [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("166de4ca-8f11-4ef9-bcf8-3e7834988e7d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.243243
84
0.74417
[ "Apache-2.0" ]
anaselhajjaji/UnoBench
UnoBunch.iOS/Properties/AssemblyInfo.cs
1,418
C#
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved namespace Microsoft.Samples.HyperV.FibreChannel { using System; using System.Management; using System.Globalization; using Microsoft.Samples.HyperV.Common; static class DeleteSanSample { /// <summary> /// Deletes a Virtual SAN by its Name. /// </summary> /// <param name="poolId">Name of the Virtual SAN to be deleted.</param> private static void DeleteSan( string poolId) { Console.WriteLine("Deleting Virtual SAN - {0} ...", poolId); ManagementScope scope = FibreChannelUtilities.GetFcScope(); using (ManagementObject rpConfigurationService = FibreChannelUtilities.GetResourcePoolConfigurationService(scope)) using (ManagementBaseObject inParams = rpConfigurationService.GetMethodParameters("DeletePool")) { inParams["Pool"] = FibreChannelUtilities.GetResourcePoolPath(scope, poolId); using (ManagementBaseObject outParams = rpConfigurationService.InvokeMethod( "DeletePool", inParams, null)) { WmiUtilities.ValidateOutput(outParams, scope, true, true); } } Console.WriteLine("Successfully deleted Virtual SAN - {0}", poolId); } /// <summary> /// Entry point for the DeleteSan sample. /// </summary> /// <param name="args">The command line arguments.</param> internal static void ExecuteSample( string[] args) { if (args.Length != 1 || (args.Length > 0 && args[0] == "/?")) { Console.WriteLine("Usage: DeleteSan <SanName>\n"); return; } try { DeleteSan(args[0]); } catch (Exception ex) { Console.WriteLine("Failed to delete the san. Error message details:\n"); Console.WriteLine(ex.Message); } } } }
34.5
93
0.532315
[ "MIT" ]
9578577/Windows-classic-samples
Samples/Hyper-V/FibreChannel/cs/DeleteSan.cs
2,482
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Grabacr07.KanColleViewer.Models; using Grabacr07.KanColleViewer.Properties; using Grabacr07.KanColleViewer.ViewModels.Messages; using Grabacr07.KanColleViewer.Views.Controls; using Livet.Behaviors.Messaging; using Livet.Messaging; namespace Grabacr07.KanColleViewer.Views.Behaviors { public class ZoomAction : InteractionMessageAction<KanColleHost> { protected override void InvokeAction(InteractionMessage message) { this.AssociatedObject.Update(); } } }
27
67
0.797101
[ "MIT" ]
KCV-Localisation/KanColleViewer
Grabacr07.KanColleViewer/Views/Behaviors/ZoomAction.cs
623
C#
namespace Aggregator.Core.Interfaces { public interface IWorkItemImplementation { IWorkItemLinkCollection WorkItemLinksImpl { get; } } }
22.428571
58
0.726115
[ "Apache-2.0" ]
evertonmc/tfsaggregator
Aggregator.Core/Aggregator.Core/Interfaces/IWorkItemImplementation.cs
159
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace CoreWCF.Configuration { internal static class BasicHttpMessageCredentialTypeHelper { internal static bool IsDefined(BasicHttpMessageCredentialType value) { return (value == BasicHttpMessageCredentialType.UserName || value == BasicHttpMessageCredentialType.Certificate); } } }
32.6
76
0.707566
[ "MIT" ]
AlexanderSemenyak/CoreWCF
src/CoreWCF.ConfigurationManager/src/CoreWCF/Configuration/BasicHttpMessageCredentialTypeHelper.cs
491
C#
namespace MemoryDB.SqlServer.Test.Models { public class Address { public int AddressId { get; set; } public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string PostCode { get; set; } } }
24.454545
48
0.609665
[ "MIT" ]
peteh1989/MemoryDB
tests/MemoryDB.SqlServer.Test/Models/Address.cs
271
C#
#region LGPL License /************************************************************************* Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net) Copyright (C)2004 Paul D Turner ([email protected]) C# Port developed by Chris McGuirk ([email protected]) Compatible with the Axiom 3D Engine (http://axiomengine.sf.net) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #endregion LGPL License using System; using System.Text; using System.Drawing; namespace CeGui { /// <summary> /// A higher order GUI entity that represents a renderable image with formatting options. /// </summary> /// <remarks> /// This class is intended to be used where a (usually top-level) GUI element needs to draw an image that requires some additional /// formatting. It is possible to specify the Image that is to be rendered, as well as the horizontal and vertical formatting /// required. /// </remarks> public class RenderableImage : RenderableElement { #region Fields /// <summary> /// Currently set horizontal formatting option. /// </summary> protected HorizontalImageFormat horizontalFormat; /// <summary> /// Currently set vertical formatting option. /// </summary> protected VerticalImageFormat verticalFormat; /// <summary> /// Reference to the actual Image to be displayed. /// </summary> protected Image image; #endregion Fields #region Constructor /// <summary> /// Default constructor. /// </summary> public RenderableImage() { // setup default formats horizontalFormat = HorizontalImageFormat.LeftAligned; verticalFormat = VerticalImageFormat.TopAligned; } #endregion Constructor #region Properties /// <summary> /// Set the required horizontal formatting. /// </summary> /// <value>One of the <see cref="HorizontalImageFormat"/> values specifying the formatting required.</value> public HorizontalImageFormat HorizontalFormat { get { return horizontalFormat; } set { horizontalFormat = value; } } /// <summary> /// Get/Set the Image object to be drawn by this RenderableImage. /// </summary> /// <value> /// Reference to the Image object to be rendered. /// Can be 'null' to specify no image is to be rendered. /// </value> public Image Image { get { return image; } set { image = value; } } /// <summary> /// Set the required vertical formatting. /// </summary> /// <value>One of the <see cref="VerticalImageFormat"/> values specifying the formatting required.</value> public VerticalImageFormat VerticalFormat { get { return verticalFormat; } set { verticalFormat = value; } } #endregion Properties #region RenderableElement Members /// <summary> /// Renders the imagery for a RenderableImage element. /// </summary> /// <param name="position">The final rendering position for the object.</param> /// <param name="clipRect">The clipping area for the rendering. No rendering will be performed outside this area.</param> protected override void DrawImpl(Vector3 position, Rect clipRect) { // do not draw anything if there is not image if(image == null) { return; } // // calculate final clipping Rect which is intersection of RenderableImage area and supplied clipping area Rect finalClipper = new Rect(position.x, position.y, 0, 0); finalClipper.Size = area.Size; finalClipper = clipRect.GetIntersection(finalClipper); SizeF imageSize = image.Size; // // calculate number of times to tile image based of formatting options int horzTiles = (horizontalFormat == HorizontalImageFormat.Tiled) ? (int)((area.Width + (imageSize.Width - 1)) / imageSize.Width) : 1; int vertTiles = (verticalFormat == VerticalImageFormat.Tiled) ? (int)((area.Height + (imageSize.Height - 1)) / imageSize.Height) : 1; // calculate 'base' X co-ordinate, depending upon formatting float baseX = 0, baseY = 0; // calc horizontal base position switch(horizontalFormat) { case HorizontalImageFormat.Stretched: imageSize.Width = area.Width; baseX = position.x; break; case HorizontalImageFormat.Tiled: case HorizontalImageFormat.LeftAligned: baseX = position.x; break; case HorizontalImageFormat.Centered: baseX = position.x + ((area.Width - imageSize.Width) * 0.5f); break; case HorizontalImageFormat.RightAligned: baseX = position.x + area.Width - imageSize.Width; break; default: throw new InvalidRequestException("An unknown horizontal format was specified for a RenderableImage."); } // calc vertical base position switch(verticalFormat) { case VerticalImageFormat.Stretched: imageSize.Height = area.Height; baseY = position.y; break; case VerticalImageFormat.Tiled: case VerticalImageFormat.TopAligned: baseY = position.y; break; case VerticalImageFormat.Centered: baseY = position.y + ((area.Height - imageSize.Height) * 0.5f); break; case VerticalImageFormat.BottomAligned: baseY = position.y + area.Height - imageSize.Height; break; default: throw new InvalidRequestException("An unknown vertical format was specified for a RenderableImage."); } Vector3 drawPos = new Vector3(0, baseY, position.z); // perform actual rendering for(int row = 0; row < vertTiles; row++) { drawPos.x = baseX; for(int col = 0; col < horzTiles; col++) { image.Draw(drawPos, imageSize, finalClipper, colors); drawPos.x += imageSize.Width; } drawPos.y += imageSize.Height; } } #endregion RenderableElement Members } } // namespace CeGui
32.197183
132
0.643045
[ "MIT" ]
astyanax/Project-Xenocide
xna/branches/Unreviewed_Patches_branch/Dependancies/CeGui/CeGui/Source/RenderableImage.cs
6,858
C#
using System; using System.Collections.Generic; class A { static int[] Read() => Array.ConvertAll(Console.ReadLine().Split(), int.Parse); static (int, int) Read2() { var a = Read(); return (a[0], a[1]); } static void Main() { var (h, w) = Read2(); var sv = Read2() - new P(1, 1); var ev = Read2() - new P(1, 1); var s = Array.ConvertAll(new bool[h], _ => Console.ReadLine()); var r = GridShortestPath.UndirectedBfs(h, w, s, sv, ev); Console.WriteLine(r.GetByP(ev)); } } struct P : IEquatable<P> { public static P Zero = new P(); public static P UnitI = new P(1, 0); public static P UnitJ = new P(0, 1); public int i, j; public P(int _i, int _j) { i = _i; j = _j; } public override string ToString() => $"{i} {j}"; public static implicit operator P((int i, int j) v) => new P(v.i, v.j); public static explicit operator (int, int)(P v) => (v.i, v.j); public bool Equals(P other) => i == other.i && j == other.j; public static bool operator ==(P v1, P v2) => v1.Equals(v2); public static bool operator !=(P v1, P v2) => !v1.Equals(v2); public override bool Equals(object obj) => obj is P && Equals((P)obj); public override int GetHashCode() => Tuple.Create(i, j).GetHashCode(); public static P operator -(P v) => new P(-v.i, -v.j); public static P operator +(P v1, P v2) => new P(v1.i + v2.i, v1.j + v2.j); public static P operator -(P v1, P v2) => new P(v1.i - v2.i, v1.j - v2.j); public bool IsInRange(int h, int w) => 0 <= i && i < h && 0 <= j && j < w; public P[] Nexts() => new[] { new P(i - 1, j), new P(i + 1, j), new P(i, j - 1), new P(i, j + 1) }; public static P[] NextsByDelta = new[] { new P(-1, 0), new P(1, 0), new P(0, -1), new P(0, 1) }; } static class GridShortestPath { const char Road = '.'; const char Wall = '#'; // 2次元配列に2次元インデックスでアクセスします。 public static T GetByP<T>(this T[][] a, P p) => a[p.i][p.j]; public static void SetByP<T>(this T[][] a, P p, T value) => a[p.i][p.j] = value; public static char GetByP(this string[] s, P p) => s[p.i][p.j]; public static string[] ReadEnclosedGrid(ref int h, ref int w, char c = '#') { var s = new string[h + 2]; s[h + 1] = s[0] = new string(c, w += 2); for (int i = 1; i <= h; ++i) s[i] = c + Console.ReadLine() + c; h += 2; return s; } public static P FindChar(string[] s, char c) { for (int i = 0; i < s.Length; ++i) for (int j = 0; j < s[0].Length; ++j) if (s[i][j] == c) return new P(i, j); return new P(-1, -1); } // 辺のコストがすべて等しい場合 // ev: 終点を指定しない場合、new P(-1, -1) // 壁チェックが含まれます。範囲チェックは含まれません。 public static int[][] Bfs(int h, int w, Func<P, IEnumerable<P>> toNexts, P sv, P ev, Func<P, bool> isWall = null) { var cs = Array.ConvertAll(new bool[h], _ => Array.ConvertAll(new bool[w], __ => int.MaxValue)); var q = new Queue<P>(); cs.SetByP(sv, 0); q.Enqueue(sv); while (q.Count > 0) { var v = q.Dequeue(); var nc = cs.GetByP(v) + 1; foreach (var nv in toNexts(v)) { if (isWall?.Invoke(nv) == true) continue; if (cs.GetByP(nv) <= nc) continue; cs.SetByP(nv, nc); if (nv == ev) return cs; q.Enqueue(nv); } } return cs; } public static int[][] Bfs(int h, int w, P[][] es, bool directed, P sv, P ev) { var map = Array.ConvertAll(new bool[h], _ => Array.ConvertAll(new bool[w], __ => new List<P>())); foreach (var e in es) { map.GetByP(e[0]).Add(e[1]); if (!directed) map.GetByP(e[1]).Add(e[0]); } return Bfs(h, w, v => map.GetByP(v), sv, ev); } public static int[][] BfsByDelta(int h, int w, Func<IEnumerable<P>> toNextsByDelta, P sv, P ev, Func<P, bool> isWall = null) { return Bfs(h, w, v => System.Linq.Enumerable.Select(toNextsByDelta(), d => v + d), sv, ev, isWall); } [Obsolete] public static int[][] UndirectedBfs0(int h, int w, string[] s, P sv, P ev) { var map = Array.ConvertAll(new bool[h], _ => Array.ConvertAll(new bool[w], __ => new List<P>())); for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) { var v = new P(i, j); if (i > 0) { var nv = new P(i - 1, j); map.GetByP(v).Add(nv); map.GetByP(nv).Add(v); } if (j > 0) { var nv = new P(i, j - 1); map.GetByP(v).Add(nv); map.GetByP(nv).Add(v); } } return Bfs(h, w, v => map.GetByP(v), sv, ev, v => s[v.i][v.j] == '#'); } // 典型的な無向グリッド BFS // ev: 終点を指定しない場合、new P(-1, -1) public static int[][] UndirectedBfs(int h, int w, string[] s, P sv, P ev) { return Bfs(h, w, v => v.Nexts(), sv, ev, v => s.GetByP(v) == '#'); } public static int[][] UndirectedBfsByDelta(int h, int w, string[] s, P sv, P ev) { return BfsByDelta(h, w, () => P.NextsByDelta, sv, ev, v => s.GetByP(v) == '#'); } }
31.311688
126
0.547283
[ "MIT" ]
sakapon/AtCoder-Contests
CSharp/Contests/ATC002/A.cs
5,012
C#
using HotChocolate.Data.Filters; using HotChocolate.Execution; using HotChocolate.Types; using Microsoft.Extensions.DependencyInjection; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver; using System; using System.Threading.Tasks; using Squadron; using Xunit; namespace HotChocolate.Data.MongoDb.Filters { public class MongoDbFindFluentTests : IClassFixture<MongoResource> { private static readonly Foo[] _fooEntities = { new Foo { Bar = true }, new Foo { Bar = false } }; private static readonly Bar[] _barEntities = { new Bar { Baz = new DateTimeOffset(2020, 1, 12, 0, 0, 0, TimeSpan.Zero) }, new Bar { Baz = new DateTimeOffset(2020, 1, 11, 0, 0, 0, TimeSpan.Zero) } }; private static readonly Baz[] _bazEntities = { new Baz { Bar = new DateTimeOffset(2020, 1, 12, 0, 0, 0, TimeSpan.Zero) }, new Baz { Bar = new DateTimeOffset(2020, 1, 11, 0, 0, 0, TimeSpan.Zero) }, new Baz { Bar = new DateTimeOffset(1996, 1, 11, 0, 0, 0, TimeSpan.Zero) } }; private readonly MongoResource _resource; public MongoDbFindFluentTests(MongoResource resource) { _resource = resource; } [Fact] public async Task BsonElement_Rename() { // arrange IRequestExecutor tester = CreateSchema( () => { IMongoCollection<Foo> collection = _resource.CreateCollection<Foo>("data_" + Guid.NewGuid().ToString("N")); collection.InsertMany(_fooEntities); return collection.Find(FilterDefinition<Foo>.Empty).AsExecutable(); }); // act // assert IExecutionResult res1 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery("{ root(where: { bar: { eq: true}}){ bar}}") .Create()); res1.MatchDocumentSnapshot("true"); IExecutionResult res2 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery("{ root(where: { bar: { eq: false}}){ bar}}") .Create()); res2.MatchDocumentSnapshot("false"); } [Fact] public async Task FindFluent_Serializer() { // arrange BsonClassMap.RegisterClassMap<Bar>( x => x.MapField(y => y.Baz) .SetSerializer(new DateTimeOffsetSerializer(BsonType.String)) .SetElementName("testName")); IRequestExecutor tester = CreateSchema( () => { IMongoCollection<Bar> collection = _resource.CreateCollection<Bar>("data_" + Guid.NewGuid().ToString("N")); collection.InsertMany(_barEntities); return collection.Find(FilterDefinition<Bar>.Empty).AsExecutable(); }); // act // assert IExecutionResult res1 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery("{ root(where: { baz: { eq: \"2020-01-11T00:00:00Z\"}}){ baz}}") .Create()); res1.MatchDocumentSnapshot("2020-01-11"); IExecutionResult res2 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery("{ root(where: { baz: { eq: \"2020-01-12T00:00:00Z\"}}){ baz}}") .Create()); res2.MatchDocumentSnapshot("2020-01-12"); } [Fact] public async Task FindFluent_CombineQuery() { // arrange IRequestExecutor tester = CreateSchema( () => { IMongoCollection<Baz> collection = _resource.CreateCollection<Baz>("data_" + Guid.NewGuid().ToString("N")); collection.InsertMany(_bazEntities); return collection .Find(x => x.Bar > new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero)) .AsExecutable(); }); // act // assert IExecutionResult res1 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery("{ root(where: { bar: { eq: \"2020-01-11T00:00:00Z\"}}){ bar}}") .Create()); res1.MatchDocumentSnapshot("2020-01-11"); IExecutionResult res2 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery("{ root(where: { bar: { eq: \"2020-01-12T00:00:00Z\"}}){ bar}}") .Create()); res2.MatchDocumentSnapshot("2020-01-12"); } public class Foo { [BsonId] public Guid Id { get; set; } = Guid.NewGuid(); [BsonElement("renameTest")] public bool Bar { get; set; } } public class Bar { [BsonId] public Guid Id { get; set; } = Guid.NewGuid(); public DateTimeOffset Baz { get; set; } } public class Baz { [BsonId] public Guid Id { get; set; } = Guid.NewGuid(); public DateTimeOffset Bar { get; set; } } private static IRequestExecutor CreateSchema<TEntity>( Func<IExecutable<TEntity>> resolver) where TEntity : class { return new ServiceCollection() .AddGraphQL() .AddFiltering(x => x.AddMongoDbDefaults()) .AddQueryType( c => c .Name("Query") .Field("root") .Type<ListType<ObjectType<TEntity>>>() .Resolver( async ctx => await new ValueTask<IExecutable<TEntity>>(resolver())) .Use( next => async context => { await next(context); if (context.Result is IExecutable executable) { context.ContextData["query"] = executable.Print(); } }) .UseFiltering<FilterInputType<TEntity>>()) .UseRequest( next => async context => { await next(context); if (context.Result is IReadOnlyQueryResult result && context.ContextData.TryGetValue("query", out object? queryString)) { context.Result = QueryResultBuilder .FromResult(result) .SetContextData("query", queryString) .Create(); } }) .UseDefaultPipeline() .Services .BuildServiceProvider() .GetRequiredService<IRequestExecutorResolver>() .GetRequestExecutorAsync() .GetAwaiter() .GetResult(); } } }
34.868778
98
0.47768
[ "MIT" ]
Alxandr/hotchocolate
src/HotChocolate/MongoDb/test/Data.MongoDb.Filters.Tests/MongoDbFindFluentTests.cs
7,706
C#
/* * MIT License * * Copyright (c) 2020 plexdata.de * * 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 Plexdata.LineEndingsReplacer.Events; using System; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.IO; using System.Text; namespace Plexdata.LineEndingsReplacer.Entities { public class WorkResultListItem { #region Private Fields public const String ActionCanceled = "Canceled"; public const String ActionFinished = "Finished"; public const String ActionDeclined = "Declined"; public const String ActionExcluded = "Excluded"; public const String ActionIncluded = "Included"; #endregion #region Construction public WorkResultListItem(Boolean canceled) { this.Action = this.GetResultType(canceled); this.Message = this.GetMessage(canceled); this.Exception = null; this.Source = null; this.Result = WorkResult.Empty; this.Foreground = this.GetForeground(canceled); this.Background = this.GetBackground(canceled); } public WorkResultListItem(WorkResultEventArgs value) { this.Action = this.GetResultType(value); this.Message = this.GetMessage(value); this.Exception = null; this.Source = value.Source; this.Result = value.Result; this.Foreground = this.GetForeground(value); this.Background = this.GetBackground(value); } public WorkResultListItem(ExceptionEventArgs value) { this.Action = this.GetResultType(value); this.Message = this.GetMessage(value); this.Exception = value.Exception; this.Source = value.Source; this.Result = new WorkResult($"Error: \"{value.Exception.Message}\""); this.Foreground = this.GetForeground(value); this.Background = this.GetBackground(value); } #endregion #region Public Properties public String Action { get; } public String Message { get; } public Exception Exception { get; } public FileSystemInfo Source { get; } public WorkResult Result { get; } public Color Foreground { get; } public Color Background { get; } public Boolean IsCanceled { get { return String.Equals(this.Action, WorkResultListItem.ActionCanceled); } } public Boolean IsFinished { get { return String.Equals(this.Action, WorkResultListItem.ActionFinished); } } public Boolean IsDeclined { get { return String.Equals(this.Action, WorkResultListItem.ActionDeclined); } } public Boolean IsExcluded { get { return String.Equals(this.Action, WorkResultListItem.ActionExcluded); } } public Boolean IsIncluded { get { return String.Equals(this.Action, WorkResultListItem.ActionIncluded); } } #endregion #region Public Methods public String ToMessage() { StringBuilder builder = new StringBuilder(128); if (this.IsDeclined) { if (this.Exception != null) { builder.AppendLine("An exception with message below has occurred while processing item!"); builder.AppendLine(); builder.AppendLine(this.Exception.Message); builder.AppendLine(); this.AddSourceToMessage(builder); } else { builder.AppendLine("An unspecified error has occurred while processing item!"); builder.AppendLine(); this.AddSourceToMessage(builder); } } else if (this.IsExcluded) { builder.AppendLine("Current item has been excluded and remains unchanged."); builder.AppendLine(); this.AddSourceToMessage(builder); } else if (this.IsIncluded) { builder.AppendLine("Current item has been included and was changed as shown below."); builder.AppendLine(); builder.AppendLine(this.Result?.ToMessage() ?? String.Empty); this.AddSourceToMessage(builder); } else { builder.AppendLine(this.Message); } return builder.ToString().Trim(); } public String[] GetReportCells() { String[] results = new String[4] { String.Empty, String.Empty, String.Empty, String.Empty }; results[0] = this.Action; if (this.IsDeclined) { results[1] = this.GetReportOrigin(this.Exception); results[2] = this.GetReportDetails(this.Exception); } else if (this.IsExcluded) { results[1] = this.GetReportOrigin(this.Source); results[2] = this.Result.Display; } else if (this.IsIncluded) { results[1] = this.GetReportOrigin(this.Source); results[2] = this.GetReportDetails(this.Source); } else { results[1] = this.GetReportOrigin(null); results[2] = this.Message; } results[3] = this.GetReportSource(); return results; } #endregion #region Private Methods private String GetResultType(Boolean canceled) { return canceled ? WorkResultListItem.ActionCanceled : WorkResultListItem.ActionFinished; } private String GetMessage(Boolean canceled) { return canceled ? "The operation has been canceled." : "The operation has finished."; } [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "<Pending>")] private Color GetForeground(Boolean canceled) { return SystemColors.WindowText; } private Color GetBackground(Boolean canceled) { return Color.FromArgb(canceled ? unchecked((Int32)0xFFFFBFBF) : unchecked((Int32)0xFFA5FFA5)); } private String GetResultType(WorkResultEventArgs value) { if (value.IsExcluded) { return WorkResultListItem.ActionExcluded; } return WorkResultListItem.ActionIncluded; } private String GetMessage(WorkResultEventArgs value) { StringBuilder builder = new StringBuilder(128); if (value.IsFolder) { builder.AppendFormat("Folder: \"{0}\"", value.ItemName); } else { builder.AppendFormat("File: \"{0}\"", value.ItemName); } return builder.ToString(); } private Color GetForeground(WorkResultEventArgs value) { if (value.IsExcluded) { return SystemColors.WindowText; } return SystemColors.WindowText; } private Color GetBackground(WorkResultEventArgs value) { if (value.IsExcluded) { return Color.FromArgb(unchecked((Int32)0xFFFFFFCC)); } return Color.White; } [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "<Pending>")] private String GetResultType(ExceptionEventArgs value) { return WorkResultListItem.ActionDeclined; } private String GetMessage(ExceptionEventArgs value) { StringBuilder builder = new StringBuilder(128); builder.Append("An error occurred"); if (value.HasSource) { builder.AppendFormat(" while processing \"{0}\"", Path.GetFileName(value.ItemName)); } builder.Append($". Operation {(value.IsAborted ? "has been aborted" : "continues with next item")}."); return builder.ToString(); } [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "<Pending>")] private Color GetForeground(ExceptionEventArgs value) { return SystemColors.WindowText; } [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "<Pending>")] private Color GetBackground(ExceptionEventArgs value) { return Color.FromArgb(unchecked((Int32)0xFFFF7F7F)); } private void AddSourceToMessage(StringBuilder builder) { if (this.Source is FileInfo) { builder.AppendLine($"File: {this.Source.Name}"); builder.AppendLine($"Path: {Path.GetDirectoryName(this.Source.FullName)}"); builder.AppendLine(); } else if (this.Source is DirectoryInfo) { builder.AppendLine($"Path: {this.Source.FullName}"); builder.AppendLine(); } } private String GetReportOrigin(Object value) { if (value is Exception) { return "Error"; } else if (value is FileInfo) { return "File"; } else if (value is DirectoryInfo) { return "Folder"; } else if (value == null && (this.IsCanceled || this.IsFinished)) { return "Global"; } else { return "Unknown"; } } private String GetReportDetails(Object value) { if (value is Exception) { if (value != null) { return this.Exception.Message; } else { return "An unspecified error has occurred."; } } else if (this.Source is FileInfo) { return this.Result.ToReport(); } else if (this.Source is DirectoryInfo) { return this.Result.Display; } else { return "Unknown"; } } private String GetReportSource() { if (this.Source != null) { return $"\"{this.Source.FullName}\""; } else if (this.IsCanceled || this.IsFinished) { return "Processing"; } else { return "Unknown"; } } #endregion } }
30.96368
115
0.521192
[ "MIT" ]
akesseler/LineEndingsReplacer
code/src/LineEndingsReplacer/Entities/WorkResultListItem.cs
12,790
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Google_Hash_Code { public class Library { public int AmountOfBooks { get; set; } public int SignupProcessTime { get; set; } public int ShippingCapacityPerDay { get; set; } public int Points { get; set; } public int Id { get; set; } public List<Book> Books { get; set; } public Library(int amountOfBooks, int signupProcessTime, int shippingCapacityPerDay) { AmountOfBooks = amountOfBooks; SignupProcessTime = signupProcessTime; ShippingCapacityPerDay = shippingCapacityPerDay; } } }
28.074074
93
0.627968
[ "MIT" ]
flabbet/hashcode_2020_qualification
Google Hash Code/Google Hash Code/Library.cs
760
C#
using System; using System.Collections.Generic; using System.Text; using System.Drawing; namespace PlottingTools { public class PlotterView { MeshPlotter m_plotter; public PlotterView(MeshPlotter plotter) { m_plotter = plotter; } private double m_obsX = 70; public double ObservatorX { get { return m_obsX; } set { m_obsX = value; m_plotter.ResizeView(); } } private double m_obsY = 35; public double ObservatorY { get { return m_obsY; } set { m_obsY = value; m_plotter.ResizeView(); } } private double m_obsZ = 40; public double ObservatorZ { get { return m_obsZ; } set { m_obsZ = value; m_plotter.ResizeView(); } } private int m_screenX = 0; public int ScreenX { get { return m_screenX; } set { m_screenX = value; m_plotter.ResizeView(); } } private int m_screenY = 0; public int ScreenY { get { return m_screenY; } set { m_screenY = value; m_plotter.ResizeView(); } } private double m_hueCS = 10; public double ColorSchema { get { return m_hueCS; } set { m_hueCS = value; m_plotter.ColorSchema = new ColorSchema(m_hueCS); } } public Color BaseColor { get { return m_plotter.ColorSchema.BaseColor; } set { m_plotter.ColorSchema = new ColorSchema(value); } } public bool IsWired { get { return m_plotter.IsWired; } set { m_plotter.IsWired = value; } } public Color PenColor { get { return m_plotter.SurfaceRenderer.PenColor; } set { m_plotter.SurfaceRenderer.PenColor = value; m_plotter.Invalidate(); } } public float PenWidth { get { return m_plotter.SurfaceRenderer.PenWidth; } set { m_plotter.SurfaceRenderer.PenWidth = value; m_plotter.Invalidate(); } } public Color BackColor { get { return m_plotter.BackColor; } set { m_plotter.BackColor = value; m_plotter.Invalidate(); } } public bool DrawBaseSurface { get { return m_plotter.SurfaceRenderer.DrawBaseSurface; } set { m_plotter.SurfaceRenderer.DrawBaseSurface = value; m_plotter.Invalidate(); } } public Color BaseSurfaceColor { get { return m_plotter.SurfaceRenderer.BaseSurfacePenColor; } set { m_plotter.SurfaceRenderer.BaseSurfacePenColor = value; m_plotter.Invalidate(); } } public float BaseSurfacePenWidth { get { return m_plotter.SurfaceRenderer.BaseSurfacePenWidth; } set { m_plotter.SurfaceRenderer.BaseSurfacePenWidth = value; m_plotter.Invalidate(); } } public bool DrawWires { get { return m_plotter.SurfaceRenderer.DrawWires; } set { m_plotter.SurfaceRenderer.DrawWires = value; m_plotter.Invalidate(); } } public double Density { get { return m_plotter.SurfaceRenderer.Density; } set { if (value <= 0.0) value = 0.5; m_plotter.SurfaceRenderer.Density = value; m_plotter.Invalidate(); } } } }
20.780822
70
0.428697
[ "MIT" ]
sinairv/GridSoccerSimulator
Source/Tools/Plot3D/PlotterView.cs
4,553
C#
namespace Gu.Units.Tests.Internals.Parsing { using System.Globalization; public class ErrorCase<T> : SuccessCase<T>, IErrorCase { public ErrorCase(string text, int start, T expected, int expectedEnd, string expectedMessage) : base(text, start, expected, expectedEnd) { this.ExpectedMessage = expectedMessage; } public ErrorCase(string text, CultureInfo cultureInfo, int start, T expected, int expectedEnd, string expectedMessage) : base(text, cultureInfo, start, expected, expectedEnd) { this.ExpectedMessage = expectedMessage; } object IErrorCase.Expected => this.Expected; public string ExpectedMessage { get; } } }
32.608696
126
0.652
[ "MIT" ]
GuOrg/Gu.Units
Gu.Units.Tests/Internals/Parsing/Sources/ErrorCase{T}.cs
752
C#
#region Using directives using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Blazorise.Utils; using Microsoft.AspNetCore.Components; #endregion namespace Blazorise { public partial class Select<TValue> : BaseInputComponent<IReadOnlyList<TValue>> { #region Members private bool multiple; private bool loading; #endregion #region Methods protected override void OnInitialized() { if ( ParentValidation != null ) { if ( Multiple ) { ParentValidation.InitializeInputExpression( SelectedValuesExpression ); } else { ParentValidation.InitializeInputExpression( SelectedValueExpression ); } } base.OnInitialized(); } protected override void BuildClasses( ClassBuilder builder ) { builder.Append( ClassProvider.Select() ); builder.Append( ClassProvider.SelectMultiple(), Multiple ); builder.Append( ClassProvider.SelectSize( Size ), Size != Size.None ); builder.Append( ClassProvider.SelectValidation( ParentValidation?.Status ?? ValidationStatus.None ), ParentValidation?.Status != ValidationStatus.None ); base.BuildClasses( builder ); } protected Task OnChangeHandler( ChangeEventArgs e ) { return CurrentValueHandler( e?.Value?.ToString() ); } protected override Task OnInternalValueChanged( IReadOnlyList<TValue> value ) { if ( Multiple ) return SelectedValuesChanged.InvokeAsync( value ); else return SelectedValueChanged.InvokeAsync( value == null ? default : value.FirstOrDefault() ); } protected override object PrepareValueForValidation( IReadOnlyList<TValue> value ) { if ( Multiple ) return value; else return value == null ? default : value.FirstOrDefault(); } protected override async Task<ParseValue<IReadOnlyList<TValue>>> ParseValueFromStringAsync( string value ) { if ( string.IsNullOrEmpty( value ) ) return ParseValue<IReadOnlyList<TValue>>.Empty; if ( Multiple ) { // when multiple selection is enabled we need to use javascript to get the list of selected items var multipleValues = await JSRunner.GetSelectedOptions<TValue>( ElementId ); return new ParseValue<IReadOnlyList<TValue>>( true, multipleValues, null ); } else { if ( Converters.TryChangeType<TValue>( value, out var result ) ) { return new ParseValue<IReadOnlyList<TValue>>( true, new TValue[] { result }, null ); } else { return ParseValue<IReadOnlyList<TValue>>.Empty; } } } protected override string FormatValueAsString( IReadOnlyList<TValue> value ) { if ( value == null || value.Count == 0 ) return string.Empty; if ( Multiple ) { return string.Empty; } else { if ( value[0] == null ) return string.Empty; return value[0].ToString(); } } public bool ContainsValue( TValue value ) { var currentValue = CurrentValue; if ( currentValue != null ) { var result = currentValue.Any( x => EqualityComparer<TValue>.Default.Equals( x, value ) ); return result; } return false; } #endregion #region Properties public override object ValidationValue { get { if ( Multiple ) return InternalValue; else return InternalValue == null ? default : InternalValue.FirstOrDefault(); } } protected override IReadOnlyList<TValue> InternalValue { get => Multiple ? SelectedValues : new TValue[] { SelectedValue }; set { if ( Multiple ) { SelectedValues = value; } else { SelectedValue = value == null ? default : value.FirstOrDefault(); } } } /// <summary> /// Specifies that multiple items can be selected. /// </summary> [Parameter] public bool Multiple { get => multiple; set { multiple = value; DirtyClasses(); } } /// <summary> /// Gets or sets the selected item value. /// </summary> [Parameter] public TValue SelectedValue { get; set; } /// <summary> /// Gets or sets the multiple selected item values. /// </summary> [Parameter] public IReadOnlyList<TValue> SelectedValues { get; set; } /// <summary> /// Occurs when the selected item value has changed. /// </summary> [Parameter] public EventCallback<TValue> SelectedValueChanged { get; set; } /// <summary> /// Occurs when the selected items value has changed (only when <see cref="Multiple"/>==true). /// </summary> [Parameter] public EventCallback<IReadOnlyList<TValue>> SelectedValuesChanged { get; set; } /// <summary> /// Gets or sets an expression that identifies the selected value. /// </summary> [Parameter] public Expression<Func<TValue>> SelectedValueExpression { get; set; } /// <summary> /// Specifies how many options should be shown at once. /// </summary> [Parameter] public int? MaxVisibleItems { get; set; } /// <summary> /// Gets or sets an expression that identifies the selected value. /// </summary> [Parameter] public Expression<Func<IReadOnlyList<TValue>>> SelectedValuesExpression { get; set; } /// <summary> /// Gets or sets loading property. /// </summary> [Parameter] public bool Loading { get => loading; set { loading = value; Disabled = value; } } /// <summary> /// Gets or sets loading property. /// </summary> [Parameter] public bool AllowClear { get; set; } #endregion } }
29.944681
165
0.523376
[ "MIT" ]
akusmin/Blazorise
Source/Blazorise/Select.razor.cs
7,039
C#
// Licensed under the MIT License. // Copyright (c) Microsoft Corporation. All rights reserved. using System.Collections.Generic; using System.Runtime.CompilerServices; using AdaptiveExpressions; using Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions; using Microsoft.Bot.Connector; using Newtonsoft.Json; namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Teams.Conditions { /// <summary> /// Actions triggered when a Teams InvokeActivity is received for 'actionableMessage/executeAction'. /// </summary> public class OnTeamsO365ConnectorCardAction : OnInvokeActivity { [JsonProperty("$kind")] public new const string Kind = "Teams.OnO365ConnectorCardAction"; [JsonConstructor] public OnTeamsO365ConnectorCardAction(List<Dialog> actions = null, string condition = null, [CallerFilePath] string callerPath = "", [CallerLineNumber] int callerLine = 0) : base(actions: actions, condition: condition, callerPath: callerPath, callerLine: callerLine) { } /// <inheritdoc/> protected override Expression CreateExpression() { // if name is 'actionableMessage/executeAction' return Expression.AndExpression(Expression.Parse($"{TurnPath.Activity}.ChannelId == '{Channels.Msteams}' && {TurnPath.Activity}.name == 'actionableMessage/executeAction'"), base.CreateExpression()); } } }
40.457143
210
0.711864
[ "MIT" ]
Robulane/botbuilder-dotnet
libraries/Microsoft.Bot.Builder.Dialogs.Adaptive.Teams/TriggerConditions/OnTeamsO365ConnectorCardAction.cs
1,418
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.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; namespace Benchmarks { public class Program { public static Task Main(string[] args) { return GetHostBuilder(args).Build().RunAsync(); } public static IHostBuilder GetHostBuilder(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .AddEnvironmentVariables(prefix: "RoutingBenchmarks_") .Build(); // Consoler logger has a major impact on perf results, so do not use // default builder. var hostBuilder = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel() .UseTestServer() .UseConfiguration(config); }); var scenario = config["scenarios"]?.ToLowerInvariant(); if (scenario == "plaintextdispatcher" || scenario == "plaintextendpointrouting") { hostBuilder.ConfigureWebHost(webHostBuilder => { webHostBuilder .UseStartup<StartupUsingEndpointRouting>() // for testing .UseSetting("Startup", nameof(StartupUsingEndpointRouting)); }); } else if (scenario == "plaintextrouting" || scenario == "plaintextrouter") { hostBuilder.ConfigureWebHost(webHostBuilder => { webHostBuilder .UseStartup<StartupUsingRouter>() // for testing .UseSetting("Startup", nameof(StartupUsingRouter)); }); } else { throw new InvalidOperationException( $"Invalid scenario '{scenario}'. Allowed scenarios are PlaintextEndpointRouting and PlaintextRouter"); } return hostBuilder; } } }
35.228571
122
0.532036
[ "Apache-2.0" ]
1175169074/aspnetcore
src/Http/Routing/test/testassets/Benchmarks/Program.cs
2,466
C#
namespace AngularProject1.Api.Configuration { public interface IApiConfiguration { string GetAzureConnectionString(); } }
20.285714
44
0.71831
[ "MIT" ]
bogdanpolak/weather-angular-netcore
AngularAPI/Api/Configuration/IApiConfiguration.cs
144
C#
using NBitcoin; using Newtonsoft.Json; namespace Stratis.Bitcoin.Features.Wallet.Models { public class AddressBalanceModel { [JsonProperty(PropertyName = "address")] public string Address { get; set; } [JsonProperty(PropertyName = "coinType")] public CoinType CoinType { get; set; } [JsonProperty(PropertyName = "amountConfirmed")] public Money AmountConfirmed { get; set; } [JsonProperty(PropertyName = "amountUnconfirmed")] public Money AmountUnconfirmed { get; set; } } }
26.47619
58
0.660072
[ "MIT" ]
AI-For-Rural/EXOSFullNode
src/Stratis.Bitcoin.Features.Wallet/Models/AddressBalanceModel.cs
558
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Org.BouncyCastle.Asn1; using Xky.Core.Model; namespace Xky.Core { /// <summary> /// 脚本引擎 /// </summary> public class Script { private readonly Device _device; /// <summary> /// 脚本引擎 /// </summary> /// <param name="device"></param> public Script(Device device) { _device = device; } /// <summary> /// 弹出toast提示框 /// </summary> /// <param name="toast">提示内容</param> /// <param name="style">风格</param> /// <returns></returns> public Response Toast(string toast, int style = 2) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "toast", new JArray(toast, style)); } /// <summary> /// 在设备外部执行adb指令 /// </summary> /// <param name="command"></param> /// <returns></returns> public Response AdbCommand(string command) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "adbCommand", new JArray(command)); } /// <summary> /// 在设备内部执行adb指令 /// </summary> /// <param name="command"></param> /// <returns></returns> public Response AdbShell(string command) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "adbShell", new JArray(command)); } /// <summary> /// 查找当前设备 /// </summary> /// <returns></returns> public Response FindMe() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "findMe", new JArray()); } /// <summary> /// 唤醒当前设备 /// </summary> /// <returns></returns> public Response WakeUp() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "wakeup", new JArray()); } /// <summary> /// 锁屏当前设备 /// </summary> /// <returns></returns> public Response LockScreen() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "lockScreen", new JArray()); } /// <summary> /// 重启app /// </summary> /// <param name="package">app包名</param> /// <returns></returns> public Response RestartApp(string package) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "restartApp", new JArray(package)); } /// <summary> /// 获取版本号 /// </summary> /// <param name="package"></param> /// <returns></returns> public Response GetAppVersion(string package) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "getAppVersion", new JArray(package)); } /// <summary> /// 结束app /// </summary> /// <param name="package">app包名</param> /// <returns></returns> public Response KillApp(string package) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "killApp", new JArray(package)); } /// <summary> /// 清空app(相当于重装) /// </summary> /// <param name="package">app包名</param> /// <returns></returns> public Response ClearApp(string package) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "clearApp", new JArray(package)); } /// <summary> /// 从url地址安装apk /// </summary> /// <param name="url">远程url地址</param> /// <returns></returns> public Response InstallApkFromUrl(string url) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "installApkFromUrl", new JArray(url)); } /// <summary> /// 查找所有UI元素 /// </summary> /// <returns></returns> public Response FindAllUiObject() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "findAllUiObject", new JArray()); } /// <summary> /// 查找界面元素 /// </summary> /// <param name="name">查找条件</param> /// <param name="option">可选条件:{"regex":false,"timeout":10}</param> /// <returns></returns> public Response FindUiObjects(string name, JObject option=null) { if(option==null) option=new JObject(); return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "findUiObjects", new JArray(name, option)); } /// <summary> /// 查找界面元素并点击它 /// </summary> /// <param name="name">查找条件</param> /// <param name="option">可选条件:{"regex":false,"timeout":10,"index":0}</param> /// <returns></returns> public Response FindAndClick(string name, JObject option=null) { if (option == null) option = new JObject(); return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "findAndClick", new JArray(name, option)); } /// <summary> /// 查找界面元素并给它赋值 /// </summary> /// <param name="name">查找条件</param> /// <param name="value">赋值内容</param> /// <param name="option">可选条件:{"regex":false,"timeout":10,"index":0}</param> /// <returns></returns> public Response FindAndInput(string name, string value, JObject option=null) { if (option == null) option = new JObject(); return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "findAndInput", new JArray(name, value, option)); } /// <summary> /// 输入文本 /// </summary> /// <param name="text">文本内容</param> /// <returns></returns> public Response Input(string text) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "input", new JArray(text)); } /// <summary> /// 点击指定位置 /// </summary> /// <param name="x">x坐标(0-1范围)</param> /// <param name="y">y坐标(0-1范围)</param> /// <returns></returns> public Response Click(double x, double y) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "click", new JArray(x, y)); } /// <summary> /// 按下指定位置 /// </summary> /// <param name="x">x坐标(0-1范围)</param> /// <param name="y">y坐标(0-1范围)</param> /// <returns></returns> public Response MouseDown(double x, double y) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "mousedown", new JArray(x, y)); } /// <summary> /// 释放指定位置 /// </summary> /// <param name="x">x坐标(0-1范围)</param> /// <param name="y">y坐标(0-1范围)</param> /// <returns></returns> public Response MouseUp(double x, double y) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "mouseup", new JArray(x, y)); } /// <summary> /// 拖动指定位置 /// </summary> /// <param name="x">x坐标(0-1范围)</param> /// <param name="y">y坐标(0-1范围)</param> /// <returns></returns> public Response MouseDrag(double x, double y) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "mousedrag", new JArray(x, y)); } /// <summary> /// 滑动指定位置 /// </summary> /// <param name="startx">滑动起始坐标x(0-1范围)</param> /// <param name="starty">滑动起始坐标y(0-1范围)</param> /// <param name="endx">滑动终点坐标x(0-1范围)</param> /// <param name="endy">滑动终点坐标y(0-1范围)</param> /// <param name="steps">滑动步数(默认10)</param> /// <returns></returns> public Response Swipe(double startx = 0.5, double starty = 0.8, double endx = 0.5, double endy = 0.2, double steps = 10) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "swipe", new JArray(startx, starty, endx, endy, steps)); } /// <summary> /// 滚动 /// </summary> /// <param name="x">滚动起始坐标x(0-1范围)</param> /// <param name="y">滚动起始坐标y(0-1范围)</param> /// <param name="updown">上下滚动量</param> /// <param name="leftright">左右滚动量</param> /// <returns></returns> public Response Wheel(double x, double y, int updown = 0, int leftright = 0) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "wheel", new JArray(x, y, updown, leftright)); } /// <summary> /// 按下并释放按键 /// </summary> /// <param name="keycode">安卓按键代码</param> /// <returns></returns> public Response PressKey(int keycode) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "pressKey", new JArray(keycode)); } /// <summary> /// 发送编辑器动作 /// </summary> /// <param name="actioncode">动作代码</param> /// <returns></returns> public Response SendEditorAction(int actioncode) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "sendEditorAction", new JArray(actioncode)); } /// <summary> /// 剪切 /// </summary> /// <returns></returns> public Response Cut() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "cut", new JArray()); } /// <summary> /// 复制 /// </summary> /// <returns></returns> public Response Copy() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "copy", new JArray()); } /// <summary> /// 粘贴 /// </summary> /// <returns></returns> public Response Paste() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "paste", new JArray()); } /// <summary> /// 设置剪贴板 /// </summary> /// <param name="value">剪贴板内容</param> /// <returns></returns> public Response SetClipboardText(string value) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "setClipboardText", new JArray(value)); } /// <summary> /// 读取剪贴板 /// </summary> /// <returns></returns> public Response GetClipboardText() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "getClipboardText", new JArray()); } /// <summary> /// 设置输入法为X输入法 /// </summary> /// <returns></returns> public Response SetInputMethod() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "setInputMethod", new JArray()); } /// <summary> /// 显示输入法选择框 /// </summary> /// <returns></returns> public Response ShowInputMethod() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "showInputMethod", new JArray()); } /// <summary> /// 写入文本到设备上 /// </summary> /// <param name="path"></param> /// <param name="str"></param> /// <returns></returns> public Response WriteStringToFile(string path, string str) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "writeStringToFile", new JArray(path, str)); } /// <summary> /// 把二进制数组写入设备 /// </summary> /// <param name="path"></param> /// <param name="data"></param> /// <returns></returns> public Response WriteBufferToFile(string path, byte[] data) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "writeBufferToFile2", new JArray(path, data)); } /// <summary> /// 从设备读取二进制数据 /// </summary> /// <param name="path"></param> /// <returns></returns> public Response ReadBufferFromFile(string path) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "readBufferFromFile", new JArray(path)); } /// <summary> /// 读取设备上的目录信息 /// </summary> /// <param name="path"></param> /// <returns></returns> public Response ReadDir(string path) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "readDir", new JArray(path)); } /// <summary> /// 创建一个新的硬件全息信息 /// </summary> /// <param name="model">指定型号</param> /// <returns></returns> public Response CreateHardware(string model = null) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "createHardware", new JArray(model)); } /// <summary> /// 还原一个硬件全息信息 /// </summary> /// <param name="key">硬件key</param> /// <returns></returns> public Response RestoreHardware(string key) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "restoreHardware", new JArray(key)); } /// <summary> /// 读取当前设备的硬件全息key /// </summary> /// <returns></returns> public Response GetHardwareKey() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "getHardwareKey", new JArray()); } /// <summary> /// 获取当前设备的快照信息 /// </summary> /// <param name="packagename">包名</param> /// <returns></returns> public Response GetCurrentAppSnapshot(string packagename) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "getCurrentAppSnapshot", new JArray(packagename)); } /// <summary> /// 创建全息快照插槽 /// </summary> /// <param name="packageName">包名</param> /// <param name="name">快照名</param> /// <param name="basepath">基础地址(默认:/data/AppSnapshot/))</param> /// <returns></returns> public Response CreateAppSnapshot(string packageName, string name, string basepath = null) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "createAppSnapshot", new JArray(packageName, name, basepath)); } /// <summary> /// 切换全息快照插槽 /// </summary> /// <param name="packageName">包名</param> /// <param name="name">快照名</param> /// <param name="basepath">基础地址(默认:/data/AppSnapshot/))</param> /// <returns></returns> public Response SetAppSnapshot(string packageName, string name, string basepath = null) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "setAppSnapshot", new JArray(packageName, name, basepath)); } /// <summary> /// 删除全息快照插槽 /// </summary> /// <param name="packageName">包名</param> /// <param name="name">快照名</param> /// <param name="basepath">基础地址(默认:/data/AppSnapshot/))</param> /// <returns></returns> public Response DelAppSnapshot(string packageName, string name, string basepath = null) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "delAppSnapshot", new JArray(packageName, name, basepath)); } /// <summary> /// 获取全息快照插槽列表 /// </summary> /// <param name="packageName">包名</param> /// <param name="basepath">基础地址(默认:/data/AppSnapshot/))</param> /// <returns></returns> public Response GetAppSnapshotList(string packageName, string basepath = null) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "getAppSnapshotList", new JArray(packageName, basepath)); } /// <summary> /// 设置定位坐标 /// </summary> /// <param name="location">坐标,如:22.517631,114.071045</param> /// <returns></returns> public Response SetLocation(string location) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "setLocation", new JArray(location)); } /// <summary> /// 读取当前定位坐标 /// </summary> /// <returns></returns> public Response GetLocation() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "getLocation", new JArray()); } /// <summary> /// 通过远程图片url更新摄像头内容 /// </summary> /// <param name="url">图片url地址</param> /// <returns></returns> public Response UpdateCameraFromUrl(string url) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "updateCameraFromUrl", new JArray(url)); } /// <summary> /// 通过二进制图片数据更新摄像头内容 /// </summary> /// <param name="data">图片二进制</param> /// <returns></returns> public Response UpdateCameraFromFile(byte[] data) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "updateCameraFromFile", new JArray(Convert.ToBase64String(data))); } /// <summary> /// 将文本内容保存为二维码更新摄像头内容 /// </summary> /// <param name="text">二维码文本</param> /// <returns></returns> public Response UpdateCameraFromText(string text) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "updateCameraFromText", new JArray(text)); } /// <summary> /// 更新摄像头 /// </summary> /// <param name="data">图片数据</param> /// <returns></returns> public Response UpdateCamera(byte[] data) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "updateCamera", new JArray(data)); } /// <summary> /// 获取联系人列表 /// </summary> /// <returns></returns> public Response GetContacts() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "getContacts", new JArray()); } /// <summary> /// 插入联系人列表 /// </summary> /// <param name="contacts"></param> /// <returns></returns> public Response InsertContacts(JArray contacts) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "insertContacts", contacts); } /// <summary> /// 清空联系人 /// </summary> /// <returns></returns> public Response ClearContacts() { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "clearContacts", new JArray()); } /// <summary> /// 插入媒体库 /// </summary> /// <param name="path"> 媒体文件路径(在设备上的路径,非本地)</param> /// <returns></returns> public Response InsertMedia(string path) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "insertMedia", new JArray(path)); } /// <summary> /// 清空媒体库 /// </summary> /// <param name="path">媒体库路径(默认:/sdcard/DCIM)</param> /// <returns></returns> public Response ClearDcim(string path = "/sdcard/DCIM") { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "clearDCIM", new JArray(path)); } /// <summary> /// 调用第三方接口 /// </summary> /// <param name="name">接口名称</param> /// <param name="option">参数</param> /// <returns></returns> public Response CallApi(string name, JObject option) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "callEvent", new JArray(name, option)); } #region 插槽相关 /// <summary> /// 获取插槽信息 /// </summary> /// <param name="packageName"></param> /// <returns></returns> public Response GetSlot(string packageName) { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "getSlot", new JArray(packageName)); } /// <summary> /// 创建插槽 /// </summary> /// <param name="packageName"></param> /// <param name="name"></param> /// <param name="basePath"></param> /// <returns></returns> public Response CreateSlot(string packageName, string name, string basePath = "/data/AppSlot/") { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "createSlot", new JArray(packageName, name, basePath)); } /// <summary> /// 设置切换插槽 /// </summary> /// <param name="packageName"></param> /// <param name="name"></param> /// <param name="basePath"></param> /// <returns></returns> public Response SetSlot(string packageName, string name, string basePath = "/data/AppSlot/") { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "setSlot", new JArray(packageName, name, basePath)); } /// <summary> /// 删除插槽 /// </summary> /// <param name="packageName"></param> /// <param name="name"></param> /// <param name="basePath"></param> /// <returns></returns> public Response DelSlot(string packageName, string name, string basePath = "/data/AppSlot/") { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "delSlot", new JArray(packageName, name, basePath)); } /// <summary> /// 获取插槽列表 /// </summary> /// <param name="packageName">包名</param> /// <param name="basePath">原始路径</param> /// <returns></returns> public Response GetSlotList(string packageName, string basePath = "/data/AppSlot/") { return Client.CallNodeApi(_device.NodeSerial, _device.Sn, "getSlotList", new JArray(packageName, basePath)); } #endregion } }
31.707928
114
0.514256
[ "Apache-2.0" ]
snowsylar/waterwheel-frontend
Xky.Core/Script.cs
24,276
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 mgn-2020-02-26.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.Mgn.Model { /// <summary> /// This is the response object from the UpdateLaunchConfiguration operation. /// </summary> public partial class UpdateLaunchConfigurationResponse : AmazonWebServiceResponse { private bool? _copyPrivateIp; private bool? _copyTags; private string _ec2LaunchTemplateID; private LaunchDisposition _launchDisposition; private Licensing _licensing; private string _name; private string _sourceServerID; private TargetInstanceTypeRightSizingMethod _targetInstanceTypeRightSizingMethod; /// <summary> /// Gets and sets the property CopyPrivateIp. /// <para> /// Copy Private IP during Launch Configuration. /// </para> /// </summary> public bool CopyPrivateIp { get { return this._copyPrivateIp.GetValueOrDefault(); } set { this._copyPrivateIp = value; } } // Check to see if CopyPrivateIp property is set internal bool IsSetCopyPrivateIp() { return this._copyPrivateIp.HasValue; } /// <summary> /// Gets and sets the property CopyTags. /// <para> /// Copy Tags during Launch Configuration. /// </para> /// </summary> public bool CopyTags { get { return this._copyTags.GetValueOrDefault(); } set { this._copyTags = value; } } // Check to see if CopyTags property is set internal bool IsSetCopyTags() { return this._copyTags.HasValue; } /// <summary> /// Gets and sets the property Ec2LaunchTemplateID. /// <para> /// Configure EC2 lauch configuration template ID. /// </para> /// </summary> [AWSProperty(Min=0, Max=256)] public string Ec2LaunchTemplateID { get { return this._ec2LaunchTemplateID; } set { this._ec2LaunchTemplateID = value; } } // Check to see if Ec2LaunchTemplateID property is set internal bool IsSetEc2LaunchTemplateID() { return this._ec2LaunchTemplateID != null; } /// <summary> /// Gets and sets the property LaunchDisposition. /// <para> /// Configure launch dispostion for launch configuration. /// </para> /// </summary> public LaunchDisposition LaunchDisposition { get { return this._launchDisposition; } set { this._launchDisposition = value; } } // Check to see if LaunchDisposition property is set internal bool IsSetLaunchDisposition() { return this._launchDisposition != null; } /// <summary> /// Gets and sets the property Licensing. /// <para> /// Configure launch configuration OS licensing. /// </para> /// </summary> public Licensing Licensing { get { return this._licensing; } set { this._licensing = value; } } // Check to see if Licensing property is set internal bool IsSetLicensing() { return this._licensing != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// Configure launch configuration name. /// </para> /// </summary> [AWSProperty(Min=0, Max=128)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property SourceServerID. /// <para> /// Configure launch configuration Source Server ID. /// </para> /// </summary> [AWSProperty(Min=19, Max=19)] public string SourceServerID { get { return this._sourceServerID; } set { this._sourceServerID = value; } } // Check to see if SourceServerID property is set internal bool IsSetSourceServerID() { return this._sourceServerID != null; } /// <summary> /// Gets and sets the property TargetInstanceTypeRightSizingMethod. /// <para> /// Configure launch configuration Target instance type right sizing method. /// </para> /// </summary> public TargetInstanceTypeRightSizingMethod TargetInstanceTypeRightSizingMethod { get { return this._targetInstanceTypeRightSizingMethod; } set { this._targetInstanceTypeRightSizingMethod = value; } } // Check to see if TargetInstanceTypeRightSizingMethod property is set internal bool IsSetTargetInstanceTypeRightSizingMethod() { return this._targetInstanceTypeRightSizingMethod != null; } } }
30.963731
101
0.590529
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Mgn/Generated/Model/UpdateLaunchConfigurationResponse.cs
5,976
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Internal.Runtime; using Internal.Text; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { public class ReadyToRunHeaderNode : ObjectNode, ISymbolDefinitionNode { struct HeaderItem { public HeaderItem(ReadyToRunSectionType id, ObjectNode node, ISymbolNode startSymbol, ISymbolNode endSymbol) { Id = id; Node = node; StartSymbol = startSymbol; EndSymbol = endSymbol; } readonly public ReadyToRunSectionType Id; readonly public ObjectNode Node; readonly public ISymbolNode StartSymbol; readonly public ISymbolNode EndSymbol; } List<HeaderItem> _items = new List<HeaderItem>(); TargetDetails _target; public ReadyToRunHeaderNode(TargetDetails target) { _target = target; } public void Add(ReadyToRunSectionType id, ObjectNode node, ISymbolNode startSymbol, ISymbolNode endSymbol = null) { _items.Add(new HeaderItem(id, node, startSymbol, endSymbol)); } public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix); sb.Append("__ReadyToRunHeader"); } public int Offset => 0; public override bool IsShareable => false; protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public override bool StaticDependenciesAreComputed => true; public override ObjectNodeSection Section { get { if (_target.IsWindows) return ObjectNodeSection.ReadOnlyDataSection; else return ObjectNodeSection.DataSection; } } public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); builder.RequireInitialPointerAlignment(); builder.AddSymbol(this); // Don't bother sorting if we're not emitting the contents if (!relocsOnly) _items.Sort((x, y) => Comparer<int>.Default.Compare((int)x.Id, (int)y.Id)); // ReadyToRunHeader.Magic builder.EmitInt((int)(ReadyToRunHeaderConstants.Signature)); // ReadyToRunHeader.MajorVersion builder.EmitShort((short)(ReadyToRunHeaderConstants.CurrentMajorVersion)); builder.EmitShort((short)(ReadyToRunHeaderConstants.CurrentMinorVersion)); // ReadyToRunHeader.Flags builder.EmitInt(0); // ReadyToRunHeader.NumberOfSections var sectionCountReservation = builder.ReserveShort(); // ReadyToRunHeader.EntrySize builder.EmitByte((byte)(8 + 2 * factory.Target.PointerSize)); // ReadyToRunHeader.EntryType builder.EmitByte(1); int count = 0; foreach (var item in _items) { // Skip empty entries if (!relocsOnly && item.Node.ShouldSkipEmittingObjectNode(factory)) continue; builder.EmitInt((int)item.Id); ModuleInfoFlags flags = 0; if (item.EndSymbol != null) { flags |= ModuleInfoFlags.HasEndPointer; } builder.EmitInt((int)flags); builder.EmitPointerReloc(item.StartSymbol); if (item.EndSymbol != null) { builder.EmitPointerReloc(item.EndSymbol); } else { builder.EmitZeroPointer(); } count++; } builder.EmitShort(sectionCountReservation, checked((short)count)); return builder.ToObjectData(); } public override int ClassCode => -534800244; } }
32.609023
121
0.584044
[ "MIT" ]
333fred/runtime
src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReadyToRunHeaderNode.cs
4,337
C#
// Copyright © 2020 Vera@Versus. All rights reserved. Licensed under the MIT License. namespace AnnoSerializer.Serialization.Core { public enum CompressionTypes { None, Zlib } }
21.333333
86
0.729167
[ "MIT" ]
Veraatversus/AnnoSavegameViewer
src/AnnoSerializer/Serialization/Core/CompressionTypes.cs
195
C#
using System; using System.Collections.Generic; using System.Text; namespace ZCore.Util { class StringExtensions { } }
13
34
0.657343
[ "MIT" ]
winkedev/CoreProject
ZCore/Util/StringExtensions.cs
145
C#
using System; using System.Threading.Tasks; namespace Owin.Security.Providers.GitHub { /// <summary> /// Default <see cref="IGitHubAuthenticationProvider"/> implementation. /// </summary> public class GitHubAuthenticationProvider : IGitHubAuthenticationProvider { /// <summary> /// Initializes a <see cref="GitHubAuthenticationProvider"/> /// </summary> public GitHubAuthenticationProvider() { OnAuthenticated = context => Task.FromResult<object>(null); OnReturnEndpoint = context => Task.FromResult<object>(null); } /// <summary> /// Gets or sets the function that is invoked when the Authenticated method is invoked. /// </summary> public Func<GitHubAuthenticatedContext, Task> OnAuthenticated { get; set; } /// <summary> /// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked. /// </summary> public Func<GitHubReturnEndpointContext, Task> OnReturnEndpoint { get; set; } /// <summary> /// Invoked whenever GitHub succesfully authenticates a user /// </summary> /// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param> /// <returns>A <see cref="Task"/> representing the completed operation.</returns> public virtual Task Authenticated(GitHubAuthenticatedContext context) { return OnAuthenticated(context); } /// <summary> /// Invoked prior to the <see cref="System.Security.Claims.ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL. /// </summary> /// <param name="context"></param> /// <returns>A <see cref="Task"/> representing the completed operation.</returns> public virtual Task ReturnEndpoint(GitHubReturnEndpointContext context) { return OnReturnEndpoint(context); } } }
41.74
180
0.644466
[ "MIT" ]
gauravbhavsar/OwinOAuthProviders
Owin.Security.Providers/GitHub/Provider/GitHubAuthenticationProvider.cs
2,089
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** 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.Kubernetes.Types.Inputs.Perf.V1Alpha1 { /// <summary> /// A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. /// </summary> public class Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsArgs : Pulumi.ResourceArgs { /// <summary> /// key is the label key that the selector applies to. /// </summary> [Input("key", required: true)] public Input<string> Key { get; set; } = null!; /// <summary> /// operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. /// </summary> [Input("operator", required: true)] public Input<string> Operator { get; set; } = null!; [Input("values")] private InputList<string>? _values; /// <summary> /// values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch. /// </summary> public InputList<string> Values { get => _values ?? (_values = new InputList<string>()); set => _values = value; } public Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsArgs() { } } }
40.255319
246
0.674947
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/kubestone/dotnet/Kubernetes/Crds/Operators/Kubestone/Perf/V1Alpha1/Inputs/Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsArgs.cs
1,892
C#
using System; using Serilog; using NBomber.CSharp; using NBomber.Plugins.Http.CSharp; using NBomber.Plugins.Network.Ping; namespace CSharp.HttpTests { // in this example we will log every raquest/response to local log file // in this example we use: // - NBomber.Http (https://nbomber.com/docs/plugins-http) public class TracingHttp { public static void Run() { var step = HttpStep.Create("fetch_html_page", context => Http.CreateRequest("GET", "https://nbomber.com") .WithHeader("Accept", "text/html") ); var scenario = ScenarioBuilder .CreateScenario("nbomber_web_site", step) .WithWarmUpDuration(TimeSpan.FromSeconds(5)) .WithLoadSimulations(new[] { Simulation.KeepConstant(copies: 1, during: TimeSpan.FromSeconds(30)) }); var pingPluginConfig = PingPluginConfig.CreateDefault(new[] {"nbomber.com"}); var pingPlugin = new PingPlugin(pingPluginConfig); NBomberRunner .RegisterScenarios(scenario) .WithPlugins(pingPlugin) .WithTestSuite("http") .WithTestName("tracing_test") .WithLoggerConfig(() => new LoggerConfiguration().MinimumLevel.Verbose()) // set log to verbose .Run(); } } }
33.55814
111
0.579349
[ "Apache-2.0" ]
abenedykt/NBomber
examples/CSharp/HttpTests/TracingHttp.cs
1,443
C#
using ScriptEngine.Machine.Contexts; namespace osf { [ContextClass ("КлФильтрыУведомления", "ClNotifyFilters")] public class ClNotifyFilters : AutoContext<ClNotifyFilters> { private int m_fileName = (int)System.IO.NotifyFilters.FileName; // 1 Имя файла. private int m_directoryName = (int)System.IO.NotifyFilters.DirectoryName; // 2 Имя каталога. private int m_attributes = (int)System.IO.NotifyFilters.Attributes; // 4 Атрибуты файла или каталога. private int m_size = (int)System.IO.NotifyFilters.Size; // 8 Размер файла или каталога. private int m_lastWrite = (int)System.IO.NotifyFilters.LastWrite; // 16 Дата последней записи в файл или каталог. private int m_lastAccess = (int)System.IO.NotifyFilters.LastAccess; // 32 Дата последнего открытия файла или каталога. private int m_creationTime = (int)System.IO.NotifyFilters.CreationTime; // 64 Время создания файла или каталога. private int m_security = (int)System.IO.NotifyFilters.Security; // 256 Параметры безопасности файла или каталога. [ContextProperty("Атрибуты", "Attributes")] public int Attributes { get { return m_attributes; } } [ContextProperty("Безопасность", "Security")] public int Security { get { return m_security; } } [ContextProperty("ВремяСоздания", "CreationTime")] public int CreationTime { get { return m_creationTime; } } [ContextProperty("ИмяКаталога", "DirectoryName")] public int DirectoryName { get { return m_directoryName; } } [ContextProperty("ИмяФайла", "FileName")] public int FileName { get { return m_fileName; } } [ContextProperty("ПоследнийДоступ", "LastAccess")] public int LastAccess { get { return m_lastAccess; } } [ContextProperty("ПоследняяЗапись", "LastWrite")] public int LastWrite { get { return m_lastWrite; } } [ContextProperty("Размер", "Size")] public int Size { get { return m_size; } } } }
33.590909
126
0.624718
[ "MPL-2.0" ]
Nivanchenko/OneScriptForms
OneScriptForms/OneScriptForms/NotifyFilters.cs
2,530
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Security.Cryptography; using System.Collections.Specialized; using System.Text.RegularExpressions; namespace WzComparerR2.WzLib { public class Wz_Crypto { public Wz_Crypto() { this.keys_bms = new Wz_CryptoKey(iv_bms); this.keys_kms = new Wz_CryptoKey(iv_kms); this.keys_gms = new Wz_CryptoKey(iv_gms); this.listwz = false; this.EncType = Wz_CryptoKeyType.Unknown; this.List = new StringCollection(); } public void Reset() { this.encryption_detected = false; this.listwz = false; this.EncType = Wz_CryptoKeyType.Unknown; this.List.Clear(); } public bool list_contains(string name) { bool contains = this.List.Contains(name); if (contains) this.List.Remove(name); return contains; // foreach (string list_entry in this.list) // { // // if (list_entry.Contains(Name)) // if (list_entry == Name) // { // this.list.Remove(list_entry); // return true; // } // } // return false; } public void LoadListWz(string path) { path = Path.Combine(path, "List.wz"); if (File.Exists(path)) { this.listwz = true; using (FileStream list_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader listwz = new BinaryReader(list_file); int length = (int)list_file.Length; int len = 0; byte b = 0; string folder = ""; list_file.Position += 4; byte check_for_d = listwz.ReadByte(); if ((char)(check_for_d ^ this.keys_gms[0]) == 'd') { this.EncType = Wz_CryptoKeyType.GMS; } else if ((char)(check_for_d ^ this.keys_kms[0]) == 'd') { this.EncType = Wz_CryptoKeyType.KMS; } list_file.Position = 0; while (list_file.Position < length) { len = listwz.ReadInt32() * 2; for (int i = 0; i < len; i += 2) { b = (byte)(listwz.ReadByte() ^ this.keys[i]); folder += (char)(b); list_file.Position++; } list_file.Position += 2; folder.Replace(".im/", ".img"); this.List.Add(folder); folder = ""; } this.List.Remove("dummy"); } } } public void DetectEncryption(Wz_File f) { int old_off = (int)f.FileStream.Position; f.FileStream.Position = f.Header.DataStartPosition; if (f.ReadInt32() <= 0) //只有文件头 无法预判 { return; } f.FileStream.Position++; int len = (int)(-f.BReader.ReadSByte()); byte[] bytes = f.BReader.ReadBytes(len); for (int i = 0; i < len; i++) { bytes[i] ^= (byte)(0xAA + i); } StringBuilder sb = new StringBuilder(); if (!this.encryption_detected) { //测试bms sb.Clear(); for (int i = 0; i < len; i++) { sb.Append((char)(keys_bms[i] ^ bytes[i])); } if (IsLegalNodeName(sb.ToString())) { this.EncType = Wz_CryptoKeyType.BMS; this.encryption_detected = true; goto lbl_end; } //测试kms sb.Clear(); for (int i = 0; i < len; i++) { sb.Append((char)(keys_kms[i] ^ bytes[i])); } if (IsLegalNodeName(sb.ToString())) { this.EncType = Wz_CryptoKeyType.KMS; this.encryption_detected = true; goto lbl_end; } //测试gms sb.Clear(); for (int i = 0; i < len; i++) { sb.Append((char)(keys_gms[i] ^ bytes[i])); } if (IsLegalNodeName(sb.ToString())) { this.EncType = Wz_CryptoKeyType.GMS; this.encryption_detected = true; goto lbl_end; } } lbl_end: f.FileStream.Position = old_off; } private bool IsLegalNodeName(string nodeName) { return nodeName.EndsWith(".img") || Regex.IsMatch(nodeName, @"^[A-Za-z-9_]+$"); } static readonly byte[] iv_gms = { 0x4d, 0x23, 0xc7, 0x2b }; static readonly byte[] iv_kms = { 0xb9, 0x7d, 0x63, 0xe9 }; static readonly byte[] iv_bms = { 0x00, 0x00, 0x00, 0x00 }; private Wz_CryptoKey keys_bms, keys_gms, keys_kms; private Wz_CryptoKeyType enc_type; public bool encryption_detected = false; public bool listwz = false; public Wz_CryptoKey keys { get; private set; } public StringCollection List { get; private set; } public Wz_CryptoKeyType EncType { get { return enc_type; } set { enc_type = value; switch (enc_type) { case Wz_CryptoKeyType.Unknown: this.keys = null; break; case Wz_CryptoKeyType.BMS: this.keys = keys_bms; break; case Wz_CryptoKeyType.KMS: this.keys = keys_kms; break; case Wz_CryptoKeyType.GMS: this.keys = keys_gms; break; } } } public enum Wz_CryptoKeyType { Unknown = 0, BMS = 1, KMS = 2, GMS = 3 } public class Wz_CryptoKey { public Wz_CryptoKey(byte[] iv) { this.iv = iv; if (iv == null || BitConverter.ToInt32(iv, 0) == 0) { this.isEmptyIV = true; } } private byte[] keys; private byte[] iv; private bool isEmptyIV; public byte this[int index] { get { if (isEmptyIV) { return 0; } if (keys == null || keys.Length <= index) { EnsureKeySize(index + 1); } return this.keys[index]; } } public void EnsureKeySize(int size) { if (isEmptyIV) { return; } if (this.keys != null && this.keys.Length >= size) { return; } size = (int)Math.Ceiling(1.0 * size / 4096) * 4096; int startIndex = 0; if (this.keys == null) { keys = new byte[size]; } else { startIndex = this.keys.Length; Array.Resize(ref this.keys, size); } Rijndael aes = Rijndael.Create(); aes.KeySize = 256; aes.BlockSize = 128; aes.Key = aesKey; aes.Mode = CipherMode.ECB; MemoryStream ms = new MemoryStream(keys, startIndex, keys.Length - startIndex, true); CryptoStream s = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write); for (int i = startIndex; i < size; i += 16) { if (i == 0) { byte[] block = new byte[16]; for (int j = 0; j < block.Length; j++) { block[j] = iv[j % 4]; } s.Write(block, 0, block.Length); } else { s.Write(keys, i - 16, 16); } } s.Flush(); ms.Close(); } public unsafe void Decrypt(byte[] buffer, int startIndex, int length) { if (isEmptyIV) return; this.EnsureKeySize(length); fixed (byte* pBuffer = buffer, pKeys = this.keys) { int i = 0; byte* pData = pBuffer + startIndex; for (int i1 = length / 4 * 4; i < i1; i += 4, pData += 4) { *((int*)pData) ^= *(int*)(pKeys + i); } for (; i < length; i++, pData++) { *pData ^= *(pKeys + i); } } } static readonly byte[] aesKey = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB4, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0x52, 0x00, 0x00, 0x00 }; } } }
32.124242
115
0.383549
[ "MIT" ]
Atomadeus/WzComparerR2
WzComparerR2.WzLib/Wz_Crypto.cs
10,633
C#
// ReSharper disable CheckNamespace // ReSharper disable ObjectCreationAsStatement // ReSharper disable StringLiteralTypo using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using AM; #nullable enable namespace UnitTests.AM.Collections { [TestClass] public class SpanEnumeratorTest { [TestMethod] public void RefEnumerator_GetEnumerator_1() { int[] array = { 1, 2, 3, 4, 5, 6 }; foreach (ref var item in array.AsRefEnumerable()) { item *= 2; } Assert.AreEqual(2, array[0]); Assert.AreEqual(4, array[1]); Assert.AreEqual(6, array[2]); Assert.AreEqual(8, array[3]); Assert.AreEqual(10, array[4]); Assert.AreEqual(12, array[5]); } [TestMethod] public void RefEnumerator_GetEnumerator_2() { int[] array = Array.Empty<int>(); foreach (ref var item in array.AsRefEnumerable()) { item *= 2; } Assert.AreEqual(0, array.Length); } } }
22.86
61
0.547682
[ "MIT" ]
amironov73/ManagedIrbis5
Source/Tests/UnitTests/Source/AM/Collections/RefEnumeratorTest.cs
1,145
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Blackbird.Stark.Trees; using Blackbird.Stark.Trees.Nodes; namespace Blackbird.Stark.Extensions { public static class TreeExtensions { public static void PrintTree<TK, TV>(this ITree<TK, TV> self) where TK: IComparable<TK> { switch (self) { case AvlTree<TK, TV> avlTree: avlTree.PrintTree(); break; case BinaryTree<TK, TV> binaryTree: binaryTree.PrintTree(); break; case RbTree<TK, TV> rbTree: rbTree.PrintTree(); break; } } public static void PrintTree<TK, TV>(this AvlTree<TK, TV> self) where TK : IComparable<TK> { RenderTree(self._root); } public static void PrintTree<TK, TV>(this BinaryTree<TK, TV> self) where TK : IComparable<TK> { RenderTree(self._root); } public static void PrintTree<TK, TV>(this RbTree<TK, TV> self) where TK : IComparable<TK> { if(self.Count > 0) RenderTree(self._root); else Console.WriteLine("RbTree is empty"); } private static void RenderTree<TK,TV>(BinaryNode<TK,TV> tree) where TK: IComparable<TK> { var map = GenerateLevelMap(tree); var maxLevelHeight = map.Select(x => x.Count).Max(); var str = new List<string>(); for (int i = 0; i < map.Count; i++) { foreach (var node in map[i]) { if(node.IsRoot) str.Add(RenderKey(i,node.Key)); else { var parentKey = RenderKey(i - 1, node.Parent.Key); var parentIndex = str.IndexOf(parentKey); if (node == node.Parent.Right) { str.Insert(parentIndex+1, RenderKey(i, node.Key)); } else { if (node.Parent.HasBothChildren) { if (parentIndex+1 < str.Count && str[parentIndex + 1].StartsWith(i.ToString())) { str.Insert(parentIndex + 2, RenderKey(i, node.Key)); } else { str.Insert(parentIndex + 1, RenderKey(i, node.Key)); } } else { str.Insert(parentIndex+1, RenderKey(i, node.Key)); } } } } } for (int i = 0; i < str.Count; i++) { for (int j = 0; j < str[i].Length; j++) { if (str[i][j] == '╚') { for (int k = i-1; k >= 0; k--) { if (j < str[k].Length) { if (str[k][j] == ' ') { var sb = new StringBuilder(str[k]) {[j] = '║'}; str[k] = sb.ToString(); } else { if (str[k][j] == '╚') { var sb = new StringBuilder(str[k]){[j] = '╠'}; str[k] = sb.ToString(); } break; } } } } } } foreach (var line in str) { Console.WriteLine(line); } } private static string RenderKey<TK>(int level, TK key) where TK : IComparable<TK> { var sb = new StringBuilder(); sb.Append($"{level}:"); if(level > 1) { for (int i = 0; i < level-1; i++) sb.Append(" "); } if (level != 0) { sb.Append("╚═══"); } sb.Append(key); return sb.ToString(); } private static List<List<BinaryNode<TK,TV>>> GenerateLevelMap<TK,TV>(BinaryNode<TK,TV> tree) where TK: IComparable<TK> { var levels = new List<List<BinaryNode<TK,TV>>>(); int currentLevel = 0; levels.Add(new List<BinaryNode<TK,TV>>() {tree}); var isThereUnprocessedNodes = true; while (isThereUnprocessedNodes) { if (levels[currentLevel].All(x => !x.HasChildren)) isThereUnprocessedNodes = false; else { levels.Add(new List<BinaryNode<TK, TV>>()); foreach (var node in levels[currentLevel]) { if (node.HasChildren) { if(node.HasLeftChild) levels[currentLevel+1].Add(node.Left); if(node.HasRightChild) levels[currentLevel+1].Add(node.Right); } } currentLevel++; } } return levels; } } }
35.83432
126
0.356671
[ "MIT" ]
Blackbird-tech/Stark
Blackbird.Stark/Extensions/TreeExtensions.cs
6,072
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MarkupExtension.cs" company="Catel development team"> // Copyright (c) 2008 - 2014 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Windows.Markup { using System; using System.ComponentModel; using Catel.Windows.Threading; #if NETFX_CORE using global::Windows.UI.Xaml; using global::Windows.UI.Xaml.Data; #else using System.Windows; using System.Windows.Data; #endif /// <summary> /// Custom markup extension. /// </summary> public abstract class MarkupExtension : Binding, INotifyPropertyChanged #if !NETFX_CORE , ISupportInitialize #endif { private object _internalBindingValue; /// <summary> /// Initializes a new instance of the <see cref="MarkupExtension"/> class. /// </summary> protected MarkupExtension() { if (CatelEnvironment.IsInDesignMode) { return; } Source = this; Mode = BindingMode.OneWay; Path = new PropertyPath("InternalBindingValue"); #if NETFX_CORE Dispatcher.BeginInvoke(UpdateBinding); #endif } /// <summary> /// Gets or sets the binding value. /// <para /> /// Do not use this property, it's use to set up the binding manually. /// </summary> /// <value>The binding value.</value> public object InternalBindingValue { get { return _internalBindingValue; } set { _internalBindingValue = value; RaisePropertyChanged("InternalBindingValue"); } } #if !NETFX_CORE /// <summary> /// Signals the object that initialization is complete. /// </summary> void ISupportInitialize.EndInit() { UpdateBinding(); } #endif /// <summary> /// Updates the binding. /// </summary> protected void UpdateBinding() { InternalBindingValue = ProvideValue(null); } /// <summary> /// When implemented in a derived class, returns an object that is provided as the value of the target property for this markup extension. /// </summary> /// <param name="serviceProvider">A service provider helper that can provide services for the markup extension.</param> /// <returns>The object value to set on the property where the extension is applied.</returns> public abstract object ProvideValue(IServiceProvider serviceProvider); /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Called when a property has been changed. /// </summary> /// <param name="propertyName">Name of the property.</param> private void RaisePropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } }
30.876106
146
0.538836
[ "MIT" ]
gautamsi/Catel
src/Catel.MVVM/Catel.MVVM.WP80/Windows/Markup/MarkupExtension.cs
3,491
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace AccountStoreTest.UWP { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; Xamarin.Forms.Forms.Init(e); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
37.931373
99
0.623934
[ "Apache-2.0" ]
GMS-online/Xamarin.Auth
samples/bugs-triaging/AccountStore/AccountStoreTest.UWP/App.xaml.cs
3,871
C#
using PnP.Core.Model.Security; using PnP.Core.Services; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; namespace PnP.Core.Model.SharePoint { /// <summary> /// Public interface to define a List object of SharePoint Online /// </summary> [ConcreteType(typeof(List))] public interface IList : IDataModel<IList>, IDataModelGet<IList>, IDataModelLoad<IList>, IDataModelUpdate, IDataModelDelete, IDataModelSupportingGetChanges, IQueryableDataModel { #region Properties /// <summary> /// The Unique ID of the List object /// </summary> Guid Id { get; } /// <summary> /// Gets or sets the list title /// </summary> public string Title { get; set; } /// <summary> /// Gets or sets the description of the list /// </summary> public string Description { get; set; } /// <summary> /// Gets or sets a value that specifies the identifier of the document template for the new list. /// SP REST property name: DocumentTemplateUrl. /// </summary> public string DocumentTemplate { get; set; } /// <summary> /// Gets or sets a value that specifies whether the new list is displayed on the Quick Launch of the site. /// </summary> public bool OnQuickLaunch { get; set; } /// <summary> /// Gets or sets a value that specifies the list server template of the new list. /// https://msdn.microsoft.com/en-us/library/office/microsoft.sharepoint.client.listtemplatetype.aspx /// SP REST property name: BaseTemplate /// </summary> public ListTemplateType TemplateType { get; } /// <summary> /// Gets or sets whether verisioning is enabled on the list /// </summary> public bool EnableVersioning { get; set; } /// <summary> /// Gets or sets whether minor verisioning is enabled on the list /// </summary> public bool EnableMinorVersions { get; set; } /// <summary> /// Gets or sets the DraftVersionVisibility for the list /// </summary> public int DraftVersionVisibility { get; set; } /// <summary> /// Gets or sets whether moderation/content approval is enabled on the list /// </summary> public bool EnableModeration { get; set; } /// <summary> /// Gets the root folder of the list. /// </summary> public IFolder RootFolder { get; } /// <summary> /// Gets or sets the MinorVersionLimit for versioning, just in case it is enabled on the list /// SP REST property name: MajorWithMinorVersionsLimit. /// </summary> public int MinorVersionLimit { get; set; } /// <summary> /// Gets or sets the MinorVersionLimit for verisioning, just in case it is enabled on the list /// SP REST property name: MajorVersionLimit. /// </summary> public int MaxVersionLimit { get; set; } /// <summary> /// Gets or sets whether content types are enabled /// </summary> public bool ContentTypesEnabled { get; set; } /// <summary> /// Gets or sets whether to hide the list /// </summary> public bool Hidden { get; set; } /// <summary> /// Gets or sets whether to force checkout of documents in the library /// </summary> public bool ForceCheckout { get; set; } /// <summary> /// Gets or sets whether attachments are enabled. Defaults to true. /// </summary> public bool EnableAttachments { get; set; } /// <summary> /// Gets or sets whether folder is enabled. Defaults to true. /// </summary> public bool EnableFolderCreation { get; set; } /// <summary> /// Gets or sets the Guid for TemplateFeature /// </summary> public Guid TemplateFeatureId { get; } /// <summary> /// Defines a list of default values for the Fields of the List Instance /// </summary> public Dictionary<string, string> FieldDefaults { get; } /// <summary> /// Defines if the current list or library has to be included in crawling, optional attribute. /// </summary> public bool NoCrawl { get; set; } /// <summary> /// Defines the current list UI/UX experience (valid for SPO only). /// SP REST property name: ListExperienceOptions. /// </summary> public ListExperience ListExperience { get; set; } /// <summary> /// Defines a value that specifies the location of the default display form for the list. /// </summary> public string DefaultDisplayFormUrl { get; set; } /// <summary> /// Defines a value that specifies the URL of the edit form to use for list items in the list. /// </summary> public string DefaultEditFormUrl { get; set; } /// <summary> /// Defines a value that specifies the location of the default new form for the list. /// </summary> public string DefaultNewFormUrl { get; set; } /// <summary> /// Defines a value that specifies the reading order of the list. /// </summary> public ListReadingDirection Direction { get; set; } /// <summary> /// Defines a value that specifies the URI for the icon of the list, optional attribute. /// </summary> public string ImageUrl { get; set; } /// <summary> /// Defines if IRM Expire property, optional attribute. /// </summary> public bool IrmExpire { get; set; } /// <summary> /// Defines the IRM Reject property, optional attribute. /// </summary> public bool IrmReject { get; set; } /// <summary> /// Defines if IRM is enabled for this list. /// </summary> public bool IrmEnabled { get; set; } /// <summary> /// Defines a value that specifies a flag that a client application can use to determine whether to display the list, optional attribute. /// </summary> public bool IsApplicationList { get; set; } /// <summary> /// Defines the Read Security property, optional attribute. /// </summary> public int ReadSecurity { get; set; } /// <summary> /// Defines the Write Security property, optional attribute. /// </summary> public int WriteSecurity { get; set; } /// <summary> /// Defines a value that specifies the data validation criteria for a list item, optional attribute. /// </summary> public string ValidationFormula { get; set; } /// <summary> /// Defines a value that specifies the error message returned when data validation fails for a list item, optional attribute. /// </summary> public string ValidationMessage { get; set; } /// <summary> /// The entity needed when updating list items /// </summary> string ListItemEntityTypeFullName { get; } /// <summary> /// Number of items in the library /// </summary> public int ItemCount { get; } /// <summary> /// Collection of list items in the current List object /// </summary> public IListItemCollection Items { get; } /// <summary> /// Collection of content types for this list /// </summary> public IContentTypeCollection ContentTypes { get; } /// <summary> /// Collection of fields for this list /// </summary> public IFieldCollection Fields { get; } /// <summary> /// Load the IRM settings of this list /// </summary> public IInformationRightsManagementSettings InformationRightsManagementSettings { get; } /// <summary> /// Collection of role assignments for this list /// </summary> public IRoleAssignmentCollection RoleAssignments { get; } /// <summary> /// Get a list of the views /// </summary> public IViewCollection Views { get; } /// <summary> /// Returns if the list has unique role assignments /// </summary> public bool HasUniqueRoleAssignments { get; } /// <summary> /// A special property used to add an asterisk to a $select statement /// </summary> public object All { get; } #endregion #region Methods /// <summary> /// Moves this list into the site collection recycle bin, returns the recyle bin item id /// </summary> /// <returns>Id of the recycle bin item</returns> public Guid Recycle(); /// <summary> /// Moves this list into the site collection recycle bin, returns the recyle bin item id /// </summary> /// <returns>Id of the recycle bin item</returns> public Task<Guid> RecycleAsync(); /// <summary> /// Moves this list into the site collection recycle bin, returns the recyle bin item id /// </summary> /// <returns>Id of the recycle bin item</returns> public IBatchSingleResult<BatchResultValue<Guid>> RecycleBatch(); /// <summary> /// Moves this list into the site collection recycle bin, returns the recyle bin item id /// </summary> /// <returns>Id of the recycle bin item</returns> public Task<IBatchSingleResult<BatchResultValue<Guid>>> RecycleBatchAsync(); /// <summary> /// Moves this list into the site collection recycle bin, returns the recyle bin item id /// </summary> /// <param name="batch">Batch to add the request to</param> /// <returns>Id of the recycle bin item</returns> public IBatchSingleResult<BatchResultValue<Guid>> RecycleBatch(Batch batch); /// <summary> /// Moves this list into the site collection recycle bin, returns the recyle bin item id /// </summary> /// <param name="batch">Batch to add the request to</param> /// <returns>Id of the recycle bin item</returns> public Task<IBatchSingleResult<BatchResultValue<Guid>>> RecycleBatchAsync(Batch batch); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="query">query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public Task LoadItemsByCamlQueryAsync(string query, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="query">query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public void LoadItemsByCamlQuery(string query, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="queryOptions"><see cref="CamlQueryOptions"/> defining the query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public Task LoadItemsByCamlQueryAsync(CamlQueryOptions queryOptions, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="queryOptions"><see cref="CamlQueryOptions"/> defining the query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public void LoadItemsByCamlQuery(CamlQueryOptions queryOptions, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="query">query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public Task LoadItemsByCamlQueryBatchAsync(string query, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="query">query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public void LoadItemsByCamlQueryBatch(string query, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="queryOptions"><see cref="CamlQueryOptions"/> defining the query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public Task LoadItemsByCamlQueryBatchAsync(CamlQueryOptions queryOptions, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="queryOptions"><see cref="CamlQueryOptions"/> defining the query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public void LoadItemsByCamlQueryBatch(CamlQueryOptions queryOptions, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="batch">Batch to add this request to </param> /// <param name="query">query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public Task LoadItemsByCamlQueryBatchAsync(Batch batch, string query, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="batch">Batch to add this request to </param> /// <param name="query">query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public void LoadItemsByCamlQueryBatch(Batch batch, string query, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="batch">Batch to add this request to </param> /// <param name="queryOptions"><see cref="CamlQueryOptions"/> defining the query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public Task LoadItemsByCamlQueryBatchAsync(Batch batch, CamlQueryOptions queryOptions, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query /// </summary> /// <param name="batch">Batch to add this request to </param> /// <param name="queryOptions"><see cref="CamlQueryOptions"/> defining the query to execute</param> /// <param name="selectors">The expressions declaring the fields to select</param> /// <returns></returns> public void LoadItemsByCamlQueryBatch(Batch batch, CamlQueryOptions queryOptions, params Expression<Func<IListItem, object>>[] selectors); /// <summary> /// Loads list items based up on a CAML query and the RenderListDataAsStream API /// </summary> /// <param name="renderOptions"><see cref="RenderListDataOptions"/> defining the query to execute</param> /// <returns></returns> public Task<Dictionary<string, object>> LoadListDataAsStreamAsync(RenderListDataOptions renderOptions); /// <summary> /// Loads list items based up on a CAML query and the RenderListDataAsStream API /// </summary> /// <param name="renderOptions"><see cref="RenderListDataOptions"/> defining the query to execute</param> /// <returns></returns> public Dictionary<string, object> LoadListDataAsStream(RenderListDataOptions renderOptions); /// <summary> /// Retrieves the compliance tag / retention label for this list /// </summary> public IComplianceTag GetComplianceTag(); /// <summary> /// Retrieves the compliance tag / retention label for this list /// </summary> public Task<IComplianceTag> GetComplianceTagAsync(); /// <summary> /// Sets a compliance tag / retention label for this list /// </summary> /// <param name="complianceTagValue">Compliance tag</param> /// <param name="blockDelete">Prevent deletion of the list (Hold)</param> /// <param name="blockEdit">Prevent editing of the list (Record)</param> /// <param name="syncToItems">If true the compliance tag is synced to the list items in this list</param> public void SetComplianceTag(string complianceTagValue, bool blockDelete, bool blockEdit, bool syncToItems); /// <summary> /// Sets a compliance tag / retention label for this list /// </summary> /// <param name="complianceTagValue">Compliance tag</param> /// <param name="blockDelete">Prevent deletion of the list (Hold)</param> /// <param name="blockEdit">Prevent editing of the list (Record)</param> /// <param name="syncToItems">If true the compliance tag is synced to the list items in this list</param> public Task SetComplianceTagAsync(string complianceTagValue, bool blockDelete, bool blockEdit, bool syncToItems); /// <summary> /// Sets a compliance tag / retention label for this list /// </summary> /// <param name="complianceTagValue">Compliance tag</param> /// <param name="blockDelete">Prevent deletion of the list (Hold)</param> /// <param name="blockEdit">Prevent editing of the list (Record)</param> /// <param name="syncToItems">If true the compliance tag is synced to the list items in this list</param> public void SetComplianceTagBatch(string complianceTagValue, bool blockDelete, bool blockEdit, bool syncToItems); /// <summary> /// Sets a compliance tag / retention label for this list /// </summary> /// <param name="complianceTagValue">Compliance tag</param> /// <param name="blockDelete">Prevent deletion of the list (Hold)</param> /// <param name="blockEdit">Prevent editing of the list (Record)</param> /// <param name="syncToItems">If true the compliance tag is synced to the list items in this list</param> public Task SetComplianceTagBatchAsync(string complianceTagValue, bool blockDelete, bool blockEdit, bool syncToItems); /// <summary> /// Sets a compliance tag / retention label for this list /// </summary> /// <param name="batch">Batch to add this request to </param> /// <param name="complianceTagValue">Compliance tag</param> /// <param name="blockDelete">Prevent deletion of the list (Hold)</param> /// <param name="blockEdit">Prevent editing of the list (Record)</param> /// <param name="syncToItems">If true the compliance tag is synced to the list items in this list</param> public void SetComplianceTagBatch(Batch batch, string complianceTagValue, bool blockDelete, bool blockEdit, bool syncToItems); /// <summary> /// Sets a compliance tag / retention label for this list /// </summary> /// <param name="batch">Batch to add this request to </param> /// <param name="complianceTagValue">Compliance tag</param> /// <param name="blockDelete">Prevent deletion of the list (Hold)</param> /// <param name="blockEdit">Prevent editing of the list (Record)</param> /// <param name="syncToItems">If true the compliance tag is synced to the list items in this list</param> public Task SetComplianceTagBatchAsync(Batch batch, string complianceTagValue, bool blockDelete, bool blockEdit, bool syncToItems); /// <summary> /// Creates unique role assignments for the list. /// </summary> /// <param name="copyRoleAssignments">Specifies whether to copy the role assignments from the parent securable object. If the value is false, the collection of role assignments must contain only 1 role assignment containing the current user after the operation.</param> /// <param name="clearSubscopes">If the securable object is a site, and the clearsubscopes parameter is true, the role assignments for all child securable objects in the current site and in the sites which inherit role assignments from the current site must be cleared and those securable objects will inherit role assignments from the current site after this call. If the securable object is a site, and the clearsubscopes parameter is false, the role assignments for all child securable objects which do not inherit role assignments from their parent object must remain unchanged. If the securable object is not a site, and the clearsubscopes parameter is true, the role assignments for all child securable objects must be cleared and those securable objects will inherit role assignments from the current securable object after this call. If the securable object is not a site, and the clearsubscopes parameter is false, the role assignments for all child securable objects which do not inherit role assignments from their parent object must remain unchanged.</param> public void BreakRoleInheritance(bool copyRoleAssignments, bool clearSubscopes); /// <summary> /// Creates unique role assignments for the list. /// </summary> /// <param name="copyRoleAssignments">Specifies whether to copy the role assignments from the parent securable object. If the value is false, the collection of role assignments must contain only 1 role assignment containing the current user after the operation.</param> /// <param name="clearSubscopes">If the securable object is a site, and the clearsubscopes parameter is true, the role assignments for all child securable objects in the current site and in the sites which inherit role assignments from the current site must be cleared and those securable objects will inherit role assignments from the current site after this call. If the securable object is a site, and the clearsubscopes parameter is false, the role assignments for all child securable objects which do not inherit role assignments from their parent object must remain unchanged. If the securable object is not a site, and the clearsubscopes parameter is true, the role assignments for all child securable objects must be cleared and those securable objects will inherit role assignments from the current securable object after this call. If the securable object is not a site, and the clearsubscopes parameter is false, the role assignments for all child securable objects which do not inherit role assignments from their parent object must remain unchanged.</param> public Task BreakRoleInheritanceAsync(bool copyRoleAssignments, bool clearSubscopes); /// <summary> /// Removes the local role assignments so that the list, and all its descendant objects, re-inherit role assignments from the parent object. /// </summary> public void ResetRoleInheritance(); /// <summary> /// Removes the local role assignments so that the list, and all its descendant objects, re-inherit role assignments from the parent object. /// </summary> public Task ResetRoleInheritanceAsync(); /// <summary> /// Returns the role definitions for a specific principal id (IUser.Id or ISharePointGroup.Id) /// </summary> /// <param name="principalId"></param> /// <returns></returns> public IRoleDefinitionCollection GetRoleDefinitions(int principalId); /// <summary> /// Returns the role definitions for a specific principal id (IUser.Id or ISharePointGroup.Id) /// </summary> /// <param name="principalId"></param> /// <returns></returns> public Task<IRoleDefinitionCollection> GetRoleDefinitionsAsync(int principalId); /// <summary> /// Add role definitions for a specific principal id (IUser.Id or ISharePointGroup.Id) /// </summary> /// <param name="principalId"></param> /// <param name="names"></param> /// <returns></returns> public bool AddRoleDefinitions(int principalId, params string[] names); /// <summary> /// Adds role definitions for a specific principal id (IUser.Id or ISharePointGroup.Id) /// </summary> /// <param name="principalId"></param> /// <param name="names"></param> /// <returns></returns> public Task<bool> AddRoleDefinitionsAsync(int principalId, params string[] names); /// <summary> /// Adds role definitions for a specific principal id (IUser.Id or ISharePointGroup.Id) /// </summary> /// <param name="principalId"></param> /// <param name="names"></param> /// <returns></returns> public bool RemoveRoleDefinitions(int principalId, params string[] names); /// <summary> /// adds role definitions for a specific principal id (IUser.Id or ISharePointGroup.Id) /// </summary> /// <param name="principalId"></param> /// <param name="names"></param> /// <returns></returns> public Task<bool> RemoveRoleDefinitionsAsync(int principalId, params string[] names); /// <summary> /// Adds a folder /// </summary> /// <param name="path"></param> /// <param name="parentFolder"></param> /// <param name="contentTypeId"></param> /// <returns></returns> public IListItem AddListFolder(string path, string parentFolder = null, string contentTypeId = "0x0120"); /// <summary> /// Adds a folder /// </summary> /// <param name="path"></param> /// <param name="parentFolder"></param> /// <param name="contentTypeId"></param> /// <returns></returns> public Task<IListItem> AddListFolderAsync(string path, string parentFolder = null, string contentTypeId = "0x0120"); /// <summary> /// Classifies and extracts all unprocessed files in the list /// </summary> /// <param name="force">Also classify and extract files that were processed before</param> /// <param name="pageSize">Page size used when loading the files in this library</param> /// <returns>Information about the created classify and extract requests</returns> Task<List<ISyntexClassifyAndExtractResult>> ClassifyAndExtractAsync(bool force = false, int pageSize = 500); /// <summary> /// Classifies and extracts all unprocessed files in the list /// </summary> /// <param name="force">Also classify and extract files that were processed before</param> /// <param name="pageSize">Page size used when loading the files in this library</param> /// <returns>Information about the created classify and extract requests</returns> List<ISyntexClassifyAndExtractResult> ClassifyAndExtract(bool force = false, int pageSize = 500); /// <summary> /// Classifies and extracts all unprocessed files in the list via the Syntex off-peak queue /// </summary> /// <returns>Information about the created classify and extract requests</returns> Task<ISyntexClassifyAndExtractResult> ClassifyAndExtractOffPeakAsync(); /// <summary> /// Classifies and extracts all unprocessed files in the list via the Syntex off-peak queue /// </summary> /// <returns>Information about the created classify and extract requests</returns> ISyntexClassifyAndExtractResult ClassifyAndExtractOffPeak(); #endregion } }
48.901361
1,078
0.639111
[ "MIT" ]
DonKirkham/pnpcore
src/sdk/PnP.Core/Model/SharePoint/Core/Public/IList.cs
28,756
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Reflection; namespace Choreograph { public partial class MainForm : Form { bool close_to_tray = true; Form display_form = null; DataView characterlist_source = null; Random seed = new Random(); private void enforce_inactivecharacters_filter() { foreach (InactiveCharacterControl control in inactivecharacterspanel.Controls) { control.filter = filtertb.Text; } } private void start_subscriptions() { characterlist_source = Storage.characters.AsDataView(); characterlist_source.Sort = "id"; enforce_inactivecharacters_filter(); Storage.characters.RowChanged += handle_characters_change; Storage.active_ids.ListChanged += handle_actives_change; Storage.characters.ColumnChanged += character_property_changed; } private void stop_subscriptions() { Storage.characters.RowChanged -= handle_characters_change; Storage.active_ids.ListChanged -= handle_actives_change; Storage.characters.ColumnChanged -= character_property_changed; } public MainForm() { InitializeComponent(); } private void show_display() { if (display_form != null) { display_form.Close(); } display_form = new InitiativeDisplayForm(hide_display); displaybtn.Text = "Hide Display"; displaybtn.BackColor = Color.Violet; display_form.Show(); Focus(); } private void hide_display() { if (display_form != null) { try { display_form.Close(); } catch (Exception) { // already closed, can ignore } } display_form = null; displaybtn.Text = "Show Display"; displaybtn.BackColor = Color.Yellow; } private void toggle_display() { if (display_form == null) { show_display(); } else { hide_display(); } this.Focus(); } private void new_character_click(object sender, EventArgs e) { DataRow new_character = Storage.characters.NewRow(); new_character["id"] = Guid.NewGuid().ToString(); new_character["name"] = ""; Storage.characters.Rows.Add(new_character); Storage.characters.AcceptChanges(); Storage.active_ids.Add((string)new_character["id"]); } private void clear_active_characters_click(object sender, EventArgs e) { relinquish_focus(); Storage.active_ids.Clear(); } private void displaybtn_Click(object sender, EventArgs e) { toggle_display(); } private void filtertb_TextChanged(object sender, EventArgs e) { enforce_inactivecharacters_filter(); } private void sort_activecharacterspanel() { activecharacterspanel.SuspendLayout(); CharacterEditControl[] ordered_controls = activecharacterspanel.Controls.OfType<CharacterEditControl>().OrderByDescending( c => (string)Storage.characters.Rows.Find(c.id)["name"] ).ToArray(); for (int i = 0; i < activecharacterspanel.Controls.Count; i++) { activecharacterspanel.Controls.SetChildIndex(ordered_controls[i], i); } activecharacterspanel.ResumeLayout(); } private void sort_inactivecharacterspanel() { inactivecharacterspanel.SuspendLayout(); InactiveCharacterControl[] ordered_controls = inactivecharacterspanel.Controls.OfType<InactiveCharacterControl>().OrderByDescending( c => (string)Storage.characters.Rows.Find(c.id)["name"] ).ToArray(); for(int i = 0; i < inactivecharacterspanel.Controls.Count; i++) { inactivecharacterspanel.Controls.SetChildIndex(ordered_controls[i], i); } inactivecharacterspanel.ResumeLayout(); } private void character_property_changed(object sender, DataColumnChangeEventArgs e) { if (e.Column.ColumnName == "name") { sort_activecharacterspanel(); sort_inactivecharacterspanel(); } } private CharacterEditControl create_active_control(string active_id) { CharacterEditControl new_control = new CharacterEditControl(relinquish_focus, active_id); new_control.Dock = DockStyle.Top; return new_control; } private void add_active_control(string active_id, bool sort = true) { CharacterEditControl new_control = create_active_control(active_id); activecharacterspanel.Controls.Add(new_control); if (sort) { sort_activecharacterspanel(); } } private InactiveCharacterControl create_inactive_control(string id) { InactiveCharacterControl new_control = new InactiveCharacterControl(relinquish_focus, id); new_control.Dock = DockStyle.Top; return new_control; } private void add_inactive_control(string id, bool sort = true) { InactiveCharacterControl new_control = create_inactive_control(id); inactivecharacterspanel.Controls.Add(new_control); if (sort) { sort_inactivecharacterspanel(); } } private void purge_active_controls() { foreach (CharacterEditControl control in activecharacterspanel.Controls) { if (!Storage.active_ids.Contains(control.id)) { activecharacterspanel.Controls.Remove(control); DataRow character = Storage.characters.Rows.Find(control.id); if (((string)character["name"]).Trim() == "") { Storage.characters.Rows.Remove(character); Storage.characters.AcceptChanges(); } } } } private void purge_inactive_controls() { foreach (InactiveCharacterControl control in inactivecharacterspanel.Controls) { if (Storage.active_ids.Contains(control.id)) { inactivecharacterspanel.Controls.Remove(control); } } } private void handle_characters_change(object sender, DataRowChangeEventArgs e) { switch (e.Action) { case DataRowAction.Add: string id = (string)e.Row["id"]; add_inactive_control(id); var tmp = characterlist_source.Find(id); break; default: break; } } private void handle_actives_change(object sender, ListChangedEventArgs e) { switch (e.ListChangedType) { case ListChangedType.ItemAdded: add_active_control(Storage.active_ids[e.NewIndex]); enforce_inactivecharacters_filter(); break; case ListChangedType.ItemDeleted: purge_active_controls(); enforce_inactivecharacters_filter(); break; case ListChangedType.Reset: Storage.purge_characters(); load_active_controls(); load_inactive_controls(); break; default: break; } } private void load_layout() { if (!Properties.Settings.Default.LoadMainFormSettings) { return; } Location = Properties.Settings.Default.MainFormLocation; Size = Properties.Settings.Default.MainFormSize; } private void load_active_controls() { List<CharacterEditControl> new_controls = new List<CharacterEditControl>(); foreach(string active_id in Storage.active_ids) { new_controls.Add(create_active_control(active_id)); } activecharacterspanel.Controls.Clear(); activecharacterspanel.Controls.AddRange(new_controls.ToArray()); sort_activecharacterspanel(); } private void load_inactive_controls() { List<InactiveCharacterControl> new_controls = new List<InactiveCharacterControl>(); foreach (DataRow character in Storage.characters.Rows) { new_controls.Add(create_inactive_control((string)character["id"])); } inactivecharacterspanel.Controls.Clear(); inactivecharacterspanel.Controls.AddRange(new_controls.ToArray()); sort_inactivecharacterspanel(); } private void MainForm_Load(object sender, EventArgs e) { SuspendLayout(); Storage.load_storage(); start_subscriptions(); load_layout(); load_inactive_controls(); load_active_controls(); filtertb.Unfocus = relinquish_focus; filtertb.Text = ""; ResumeLayout(); } private void save_layout() { if (WindowState == FormWindowState.Normal) { Properties.Settings.Default.MainFormLocation = Location; Properties.Settings.Default.MainFormSize = Size; Properties.Settings.Default.MainSplitterDistance = splitContainer1.SplitterDistance; } Properties.Settings.Default.ShowDisplay = (display_form != null); Properties.Settings.Default.LoadMainFormSettings = true; Properties.Settings.Default.Save(); } public void Terminate() { close_to_tray = false; this.Close(); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { relinquish_focus(); save_layout(); if (!Storage.save_storage()) { if (MessageBox.Show("Failed while writing data to storage.\nThis may be due to folder permissions.\n\nContinue closing the application?", "Write Error", MessageBoxButtons.YesNo) == DialogResult.No) { e.Cancel = true; return; } } if (e.CloseReason == CloseReason.UserClosing) { if (close_to_tray) { e.Cancel = true; Hide(); return; } hide_display(); } stop_subscriptions(); } private void label1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { activecharactersmenustrip.Show(MousePosition); } } private int roll_initiative(int modifier) { return seed.Next(1, 21) + modifier; } private void rollbtn_Click(object sender, EventArgs e) { foreach (DataRow character in Storage.characters.Rows) { if ((bool)character["locked"]) { continue; } if (Storage.active_ids.Contains(character["id"])) { character["roll"] = roll_initiative((int)character["mod"]); } } Storage.characters.AcceptChanges(); } private void MainForm_Shown(object sender, EventArgs e) { relinquish_focus(); if (Properties.Settings.Default.MainSplitterDistance >= 0) { splitContainer1.SplitterDistance = Properties.Settings.Default.MainSplitterDistance; } if (Properties.Settings.Default.ShowDisplay) { show_display(); } } private void relinquish_focus() { if (Storage.active_ids.Count <= 0) { newbtn.Focus(); } else { rollbtn.Focus(); } } private void MainForm_MouseClick(object sender, MouseEventArgs e) { relinquish_focus(); if (e.Button == MouseButtons.Right) { // Nothing to show on menu at the moment //menustrip.Show(MousePosition); } } // Bubbling. There doesn't seem to be a cleaner option private void pass_mouseclick_to_form(object sender, MouseEventArgs e) { MainForm_MouseClick(sender, e); } private void closeToolStripMenuItem_Click(object sender, EventArgs e) { Terminate(); } private void show_mainform() { if (WindowState == FormWindowState.Minimized) { WindowState = FormWindowState.Normal; } Show(); BringToFront(); } private void showToolStripMenuItem_Click(object sender, EventArgs e) { show_mainform(); } private void notifyIcon_MouseDoubleClick(object sender, EventArgs e) { show_mainform(); } } }
32.719818
213
0.54372
[ "MIT" ]
Hynchus/DMFamiliar
Choreograph/MainForm.cs
14,366
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.ML.OnnxRuntime.Tensors; using System; using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; namespace Microsoft.ML.OnnxRuntime { /// <summary> /// A type of data that OrtValue encapsulates. /// </summary> public enum OnnxValueType { ONNX_TYPE_UNKNOWN = 0, // Not set ONNX_TYPE_TENSOR = 1, // It's a Tensor ONNX_TYPE_SEQUENCE = 2, // It's an Onnx sequence which may be a sequence of Tensors/Maps/Sequences ONNX_TYPE_MAP = 3, // It's a map ONNX_TYPE_OPAQUE = 4, // It's an experimental Opaque object ONNX_TYPE_SPARSETENSOR = 5, // It's a Sparse Tensor } /// <summary> /// Represents a disposable OrtValue. /// This class exposes a native instance of OrtValue. /// The class implements IDisposable via SafeHandle and must /// be disposed. /// </summary> public class OrtValue : SafeHandle { /// <summary> /// Use factory methods to instantiate this class /// </summary> /// <param name="handle">Pointer to a native instance of OrtValue</param> /// <param name="owned">Default true, own the raw handle. Otherwise, the handle is owned by another instance /// However, we use this class to expose OrtValue that is owned by DisposableNamedOnnxValue /// </param> internal OrtValue(IntPtr handle, bool owned = true) : base(handle, true) { IsOwned = owned; } internal IntPtr Handle { get { return handle; } } /// <summary> /// Overrides SafeHandle.IsInvalid /// </summary> /// <value>returns true if handle is equal to Zero</value> public override bool IsInvalid { get { return handle == IntPtr.Zero; } } #region NamedOnnxValue/DisposableOnnxValue accommodations /// <summary> /// This internal interface is used to transfer ownership elsewhere. /// This instance must still be disposed in case there are other native /// objects still owned. This is a convenience method to ensure that an underlying /// OrtValue is disposed exactly once when exception is thrown. /// </summary> /// <returns></returns> internal IntPtr Disown() { var ret = Handle; handle = IntPtr.Zero; IsOwned = false; return ret; } internal bool IsOwned { get; private set; } #endregion /// <summary> /// Factory method to construct an OrtValue of Tensor type on top of pre-allocated memory. /// This can be a piece of native memory allocated by OrtAllocator (possibly on a device) /// or a piece of pinned managed memory. /// /// The resulting OrtValue does not own the underlying memory buffer and will not attempt to /// deallocate it. /// </summary> /// <param name="memInfo">Memory Info. For managed memory it is a default cpu. /// For Native memory must be obtained from the allocator or OrtMemoryAllocation instance</param> /// <param name="elementType">DataType for the Tensor</param> /// <param name="shape">Tensor shape</param> /// <param name="dataBuffer">Pointer to a raw memory buffer</param> /// <param name="bufferLength">Buffer length in bytes</param> /// <returns>A disposable instance of OrtValue</returns> public static OrtValue CreateTensorValueWithData(OrtMemoryInfo memInfo, TensorElementType elementType, long[] shape, IntPtr dataBuffer, long bufferLength) { Type type; int width; TensorElementTypeConverter.GetTypeAndWidth(elementType, out type, out width); if(width < 1) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Unsupported data type (such as string)"); } var shapeSize = ArrayUtilities.GetSizeForShape(shape); if((shapeSize * width) > bufferLength) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Can not bind the shape to smaller buffer"); } IntPtr ortValueHandle = IntPtr.Zero; NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateTensorWithDataAsOrtValue( memInfo.Pointer, dataBuffer, (UIntPtr)bufferLength, shape, (UIntPtr)shape.Length, elementType, out ortValueHandle )); return new OrtValue(ortValueHandle); } /// <summary> /// This is a factory method creates a native Onnxruntime OrtValue containing a tensor. /// The method will attempt to pin managed memory so no copying occurs when data is passed down /// to native code. /// </summary> /// <param name="value">Tensor object</param> /// <param name="memoryHandle">For all tensor types but string tensors we endeavor to use managed memory /// to avoid additional allocation and copy. This out parameter represents a chunk of pinned memory which will need /// to be disposed when no longer needed. The lifespan of memoryHandle should eclipse the lifespan of the corresponding /// OrtValue. /// </param> /// <param name="elementType">discovered tensor element type</param> /// <returns>And instance of OrtValue constructed on top of the object</returns> public static OrtValue CreateFromTensorObject(Object value, out MemoryHandle? memoryHandle, out TensorElementType elementType) { // Check if this is a Tensor if (!(value is TensorBase)) { throw new NotSupportedException("The inference value " + nameof(value) + " is not of a supported type"); } var tensorBase = value as TensorBase; var typeInfo = tensorBase.GetTypeInfo(); if (typeInfo == null) { throw new OnnxRuntimeException(ErrorCode.RequirementNotRegistered, "BUG Check"); } MemoryHandle? memHandle; OrtValue ortValue = null; int dataBufferLength = 0; long[] shape = null; int rank = 0; TensorElementType elType = typeInfo.ElementType; var typeSize = typeInfo.TypeSize; if (typeInfo.IsString) { ortValue = CreateStringTensor(value as Tensor<string>); memHandle = null; } else { switch (elType) { case TensorElementType.Float: PinAsTensor(value as Tensor<float>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.Double: PinAsTensor(value as Tensor<double>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.Int32: PinAsTensor(value as Tensor<int>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.UInt32: PinAsTensor(value as Tensor<uint>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.Int64: PinAsTensor(value as Tensor<long>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.UInt64: PinAsTensor(value as Tensor<ulong>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.Int16: PinAsTensor(value as Tensor<short>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.UInt16: PinAsTensor(value as Tensor<ushort>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.UInt8: PinAsTensor(value as Tensor<byte>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.Int8: PinAsTensor(value as Tensor<sbyte>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.Bool: PinAsTensor(value as Tensor<bool>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.Float16: PinAsTensor(value as Tensor<Float16>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; case TensorElementType.BFloat16: PinAsTensor(value as Tensor<BFloat16>, typeSize, out memHandle, out dataBufferLength, out shape, out rank); break; default: throw new NotSupportedException("Element type: " + elType + " is not of a supported type"); } try { Debug.Assert(memHandle.HasValue); IntPtr dataBufferPointer = IntPtr.Zero; unsafe { dataBufferPointer = (IntPtr)((MemoryHandle)memHandle).Pointer; } IntPtr nativeValue; NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateTensorWithDataAsOrtValue( OrtMemoryInfo.DefaultInstance.Pointer, dataBufferPointer, (UIntPtr)(dataBufferLength), shape, (UIntPtr)rank, elType, out nativeValue)); ortValue = new OrtValue(nativeValue); } catch (Exception) { memHandle?.Dispose(); throw; } } memoryHandle = memHandle; elementType = elType; return ortValue; } private static void PinAsTensor<T>( Tensor<T> tensor, int elementSize, out MemoryHandle? pinnedHandle, out int dataBufferLength, out long[] shape, out int rank) { if (tensor == null) { throw new OnnxRuntimeException(ErrorCode.Fail, "Cast to Tensor<T> failed. BUG check!"); } if (tensor.IsReversedStride) { //TODO: not sure how to support reverse stride. may be able to calculate the shape differently throw new NotSupportedException(nameof(Tensor<T>) + " of reverseStride is not supported"); } DenseTensor<T> dt = null; if (tensor is DenseTensor<T>) { dt = tensor as DenseTensor<T>; } else { dt = tensor.ToDenseTensor(); } pinnedHandle = dt.Buffer.Pin(); dataBufferLength = dt.Buffer.Length * elementSize; shape = new long[dt.Dimensions.Length]; for (int i = 0; i < dt.Dimensions.Length; ++i) { shape[i] = dt.Dimensions[i]; } rank = dt.Rank; } private static OrtValue CreateStringTensor(Tensor<string> tensor) { if (tensor == null) { throw new OnnxRuntimeException(ErrorCode.Fail, "Cast to Tensor<string> failed. BUG check!"); } int totalLength = 0; for (int i = 0; i < tensor.Length; i++) { totalLength += System.Text.Encoding.UTF8.GetByteCount(tensor.GetValue(i)); } long[] shape = new long[tensor.Dimensions.Length]; for (int i = 0; i < tensor.Dimensions.Length; i++) { shape[i] = tensor.Dimensions[i]; } // allocate the native tensor IntPtr valueHandle = IntPtr.Zero; NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateTensorAsOrtValue( OrtAllocator.DefaultInstance.Pointer, shape, (UIntPtr)(shape.Length), TensorElementType.String, out valueHandle )); var ortValue = new OrtValue(valueHandle); try { // fill the native tensor, using GetValue(index) from the Tensor<string> var len = tensor.Length; var nativeStrings = new IntPtr[len]; using (var pinnedHandles = new DisposableList<PinnedGCHandle>((int)len)) { for (int i = 0; i < len; i++) { var utf8str = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(tensor.GetValue(i)); var gcHandle = GCHandle.Alloc(utf8str, GCHandleType.Pinned); nativeStrings[i] = gcHandle.AddrOfPinnedObject(); pinnedHandles.Add(new PinnedGCHandle(gcHandle)); } using (var pinnedStrings = new PinnedGCHandle(GCHandle.Alloc(nativeStrings, GCHandleType.Pinned))) NativeApiStatus.VerifySuccess(NativeMethods.OrtFillStringTensor(ortValue.Handle, nativeStrings, (UIntPtr)len)); } } catch (OnnxRuntimeException) { ortValue.Dispose(); throw; } return ortValue; } #region SafeHandle /// <summary> /// Overrides SafeHandle.ReleaseHandle() to properly dispose of /// the native instance of OrtValue /// </summary> /// <returns>always returns true</returns> protected override bool ReleaseHandle() { // We have to surrender ownership to some legacy classes // Or we never had that ownership to begin with if (IsOwned) { NativeMethods.OrtReleaseValue(handle); } // Prevent use after disposal handle = IntPtr.Zero; return true; } // No need for the finalizer #endregion } }
43.023499
135
0.506069
[ "MIT" ]
Alexander-code-365/onnxruntime
csharp/src/Microsoft.ML.OnnxRuntime/OrtValue.shared.cs
16,480
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; namespace Shadowsocks.Controller { public class FileManager { public static bool ByteArrayToFile(string fileName, byte[] content) { try { System.IO.FileStream _FileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); _FileStream.Write(content, 0, content.Length); _FileStream.Close(); return true; } catch (Exception _Exception) { Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } return false; } public static void UncompressFile(string fileName, byte[] content) { FileStream destinationFile = File.Create(fileName); // Because the uncompressed size of the file is unknown, // we are using an arbitrary buffer size. byte[] buffer = new byte[4096]; int n; using (GZipStream input = new GZipStream(new MemoryStream(content), CompressionMode.Decompress, false)) { while (true) { n = input.Read(buffer, 0, buffer.Length); if (n == 0) { break; } destinationFile.Write(buffer, 0, n); } } destinationFile.Close(); } public static byte[] DeflateCompress(byte[] content, int index, int count, out int size) { size = 0; try { MemoryStream memStream = new MemoryStream(); using (DeflateStream ds = new DeflateStream(memStream, CompressionMode.Compress)) { ds.Write(content, index, count); } byte[] buffer = memStream.ToArray(); size = buffer.Length; return buffer; } catch (Exception _Exception) { Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } return null; } public static byte[] DeflateDecompress(byte[] content, int index, int count, out int size) { size = 0; try { byte[] buffer = new byte[16384]; DeflateStream ds = new DeflateStream(new MemoryStream(content, index, count), CompressionMode.Decompress); int readsize; while (true) { readsize = ds.Read(buffer, size, buffer.Length - size); if (readsize == 0) { break; } size += readsize; byte[] newbuffer = new byte[buffer.Length * 2]; buffer.CopyTo(newbuffer, 0); buffer = newbuffer; } return buffer; } catch (Exception _Exception) { Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } return null; } } }
34.570093
123
0.444174
[ "Apache-2.0" ]
Benjamartin/shadowsocksr-csharp
shadowsocks-csharp/Controller/FileManager.cs
3,701
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.dms_enterprise.Model.V20181101; namespace Aliyun.Acs.dms_enterprise.Transform.V20181101 { public class PauseDataCorrectSQLJobResponseUnmarshaller { public static PauseDataCorrectSQLJobResponse Unmarshall(UnmarshallerContext _ctx) { PauseDataCorrectSQLJobResponse pauseDataCorrectSQLJobResponse = new PauseDataCorrectSQLJobResponse(); pauseDataCorrectSQLJobResponse.HttpResponse = _ctx.HttpResponse; pauseDataCorrectSQLJobResponse.RequestId = _ctx.StringValue("PauseDataCorrectSQLJob.RequestId"); pauseDataCorrectSQLJobResponse.Success = _ctx.BooleanValue("PauseDataCorrectSQLJob.Success"); pauseDataCorrectSQLJobResponse.ErrorMessage = _ctx.StringValue("PauseDataCorrectSQLJob.ErrorMessage"); pauseDataCorrectSQLJobResponse.ErrorCode = _ctx.StringValue("PauseDataCorrectSQLJob.ErrorCode"); return pauseDataCorrectSQLJobResponse; } } }
42.302326
106
0.782848
[ "Apache-2.0" ]
pengweiqhca/aliyun-openapi-net-sdk
aliyun-net-sdk-dms-enterprise/Dms_enterprise/Transform/V20181101/PauseDataCorrectSQLJobResponseUnmarshaller.cs
1,819
C#
namespace AplikasiIsg { partial class Setting { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.timer2 = new System.Windows.Forms.Timer(this.components); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.textBox4 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // timer1 // this.timer1.Enabled = true; this.timer1.Interval = 1; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // timer2 // this.timer2.Interval = 1; this.timer2.Tick += new System.EventHandler(this.timer2_Tick); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(148, 31); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(246, 22); this.textBox1.TabIndex = 0; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(148, 59); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(246, 22); this.textBox2.TabIndex = 1; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(148, 87); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(246, 22); this.textBox3.TabIndex = 2; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(148, 115); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(246, 22); this.textBox4.TabIndex = 3; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(18, 34); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(67, 17); this.label1.TabIndex = 4; this.label1.Text = "Dir. Inbox"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(18, 62); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(79, 17); this.label2.TabIndex = 5; this.label2.Text = "Dir. Outbox"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(18, 90); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(87, 17); this.label3.TabIndex = 6; this.label3.Text = "Dir. Success"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(18, 118); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(66, 17); this.label4.TabIndex = 7; this.label4.Text = "Dir. Error"; // // button1 // this.button1.Location = new System.Drawing.Point(400, 30); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(29, 23); this.button1.TabIndex = 8; this.button1.Text = "..."; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(400, 58); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(29, 23); this.button2.TabIndex = 9; this.button2.Text = "..."; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.Location = new System.Drawing.Point(400, 86); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(29, 23); this.button3.TabIndex = 10; this.button3.Text = "..."; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // button4 // this.button4.Location = new System.Drawing.Point(400, 114); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(29, 23); this.button4.TabIndex = 11; this.button4.Text = "..."; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.textBox1); this.groupBox1.Controls.Add(this.button4); this.groupBox1.Controls.Add(this.textBox2); this.groupBox1.Controls.Add(this.button3); this.groupBox1.Controls.Add(this.textBox3); this.groupBox1.Controls.Add(this.button2); this.groupBox1.Controls.Add(this.textBox4); this.groupBox1.Controls.Add(this.button1); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Location = new System.Drawing.Point(34, 34); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(453, 158); this.groupBox1.TabIndex = 12; this.groupBox1.TabStop = false; this.groupBox1.Text = "Direktori"; // // Setting // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.ActiveCaption; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(1053, 541); this.Controls.Add(this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "Setting"; this.Opacity = 0D; this.ShowIcon = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Setting"; this.TopMost = true; this.Load += new System.EventHandler(this.Setting_Load); this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Setting_MouseClick); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Timer timer1; private System.Windows.Forms.Timer timer2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.GroupBox groupBox1; } }
43.748899
108
0.549391
[ "MIT" ]
tony4mail/AplikasiIsg
AplikasiIsg-master/AplikasiIsg/Setting.Designer.cs
9,933
C#
// CellPhoneAppBehaviour public enum CellPhoneAppBehaviour { LoadScene, ChangeScreen, LoadSettings }
13
33
0.817308
[ "MIT" ]
smdx24/CPI-Source-Code
ClubPenguin.CellPhone/CellPhoneAppBehaviour.cs
104
C#
using System; using VkNet.Utils; namespace VkNet.Model { /// <summary> /// Вариант ответа в опросе /// </summary> [Serializable] public class PollAnswer { /// <summary> /// Идентификатор варианта ответа /// </summary> public long? Id { get; set; } /// <summary> /// Текст ответа /// </summary> public string Text { get; set; } /// <summary> /// Кол-во проголосовавших /// </summary> public int? Votes { get; set; } /// <summary> /// Процент текущего ответа ко всем остальным вариантам /// </summary> public double? Rate { get; set; } /// <summary> /// Разобрать из json. /// </summary> /// <param name="response"> Ответ сервера. </param> /// <returns> </returns> public static PollAnswer FromJson(VkResponse response) { var answer = new PollAnswer { Id = response[key: "id"] , Text = response[key: "text"] , Votes = response[key: "votes"] , Rate = response[key: "rate"] }; return answer; } } }
19.74
57
0.593718
[ "MIT" ]
Azrael141/vk
VkNet/Model/PollAnswer.cs
1,135
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using UnprofessionalsApp.Data; namespace UnprofessionalsApp.Data.Migrations { [DbContext(typeof(UnprofessionalsDbContext))] partial class UnprofessionalsDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.0-rtm-35687") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole<int>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<int>("RoleId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<int>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<int>("UserId"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<int>", b => { b.Property<int>("UserId"); b.Property<int>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b => { b.Property<int>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("UnprofessionalsApp.Models.Category", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<bool>("IsDeleted"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Categories"); }); modelBuilder.Entity("UnprofessionalsApp.Models.Comment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("DateOfCreation"); b.Property<string>("Description"); b.Property<bool>("IsDeleted"); b.Property<int>("PostId"); b.Property<int>("UserId"); b.HasKey("Id"); b.HasIndex("PostId"); b.HasIndex("UserId"); b.ToTable("Comments"); }); modelBuilder.Entity("UnprofessionalsApp.Models.Firm", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("DateOfRegistration"); b.Property<bool>("IsDeleted"); b.Property<string>("LegalForm") .IsRequired(); b.Property<string>("Name") .IsRequired(); b.Property<string>("UniqueFirmId") .IsRequired() .HasMaxLength(9); b.HasKey("Id"); b.ToTable("Firms"); }); modelBuilder.Entity("UnprofessionalsApp.Models.Image", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Url") .IsRequired(); b.HasKey("Id"); b.ToTable("Images"); }); modelBuilder.Entity("UnprofessionalsApp.Models.Post", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CategoryId"); b.Property<DateTime>("DateOfCreation"); b.Property<string>("Description"); b.Property<Guid?>("FirmId"); b.Property<int>("ImageId"); b.Property<bool>("IsDeleted"); b.Property<string>("Title"); b.Property<int>("UserId"); b.HasKey("Id"); b.HasIndex("CategoryId"); b.HasIndex("FirmId"); b.HasIndex("ImageId"); b.HasIndex("UserId"); b.ToTable("Posts"); }); modelBuilder.Entity("UnprofessionalsApp.Models.Reply", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CommentId"); b.Property<DateTime>("DateOfCreation"); b.Property<string>("Description"); b.Property<bool>("IsDeleted"); b.Property<int>("UserId"); b.HasKey("Id"); b.HasIndex("CommentId"); b.HasIndex("UserId"); b.ToTable("Replies"); }); modelBuilder.Entity("UnprofessionalsApp.Models.Report", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("CommentId"); b.Property<DateTime>("CreationDate"); b.Property<string>("Description") .IsRequired(); b.Property<Guid?>("FirmId"); b.Property<bool>("IsDeleted"); b.Property<int?>("PostId"); b.Property<int?>("ReplyId"); b.Property<int?>("ReportedUserId"); b.Property<int>("UserId"); b.HasKey("Id"); b.HasIndex("CommentId"); b.HasIndex("FirmId"); b.HasIndex("PostId"); b.HasIndex("ReplyId"); b.HasIndex("ReportedUserId"); b.HasIndex("UserId"); b.ToTable("Reports"); }); modelBuilder.Entity("UnprofessionalsApp.Models.Tag", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<bool>("IsDeleted"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Tags"); }); modelBuilder.Entity("UnprofessionalsApp.Models.TagPost", b => { b.Property<int>("TagId"); b.Property<int>("PostId"); b.HasKey("TagId", "PostId"); b.HasIndex("PostId"); b.ToTable("TagsPosts"); }); modelBuilder.Entity("UnprofessionalsApp.Models.UnprofessionalsAppUser", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("DateOfRegistration"); b.Property<string>("Description"); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<int>("ImageId"); b.Property<bool>("IsDeleted"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("ImageId"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<int>") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b => { b.HasOne("UnprofessionalsApp.Models.UnprofessionalsAppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b => { b.HasOne("UnprofessionalsApp.Models.UnprofessionalsAppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<int>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<int>") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("UnprofessionalsApp.Models.UnprofessionalsAppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b => { b.HasOne("UnprofessionalsApp.Models.UnprofessionalsAppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("UnprofessionalsApp.Models.Comment", b => { b.HasOne("UnprofessionalsApp.Models.Post", "Post") .WithMany("Comments") .HasForeignKey("PostId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("UnprofessionalsApp.Models.UnprofessionalsAppUser", "User") .WithMany("Comments") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("UnprofessionalsApp.Models.Post", b => { b.HasOne("UnprofessionalsApp.Models.Category", "Category") .WithMany("Posts") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("UnprofessionalsApp.Models.Firm", "Firm") .WithMany("Posts") .HasForeignKey("FirmId"); b.HasOne("UnprofessionalsApp.Models.Image", "Image") .WithMany("Posts") .HasForeignKey("ImageId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("UnprofessionalsApp.Models.UnprofessionalsAppUser", "User") .WithMany("Posts") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("UnprofessionalsApp.Models.Reply", b => { b.HasOne("UnprofessionalsApp.Models.Comment", "Comment") .WithMany("Replies") .HasForeignKey("CommentId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("UnprofessionalsApp.Models.UnprofessionalsAppUser", "User") .WithMany("Replies") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("UnprofessionalsApp.Models.Report", b => { b.HasOne("UnprofessionalsApp.Models.Comment", "Comment") .WithMany("Reports") .HasForeignKey("CommentId"); b.HasOne("UnprofessionalsApp.Models.Firm", "Firm") .WithMany("Reports") .HasForeignKey("FirmId"); b.HasOne("UnprofessionalsApp.Models.Post", "Post") .WithMany("Reports") .HasForeignKey("PostId"); b.HasOne("UnprofessionalsApp.Models.Reply", "Reply") .WithMany("Reports") .HasForeignKey("ReplyId"); b.HasOne("UnprofessionalsApp.Models.UnprofessionalsAppUser", "ReportedUser") .WithMany("Reports") .HasForeignKey("ReportedUserId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("UnprofessionalsApp.Models.UnprofessionalsAppUser", "User") .WithMany("CreatedReports") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("UnprofessionalsApp.Models.TagPost", b => { b.HasOne("UnprofessionalsApp.Models.Post", "Post") .WithMany("Tags") .HasForeignKey("PostId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("UnprofessionalsApp.Models.Tag", "Tag") .WithMany("Posts") .HasForeignKey("TagId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("UnprofessionalsApp.Models.UnprofessionalsAppUser", b => { b.HasOne("UnprofessionalsApp.Models.Image", "Image") .WithMany("Users") .HasForeignKey("ImageId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
34.989011
125
0.470844
[ "MIT" ]
sapphire119/NullPro
src/Data/UnprofessionalsApp.Data/Migrations/UnprofessionalsDbContextModelSnapshot.cs
19,106
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // Управление общими сведениями о сборке осуществляется с помощью // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("Memoria.Client")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Memoria.Client")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми // для COM-компонентов. Если требуется обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] //Чтобы начать сборку локализованных приложений, задайте //<UICulture>CultureYouAreCodingWith</UICulture> в файле .csproj //внутри <PropertyGroup>. Например, если используется английский США //в своих исходных файлах установите <UICulture> в en-US. Затем отмените преобразование в комментарий //атрибута NeutralResourceLanguage ниже. Обновите "en-US" в //строка внизу для обеспечения соответствия настройки UICulture в файле проекта. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам //(используется, если ресурс не найден на странице // или в словарях ресурсов приложения) ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов //(используется, если ресурс не найден на странице, // в приложении или в каких-либо словарях ресурсов для конкретной темы) )] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номера сборки и редакции по умолчанию // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
43.446429
117
0.724209
[ "MIT" ]
Albeoris/Memoria
Memoria.Client/Properties/AssemblyInfo.cs
3,423
C#
using System; using System.Collections.Generic; using System.Linq; namespace TestClient { public class StartUp { public static void Main() { string[] input = Console.ReadLine().Split().ToArray(); Dictionary<int, BankAccount> accounts = new Dictionary<int, BankAccount>(); while (input[0] != "End") { switch (input[0]) { case "Create": Create(input, accounts); break; case "Deposit": Decposit(input, accounts); break; case "Withdraw": Withdraw(input, accounts); break; case "Print": Print(input, accounts); break; } input = Console.ReadLine().Split().ToArray(); } } private static void Print(string[] input, Dictionary<int, BankAccount> accounts) { int id = int.Parse(input[1]); if (accounts.ContainsKey(id)) { Console.WriteLine(accounts[id]); } else { Console.WriteLine("Account does not exist"); } } private static void Withdraw(string[] input, Dictionary<int, BankAccount> accounts) { int id = int.Parse(input[1]); decimal amount = decimal.Parse(input[2]); if (accounts.ContainsKey(id)) { if (accounts[id].Balance >= amount) { accounts[id].Balance -= amount; } else { Console.WriteLine("Insufficient balance"); } } else { Console.WriteLine("Account does not exist"); } } private static void Decposit(string[] input, Dictionary<int, BankAccount> accounts) { int id = int.Parse(input[1]); decimal amount = decimal.Parse(input[2]); if (accounts.ContainsKey(id)) { accounts[id].Balance += amount; } else { Console.WriteLine("Account does not exist"); } } private static void Create(string[] input, Dictionary<int, BankAccount> accounts) { int id = int.Parse(input[1]); if (!accounts.ContainsKey(id)) { BankAccount acc = new BankAccount(); acc.Id = id; accounts.Add(id, acc); } else { Console.WriteLine("Account already exists"); } } } }
28.028846
91
0.428473
[ "MIT" ]
DanielBankov/SoftUni
C# Fundamentals/C# OOP Basics/01. Defining Classes - Lab/TestClient/StartUp.cs
2,917
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Identity.AccessContextManager.V1.Snippets { // [START accesscontextmanager_v1_generated_AccessContextManager_ListAccessPolicies_async] using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Identity.AccessContextManager.V1; using System; using System.Linq; using System.Threading.Tasks; public sealed partial class GeneratedAccessContextManagerClientSnippets { /// <summary>Snippet for ListAccessPoliciesAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task ListAccessPoliciesRequestObjectAsync() { // Create client AccessContextManagerClient accessContextManagerClient = await AccessContextManagerClient.CreateAsync(); // Initialize request argument(s) ListAccessPoliciesRequest request = new ListAccessPoliciesRequest { ParentAsOrganizationName = OrganizationName.FromOrganization("[ORGANIZATION]"), }; // Make the request PagedAsyncEnumerable<ListAccessPoliciesResponse, AccessPolicy> response = accessContextManagerClient.ListAccessPoliciesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((AccessPolicy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAccessPoliciesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AccessPolicy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AccessPolicy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AccessPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } // [END accesscontextmanager_v1_generated_AccessContextManager_ListAccessPolicies_async] }
43.790123
146
0.654074
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Identity.AccessContextManager.V1/Google.Identity.AccessContextManager.V1.GeneratedSnippets/AccessContextManagerClient.ListAccessPoliciesRequestObjectAsyncSnippet.g.cs
3,547
C#
using System; namespace JugaAgenda_v2 { class Work { public enum Status { todo_no_components, todo_yes_components, // 5 = yellow doing, // 9 = blue done, // 2 = green cancel // 8 = gray } private string description; private decimal duration; private string clientName; private string phoneNumber; private string orderNumber; private Status status; public Work() { } public Work(decimal duration, string clientName, string phoneNumber, string orderNumber, string description, Status status) { this.description = description; this.duration = duration; this.clientName = clientName; this.phoneNumber = phoneNumber; this.orderNumber = orderNumber; this.status = status; } public Work(string[] title, string description, Status status) { for (int i = 0; i < title.Length; i++) { if (i == 0) this.duration = Convert.ToDecimal(title[i].Split('u')[0].Replace('.', ',')); if (i == 1) this.clientName = title[i]; if (i == 1) this.phoneNumber = title[i]; if (i == 1) this.orderNumber = title[i]; } this.description = description; this.status = status; } public Work(string[] title, string description, int colorID) { for (int i = 0; i < title.Length; i++) { if (i == 0) this.duration = Convert.ToDecimal(title[i].Split('u')[0].Replace('.', ',')); if (i == 1) this.clientName = title[i]; if (i == 2) this.phoneNumber = title[i]; if (i == 3) this.orderNumber = title[i]; } this.description = description; this.status = colorID_to_status(colorID); } public Work(Google.Apis.Calendar.v3.Data.Event item) { if (check_title(item.Summary)) { String[] title = item.Summary.Split(' '); for (int i = 0; i < title.Length; i++) { if (i == 0) this.duration = Convert.ToDecimal(title[i].Split('u')[0].Replace('.', ',')); if (i == 1) this.clientName = title[i]; if (i == 2) this.phoneNumber = title[i]; if (i == 3) this.orderNumber = title[i]; } this.description = item.Description; this.status = colorID_to_status((int) Convert.ToInt64(item.ColorId)); } } public Status colorID_to_status(int colorID) { switch (colorID) { case 5: return Status.todo_yes_components; case 9: return Status.doing; case 2: return Status.done; case 8: return Status.cancel; default: return Status.todo_no_components; } } public int status_to_colorID(Status status) { switch (status) { case Status.todo_yes_components: return 5; case Status.doing: return 9; case Status.done: return 2; case Status.cancel: return 8; default: return 0; } } public bool check_title(String title) { String[] titleArray = title.Split(' '); if (titleArray.Length < 3 || titleArray.Length > 4) return false; try { if (!titleArray[0].Substring(titleArray[0].Length - 1).Equals("u")) return false; foreach (char c in titleArray[0].Split('u')[0]) if (!"0123456789.,".Contains(c.ToString())) return false; } catch { return false; } return true; } #region getters public string getDescription() { return description; } public decimal getDuration() { return duration; } public string getClientName() { return clientName; } public string getPhoneNumber() { return phoneNumber; } public string getOrderNumber() { return orderNumber; } public Status getStatus() { return status; } public int getColorID() { switch (this.status) { case Status.todo_yes_components: return 5; case Status.doing: return 9; case Status.done: return 2; case Status.cancel: return 8; default: return 0; } } #endregion #region setters public void setDescription(string description) { this.description = description; } public void setDuration(decimal duration) { this.duration = duration; } public void setClientName(string clientName) { this.clientName = clientName; } public void setPhoneNumber(string phoneNumber) { this.phoneNumber = phoneNumber; } public void setOrderNumber(string orderNumber) { this.orderNumber = orderNumber; } public void setStatus(Status status) { this.status = status; } #endregion } }
28.850962
131
0.460757
[ "MIT" ]
Arno1235Official/JugaAgenda
JugaAgenda_v2/Classes/Work.cs
6,003
C#
// *********************************************************************** // Copyright (c) 2004 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Globalization; using System.IO; using NUnit.TestUtilities; namespace NUnit.Framework.Assertions { [TestFixture] public class AssertEqualsTests { [Test] public void Equals() { string nunitString = "Hello NUnit"; string expected = nunitString; string actual = nunitString; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual); } [Test] public void EqualsNull() { Assert.AreEqual(null, null); } [Test] public void Bug575936Int32Int64Comparison() { long l64 = 0; int i32 = 0; Assert.AreEqual(i32, l64); } [Test] public void Bug524CharIntComparision() { char c = '\u0000'; Assert.AreEqual(0, c); } [Test] public void Bug524CharIntWithoutOverload() { char c = '\u0000'; Assert.That(c, Is.EqualTo(0)); } [Test] public void CharCharComparision() { char c = 'a'; Assert.That(c, Is.EqualTo('a')); } [Test] public void IntegerLongComparison() { Assert.AreEqual(1, 1L); Assert.AreEqual(1L, 1); } [Test] public void IntegerEquals() { int val = 42; Assert.AreEqual(val, 42); } [Test] public void EqualsFail() { string junitString = "Goodbye JUnit"; string expected = "Hello NUnit"; var expectedMessage = " Expected string length 11 but was 13. Strings differ at index 0." + Env.NewLine + " Expected: \"Hello NUnit\"" + Env.NewLine + " But was: \"Goodbye JUnit\"" + Env.NewLine + " -----------^" + Env.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(expected, junitString)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void EqualsNaNFails() { var expectedMessage = " Expected: 1.234d +/- 0.0d" + Env.NewLine + " But was: " + Double.NaN + Env.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(1.234, Double.NaN, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void NanEqualsFails() { var expectedMessage = " Expected: " + Double.NaN + Env.NewLine + " But was: 1.234d" + Env.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(Double.NaN, 1.234, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void NanEqualsNaNSucceeds() { Assert.AreEqual(Double.NaN, Double.NaN, 0.0); } [Test] public void NegInfinityEqualsInfinity() { Assert.AreEqual(Double.NegativeInfinity, Double.NegativeInfinity, 0.0); } [Test] public void PosInfinityEqualsInfinity() { Assert.AreEqual(Double.PositiveInfinity, Double.PositiveInfinity, 0.0); } [Test] public void PosInfinityNotEquals() { var expectedMessage = " Expected: " + Double.PositiveInfinity + Env.NewLine + " But was: 1.23d" + Env.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(Double.PositiveInfinity, 1.23, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void PosInfinityNotEqualsNegInfinity() { var expectedMessage = " Expected: " + Double.PositiveInfinity + Env.NewLine + " But was: " + Double.NegativeInfinity + Env.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(Double.PositiveInfinity, Double.NegativeInfinity, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void SinglePosInfinityNotEqualsNegInfinity() { var expectedMessage = " Expected: " + Double.PositiveInfinity + Env.NewLine + " But was: " + Double.NegativeInfinity + Env.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(float.PositiveInfinity, float.NegativeInfinity, (float)0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #if !NETCF [Test] public void EqualsThrowsException() { object o = new object(); Assert.Throws<InvalidOperationException>(() => Assert.Equals(o, o)); } [Test] public void ReferenceEqualsThrowsException() { object o = new object(); Assert.Throws<InvalidOperationException>(() => Assert.ReferenceEquals(o, o)); } #endif [Test] public void Float() { float val = (float)1.0; float expected = val; float actual = val; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual, (float)0.0); } [Test] public void Byte() { byte val = 1; byte expected = val; byte actual = val; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual); } [Test] public void String() { string s1 = "test"; string s2 = new System.Text.StringBuilder(s1).ToString(); Assert.IsTrue(s1.Equals(s2)); Assert.AreEqual(s1,s2); } [Test] public void Short() { short val = 1; short expected = val; short actual = val; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual); } [Test] public void Int() { int val = 1; int expected = val; int actual = val; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual); } [Test] public void UInt() { uint val = 1; uint expected = val; uint actual = val; Assert.IsTrue(expected == actual); Assert.AreEqual(expected, actual); } [Test] public void Decimal() { decimal expected = 100m; decimal actual = 100.0m; int integer = 100; Assert.IsTrue( expected == actual ); Assert.AreEqual(expected, actual); Assert.IsTrue(expected == integer); Assert.AreEqual(expected, integer); Assert.IsTrue(actual == integer); Assert.AreEqual(actual, integer); } /// <summary> /// Checks to see that a value comparison works with all types. /// Current version has problems when value is the same but the /// types are different...C# is not like Java, and doesn't automatically /// perform value type conversion to simplify this type of comparison. /// /// Related to Bug575936Int32Int64Comparison, but covers all numeric /// types. /// </summary> [Test] public void EqualsSameTypes() { byte b1 = 35; sbyte sb2 = 35; decimal d4 = 35; double d5 = 35; float f6 = 35; int i7 = 35; uint u8 = 35; long l9 = 35; short s10 = 35; ushort us11 = 35; char c1 = '3'; char c2 = 'a'; System.Byte b12 = 35; System.SByte sb13 = 35; System.Decimal d14 = 35; System.Double d15 = 35; System.Single s16 = 35; System.Int32 i17 = 35; System.UInt32 ui18 = 35; System.Int64 i19 = 35; System.UInt64 ui20 = 35; System.Int16 i21 = 35; System.UInt16 i22 = 35; System.Char c12 = '3'; System.Char c22 = 'a'; Assert.AreEqual(35, b1); Assert.AreEqual(35, sb2); Assert.AreEqual(35, d4); Assert.AreEqual(35, d5); Assert.AreEqual(35, f6); Assert.AreEqual(35, i7); Assert.AreEqual(35, u8); Assert.AreEqual(35, l9); Assert.AreEqual(35, s10); Assert.AreEqual(35, us11); Assert.AreEqual('3', c1); Assert.AreEqual('a', c2); Assert.AreEqual( 35, b12 ); Assert.AreEqual( 35, sb13 ); Assert.AreEqual( 35, d14 ); Assert.AreEqual( 35, d15 ); Assert.AreEqual( 35, s16 ); Assert.AreEqual( 35, i17 ); Assert.AreEqual( 35, ui18 ); Assert.AreEqual( 35, i19 ); Assert.AreEqual( 35, ui20 ); Assert.AreEqual( 35, i21 ); Assert.AreEqual( 35, i22 ); Assert.AreEqual('3', c12); Assert.AreEqual('a', c22); byte? b23 = 35; sbyte? sb24 = 35; decimal? d25 = 35; double? d26 = 35; float? f27 = 35; int? i28 = 35; uint? u29 = 35; long? l30 = 35; short? s31 = 35; ushort? us32 = 35; char? c3 = '3'; char? c4 = 'a'; Assert.AreEqual(35, b23); Assert.AreEqual(35, sb24); Assert.AreEqual(35, d25); Assert.AreEqual(35, d26); Assert.AreEqual(35, f27); Assert.AreEqual(35, i28); Assert.AreEqual(35, u29); Assert.AreEqual(35, l30); Assert.AreEqual(35, s31); Assert.AreEqual(35, us32); Assert.AreEqual('3', c3); Assert.AreEqual('a', c4); } [Test] public void EnumsEqual() { MyEnum actual = MyEnum.a; Assert.AreEqual( MyEnum.a, actual ); } [Test] public void EnumsNotEqual() { MyEnum actual = MyEnum.a; var expectedMessage = " Expected: c" + Env.NewLine + " But was: a" + Env.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual( MyEnum.c, actual )); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void DateTimeEqual() { DateTime dt1 = new DateTime( 2005, 6, 1, 7, 0, 0 ); DateTime dt2 = new DateTime( 2005, 6, 1, 0, 0, 0 ) + TimeSpan.FromHours( 7.0 ); Assert.AreEqual( dt1, dt2 ); } [Test] public void DateTimeNotEqual() { DateTime dt1 = new DateTime( 2005, 6, 1, 7, 0, 0 ); DateTime dt2 = new DateTime( 2005, 6, 1, 0, 0, 0 ); var expectedMessage = " Expected: 2005-06-01 07:00:00.000" + Env.NewLine + " But was: 2005-06-01 00:00:00.000" + Env.NewLine; var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(dt1, dt2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #if !PORTABLE [Test] public void DirectoryInfoEqual() { using (var testDir = new TestDirectory()) { var one = new DirectoryInfo(testDir.Directory.FullName); var two = new DirectoryInfo(testDir.Directory.FullName); Assert.AreEqual(one, two); } } [Test] public void DirectoryInfoNotEqual() { using (var one = new TestDirectory()) using (var two = new TestDirectory()) { var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(one.Directory, two.Directory)); } } #endif private enum MyEnum { a, b, c } [Test] public void DoubleNotEqualMessageDisplaysAllDigits() { string message = ""; try { double d1 = 36.1; double d2 = 36.099999999999994; Assert.AreEqual( d1, d2 ); } catch(AssertionException ex) { message = ex.Message; } if ( message == "" ) Assert.Fail( "Should have thrown an AssertionException" ); int i = message.IndexOf('3'); int j = message.IndexOf( 'd', i ); string expected = message.Substring( i, j - i + 1 ); i = message.IndexOf( '3', j ); j = message.IndexOf( 'd', i ); string actual = message.Substring( i , j - i + 1 ); Assert.AreNotEqual( expected, actual ); } [Test] public void FloatNotEqualMessageDisplaysAllDigits() { string message = ""; try { float f1 = 36.125F; float f2 = 36.125004F; Assert.AreEqual( f1, f2 ); } catch(AssertionException ex) { message = ex.Message; } if ( message == "" ) Assert.Fail( "Should have thrown an AssertionException" ); int i = message.IndexOf( '3' ); int j = message.IndexOf( 'f', i ); string expected = message.Substring( i, j - i + 1 ); i = message.IndexOf( '3', j ); j = message.IndexOf( 'f', i ); string actual = message.Substring( i, j - i + 1 ); Assert.AreNotEqual( expected, actual ); } [Test] public void DoubleNotEqualMessageDisplaysTolerance() { string message = ""; try { double d1 = 0.15; double d2 = 0.12; double tol = 0.005; Assert.AreEqual(d1, d2, tol); } catch (AssertionException ex) { message = ex.Message; } if (message == "") Assert.Fail("Should have thrown an AssertionException"); Assert.That(message, Does.Contain("+/- 0.005")); } [Test] public void FloatNotEqualMessageDisplaysTolerance() { string message = ""; try { float f1 = 0.15F; float f2 = 0.12F; float tol = 0.001F; Assert.AreEqual( f1, f2, tol ); } catch( AssertionException ex ) { message = ex.Message; } if ( message == "" ) Assert.Fail( "Should have thrown an AssertionException" ); Assert.That(message, Does.Contain( "+/- 0.001")); } [Test] public void DoubleNotEqualMessageDisplaysDefaultTolerance() { string message = ""; GlobalSettings.DefaultFloatingPointTolerance = 0.005d; try { double d1 = 0.15; double d2 = 0.12; Assert.AreEqual(d1, d2); } catch (AssertionException ex) { message = ex.Message; } finally { GlobalSettings.DefaultFloatingPointTolerance = 0.0d; } if (message == "") Assert.Fail("Should have thrown an AssertionException"); Assert.That(message, Does.Contain("+/- 0.005")); } [Test] public void DoubleNotEqualWithNanDoesNotDisplayDefaultTolerance() { string message = ""; GlobalSettings.DefaultFloatingPointTolerance = 0.005d; try { double d1 = double.NaN; double d2 = 0.12; Assert.AreEqual(d1, d2); } catch (AssertionException ex) { message = ex.Message; } finally { GlobalSettings.DefaultFloatingPointTolerance = 0.0d; } if (message == "") Assert.Fail("Should have thrown an AssertionException"); Assert.That(message.IndexOf("+/-") == -1); } [Test] public void IEquatableSuccess_OldSyntax() { IntEquatable a = new IntEquatable(1); Assert.AreEqual(1, a); Assert.AreEqual(a, 1); } [Test] public void IEquatableSuccess_ConstraintSyntax() { IntEquatable a = new IntEquatable(1); Assert.That(a, Is.EqualTo(1)); Assert.That(1, Is.EqualTo(a)); } } public class IntEquatable : IEquatable<int> { private int i; public IntEquatable(int i) { this.i = i; } public bool Equals(int other) { return i.Equals(other); } } }
30.053543
138
0.48842
[ "MIT" ]
Oipo/nunit
src/NUnitFramework/tests/Assertions/AssertEqualsTests.cs
19,086
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Modifications Copyright (c) C Daniel Waddell. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace ExampleSingleSignOn { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
27.708333
107
0.652632
[ "Apache-2.0" ]
cdwaddell/ExampleSingleSignOn
ExampleSingleSignOn/Program.cs
667
C#
using Newtonsoft.Json; using System; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using System.Runtime.Serialization; namespace OneUpside.Data { /// <summary> /// A serialisable function. /// </summary> /// <typeparam name="A">Argument type</typeparam> /// <typeparam name="B">Argument type</typeparam> /// <typeparam name="R">Return type</typeparam> [DataContract] public sealed class SFunc<A,B,R> { [DataMember] private SFuncData Data; /// <summary> /// Construct a <see cref="SFunc{A, B, R}"/>. /// </summary> /// <param name="func"> /// A public method (instance or static) castable to /// <see cref="Func{A,B,R}" /> If an instance method, the object must be /// serializable. /// </param> /// <param name="obj"> /// If <paramref name="func" /> is an instance method then this must be /// an appropriate and serializable object. Otherwise, if it is a static /// method then this must be null. /// </param> public SFunc(object obj, MethodInfo func) { Contract.Requires ( func.GetParameters().Equals(new Type[] { typeof(A), typeof(B) }) && func.ReturnType.Equals(typeof(R)) && ( (!func.IsStatic && obj != null) || (func.IsStatic && obj == null) ) ); Data = new SFuncData { DeclaringTypeName = func.DeclaringType.AssemblyQualifiedName , MethodName = func.Name , Instance = obj }; } [JsonConstructor] private SFunc(SFuncData data) { Data = data; } /// <summary> /// Apply this function to arguments. /// </summary> /// <param name="a">Function argument</param> /// <param name="b">Function argument</param> /// <returns>Function return value</returns> public R Apply(A a, B b) { var parameterTypes = new Type[] { typeof(A), typeof(B) }; var method = Type.GetType(Data.DeclaringTypeName).GetTypeInfo() .DeclaredMethods .Where ( m => m.Name == Data.MethodName && m.GetParameters() .Select(p => p.ParameterType) .SequenceEqual(parameterTypes) ) .First(); return (R)method.Invoke(Data.Instance, new object[] { a, b }); } } }
28.621951
79
0.577759
[ "BSD-3-Clause" ]
1Upside/OneUpside-Data
SFunc`3.cs
2,349
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.Azure.Cdn.Outputs { [OutputType] public sealed class EndpointDeliveryRuleCookiesCondition { /// <summary> /// List of values for the cookie. This is required if `operator` is not `Any`. /// </summary> public readonly ImmutableArray<string> MatchValues; /// <summary> /// Defaults to `false`. /// </summary> public readonly bool? NegateCondition; /// <summary> /// Valid values are `Any`, `BeginsWith`, `Contains`, `EndsWith`, `Equal`, `GreaterThan`, `GreaterThanOrEqual`, `LessThan` and `LessThanOrEqual`. /// </summary> public readonly string Operator; /// <summary> /// Name of the cookie. /// </summary> public readonly string Selector; /// <summary> /// Valid values are `Lowercase` and `Uppercase`. /// </summary> public readonly ImmutableArray<string> Transforms; [OutputConstructor] private EndpointDeliveryRuleCookiesCondition( ImmutableArray<string> matchValues, bool? negateCondition, string @operator, string selector, ImmutableArray<string> transforms) { MatchValues = matchValues; NegateCondition = negateCondition; Operator = @operator; Selector = selector; Transforms = transforms; } } }
31.035088
153
0.607123
[ "ECL-2.0", "Apache-2.0" ]
ScriptBox99/pulumi-azure
sdk/dotnet/Cdn/Outputs/EndpointDeliveryRuleCookiesCondition.cs
1,769
C#
#pragma checksum "D:\C#\Projects\IdentityDemo\IdentityDemo\Areas\Identity\Pages\Account\Manage\_StatusMessage.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "caf0ba0e017fe2d5d40e06cba52017213983ba34" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(IdentityDemo.Areas.Identity.Pages.Account.Manage.Areas_Identity_Pages_Account_Manage__StatusMessage), @"mvc.1.0.view", @"/Areas/Identity/Pages/Account/Manage/_StatusMessage.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Areas/Identity/Pages/Account/Manage/_StatusMessage.cshtml", typeof(IdentityDemo.Areas.Identity.Pages.Account.Manage.Areas_Identity_Pages_Account_Manage__StatusMessage))] namespace IdentityDemo.Areas.Identity.Pages.Account.Manage { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "D:\C#\Projects\IdentityDemo\IdentityDemo\Areas\Identity\Pages\_ViewImports.cshtml" using Microsoft.AspNetCore.Identity; #line default #line hidden #line 2 "D:\C#\Projects\IdentityDemo\IdentityDemo\Areas\Identity\Pages\_ViewImports.cshtml" using IdentityDemo.Areas.Identity; #line default #line hidden #line 3 "D:\C#\Projects\IdentityDemo\IdentityDemo\Areas\Identity\Pages\_ViewImports.cshtml" using IdentityDemo.Models; #line default #line hidden #line 1 "D:\C#\Projects\IdentityDemo\IdentityDemo\Areas\Identity\Pages\Account\_ViewImports.cshtml" using IdentityDemo.Areas.Identity.Pages.Account; #line default #line hidden #line 1 "D:\C#\Projects\IdentityDemo\IdentityDemo\Areas\Identity\Pages\Account\Manage\_ViewImports.cshtml" using IdentityDemo.Areas.Identity.Pages.Account.Manage; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"caf0ba0e017fe2d5d40e06cba52017213983ba34", @"/Areas/Identity/Pages/Account/Manage/_StatusMessage.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"a7297e96840963242484582ac4debf134c53cf49", @"/Areas/Identity/Pages/_ViewImports.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e226691ce49b029a5ff3fac271e7c6f3abd2ba62", @"/Areas/Identity/Pages/Account/_ViewImports.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"a56ff26ff2e53faf6c70a135cf0a192952e9126e", @"/Areas/Identity/Pages/Account/Manage/_ViewImports.cshtml")] public class Areas_Identity_Pages_Account_Manage__StatusMessage : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<string> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(15, 2, true); WriteLiteral("\r\n"); EndContext(); #line 3 "D:\C#\Projects\IdentityDemo\IdentityDemo\Areas\Identity\Pages\Account\Manage\_StatusMessage.cshtml" if (!String.IsNullOrEmpty(Model)) { var statusMessageClass = Model.StartsWith("Error") ? "danger" : "success"; #line default #line hidden BeginContext(136, 8, true); WriteLiteral(" <div"); EndContext(); BeginWriteAttribute("class", " class=\"", 144, "\"", 201, 4); WriteAttributeValue("", 152, "alert", 152, 5, true); WriteAttributeValue(" ", 157, "alert-", 158, 7, true); #line 6 "D:\C#\Projects\IdentityDemo\IdentityDemo\Areas\Identity\Pages\Account\Manage\_StatusMessage.cshtml" WriteAttributeValue("", 164, statusMessageClass, 164, 19, false); #line default #line hidden WriteAttributeValue(" ", 183, "alert-dismissible", 184, 18, true); EndWriteAttribute(); BeginContext(202, 158, true); WriteLiteral(" role=\"alert\">\r\n <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\r\n "); EndContext(); BeginContext(361, 5, false); #line 8 "D:\C#\Projects\IdentityDemo\IdentityDemo\Areas\Identity\Pages\Account\Manage\_StatusMessage.cshtml" Write(Model); #line default #line hidden EndContext(); BeginContext(366, 14, true); WriteLiteral("\r\n </div>\r\n"); EndContext(); #line 10 "D:\C#\Projects\IdentityDemo\IdentityDemo\Areas\Identity\Pages\Account\Manage\_StatusMessage.cshtml" } #line default #line hidden } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<string> Html { get; private set; } } } #pragma warning restore 1591
53.415094
270
0.741611
[ "MIT" ]
TodorNikolov89/Projects
IdentityDemo/IdentityDemo/obj/Debug/netcoreapp2.2/Razor/Areas/Identity/Pages/Account/Manage/_StatusMessage.cshtml.g.cs
5,662
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using PlaywrightSharp.Chromium; using PlaywrightSharp.Chromium.Protocol.Browser; using PlaywrightSharp.Chromium.Protocol.Emulation; using PlaywrightSharp.Chromium.Protocol.Target; namespace PlaywrightSharp { /// <inheritdoc cref="IBrowserContextDelegate"/> public class ChromiumBrowserContext : IBrowserContextDelegate { private static readonly IReadOnlyDictionary<ContextPermission, PermissionType> WebPermissionToProtocol = new Dictionary<ContextPermission, PermissionType> { // TODO }; private readonly ChromiumSession _client; private readonly string _contextId; private readonly ChromiumBrowser _browser; internal ChromiumBrowserContext(ChromiumSession client, ChromiumBrowser chromiumBrowser) : this(client, chromiumBrowser, null, null) { } internal ChromiumBrowserContext( ChromiumSession client, ChromiumBrowser chromiumBrowser, string contextId, BrowserContextOptions options) { _client = client; _browser = chromiumBrowser; _contextId = contextId; Options = options; } /// <inheritdoc cref="IBrowserContext"/> public BrowserContextOptions Options { get; } /// <inheritdoc cref="IBrowserContextDelegate.BrowserContext"/> public BrowserContext BrowserContext { get; set; } /// <inheritdoc cref="IBrowserContextDelegate.GetPagesAsync"/> public async Task<IPage[]> GetPagesAsync() { var pageTasks = _browser.GetAllTargets() .Where(target => target.BrowserContext == BrowserContext && target.Type == TargetType.Page) .Select(t => t.PageAsync()); var pages = await Task.WhenAll(pageTasks).ConfigureAwait(false); return pages.Where(p => p != null).ToArray(); } /// <inheritdoc cref="IBrowserContextDelegate.NewPage"/> public async Task<IPage> NewPage() { var createTargetRequest = new TargetCreateTargetRequest { Url = "about:blank", }; if (_contextId != null) { createTargetRequest.BrowserContextId = _contextId; } string targetId = (await _client.SendAsync(createTargetRequest) .ConfigureAwait(false)).TargetId; var target = _browser.TargetsMap[targetId]; await target.InitializedTask.ConfigureAwait(false); return await target.PageAsync().ConfigureAwait(false); } /// <inheritdoc cref="IBrowserContextDelegate.SetGeolocationAsync(GeolocationOption)"/> public async Task SetGeolocationAsync(GeolocationOption geolocation) { var request = new EmulationSetGeolocationOverrideRequest(); if (geolocation != null) { request.Accuracy = geolocation.Accuracy; request.Latitude = geolocation.Latitude; request.Longitude = geolocation.Longitude; } foreach (Page page in await BrowserContext.GetPagesAsync().ConfigureAwait(false)) { await ((ChromiumPage)page.Delegate).Client.SendAsync(request).ConfigureAwait(false); } } /// <inheritdoc cref="IBrowserContextDelegate.CloseAsync"/> public async Task CloseAsync() { if (string.IsNullOrEmpty(_contextId)) { throw new PlaywrightSharpException("Non-incognito profiles cannot be closed!"); } await _client.SendAsync(new TargetDisposeBrowserContextRequest { BrowserContextId = _contextId }).ConfigureAwait(false); _browser.RemoveContext(_contextId); } /// <inheritdoc cref="IBrowserContextDelegate.GetExistingPages"/> public IEnumerable<IPage> GetExistingPages() { foreach (var target in _browser.GetAllTargets()) { if (target.BrowserContext == BrowserContext && target.ChromiumPage != null) { yield return target.ChromiumPage.Page; } } } /// <inheritdoc cref="IBrowserContextDelegate.SetPermissionsAsync(string, ContextPermission[])"/> public Task SetPermissionsAsync(string origin, params ContextPermission[] permissions) { return _client.SendAsync(new BrowserGrantPermissionsRequest { Origin = origin, BrowserContextId = _contextId, Permissions = Array.ConvertAll(permissions, permission => WebPermissionToProtocol[permission]), }); } } }
38.136364
163
0.605284
[ "MIT" ]
slang25/playwright-sharp
src/PlaywrightSharp.Chromium/ChromiumBrowserContext.cs
5,034
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("ProjectHelper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ProjectHelper")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("e527cd98-79f0-4e19-a742-60aa6ddeffee")] // 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.675676
84
0.748207
[ "MIT" ]
alecamaracm/SeniorCapstone_LEGO
SeniorCapstone_LEGO_VS/ProjectHelper/Properties/AssemblyInfo.cs
1,397
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DatabaseWorkers { partial class Worker { public override string ToString() { return FirstName + " " + LastName + " (reprimands: " + this.Reprimand.Count + " penalty pts: " + this.Reprimand.Sum(x => x.PenaltyPoints) + ")"; } } }
23.388889
109
0.610451
[ "MIT" ]
kpagacz/software-engineering
programowanie-komponentowe/lab-9/PK_2019_2020_07_DatabaseWorkes/DatabaseWorkers/WorkerExtenstion.cs
423
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace ItLank.CleanArchitecture.Web.Filters { public class ValidateModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid) { context.Result = new BadRequestObjectResult(context.ModelState); } } } }
26.705882
80
0.665198
[ "MIT" ]
ShabanGomaa/CleanArchitecture
src/ItLank.CleanArchitecture.Web/Filters/ValidateModelAttribute.cs
456
C#
// Licensed to Finnovation Labs Limited under one or more agreements. // Finnovation Labs Limited licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using FinnovationLabs.OpenBanking.Library.Connector.Instrumentation; using FinnovationLabs.OpenBanking.Library.Connector.Models.Fapi; using FinnovationLabs.OpenBanking.Library.Connector.Models.Public.PaymentInitiation; using FinnovationLabs.OpenBanking.Library.Connector.Models.Public.VariableRecurringPayments; using FinnovationLabs.OpenBanking.Library.Connector.Models.Public.VariableRecurringPayments.Response; using FinnovationLabs.OpenBanking.Library.Connector.Models.Repository; using FinnovationLabs.OpenBanking.Library.Connector.Operations.ExternalApi; using FinnovationLabs.OpenBanking.Library.Connector.Operations.ExternalApi.PaymentInitiation; using FinnovationLabs.OpenBanking.Library.Connector.Persistence; using FinnovationLabs.OpenBanking.Library.Connector.Services; using DomesticVrpConsentRequest = FinnovationLabs.OpenBanking.Library.Connector.Models.Public.VariableRecurringPayments.Request.DomesticVrpConsent; using VariableRecurringPaymentsModelsPublic = FinnovationLabs.OpenBanking.Library.BankApiModels.UkObRw.V3p1p8.Vrp.Models; namespace FinnovationLabs.OpenBanking.Library.Connector.Models.Persistent.VariableRecurringPayments { /// <summary> /// Persisted type. /// Internal to help ensure public request and response types used on public API. /// </summary> internal partial class DomesticVrpConsent : EntityBase, ISupportsFluentDeleteLocal<DomesticVrpConsent>, IDomesticVrpConsentPublicQuery { public VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentRequest BankApiRequest { get; set; } = null!; /// <summary> /// External API ID, i.e. ID of object at bank. This should be unique between objects created at the /// same bank but we do not assume global uniqueness between objects created at multiple banks. /// </summary> public string ExternalApiId { get; set; } = null!; [ForeignKey("BankRegistrationId")] public BankRegistration BankRegistrationNavigation { get; set; } = null!; [ForeignKey("BankApiSetId")] public BankApiSet BankApiSetNavigation { get; set; } = null!; public List<DomesticVrp> DomesticVrpsNavigation { get; set; } = null!; public List<DomesticVrpConsentAuthContext> DomesticVrpConsentAuthContextsNavigation { get; set; } = null!; public ReadWriteProperty<VariableRecurringPaymentsModelsPublic.OBVRPFundsConfirmationResponse?> BankApiFundsConfirmationResponse { get; set; } = null!; public Guid BankRegistrationId { get; set; } public Guid BankApiSetId { get; set; } public ReadWriteProperty<VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse> BankApiResponse { get; set; } = null!; } internal partial class DomesticVrpConsent : ISupportsFluentReadWritePost<DomesticVrpConsentRequest, DomesticVrpConsentResponse, VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentRequest, VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse> { public DomesticVrpConsentResponse PublicGetResponse => new DomesticVrpConsentResponse( Id, Name, Created, CreatedBy, BankApiResponse, BankRegistrationId, BankApiSetId); public void Initialise( DomesticVrpConsentRequest request, string? createdBy, ITimeProvider timeProvider) { base.Initialise(Guid.NewGuid(), request.Name, createdBy, timeProvider); BankRegistrationId = request.BankRegistrationId; BankApiSetId = request.BankApiSetId; BankApiFundsConfirmationResponse = new ReadWriteProperty<VariableRecurringPaymentsModelsPublic.OBVRPFundsConfirmationResponse?>( null, timeProvider, createdBy); } public void UpdateBeforeApiPost(VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentRequest apiRequest) { BankApiRequest = apiRequest; } public void UpdateAfterApiPost( VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse apiResponse, string? modifiedBy, ITimeProvider timeProvider) { BankApiResponse = new ReadWriteProperty<VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse>( apiResponse, timeProvider, modifiedBy); ExternalApiId = BankApiResponse.Data.Data.ConsentId; } public DomesticVrpConsentResponse PublicPostResponse => PublicGetResponse; public IApiPostRequests<VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentRequest, VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse> ApiPostRequests( PaymentInitiationApi? paymentInitiationApi, VariableRecurringPaymentsApi? variableRecurringPaymentsApi, string bankFinancialId, TokenEndpointResponse tokenEndpointResponse, ProcessedSoftwareStatementProfile processedSoftwareStatementProfile, IInstrumentationClient instrumentationClient) => ApiRequests( paymentInitiationApi, variableRecurringPaymentsApi, bankFinancialId, tokenEndpointResponse, processedSoftwareStatementProfile, instrumentationClient); public IApiRequests<VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentRequest, VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse> ApiRequests( PaymentInitiationApi? paymentInitiationApi, VariableRecurringPaymentsApi? variableRecurringPaymentsApi, string bankFinancialId, TokenEndpointResponse tokenEndpointResponse, ProcessedSoftwareStatementProfile processedSoftwareStatementProfile, IInstrumentationClient instrumentationClient) => variableRecurringPaymentsApi?.VariableRecurringPaymentsApiVersion switch { VariableRecurringPaymentsApiVersion.Version3p1p8 => new ApiRequests< VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentRequest, VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse, VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentRequest, VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse>( new PaymentInitiationGetRequestProcessor(bankFinancialId, tokenEndpointResponse), new PaymentInitiationPostRequestProcessor< VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentRequest>( bankFinancialId, tokenEndpointResponse, instrumentationClient, false, processedSoftwareStatementProfile)), null => throw new NullReferenceException("No VRP API specified for this bank."), _ => throw new ArgumentOutOfRangeException( $"VRP API version {variableRecurringPaymentsApi.VariableRecurringPaymentsApiVersion} not supported.") }; } internal partial class DomesticVrpConsent : ISupportsFluentReadWriteGet<DomesticVrpConsentResponse, VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse> { public IApiGetRequests<VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse> ApiGetRequests( PaymentInitiationApi? paymentInitiationApi, VariableRecurringPaymentsApi? variableRecurringPaymentsApi, string bankFinancialId, TokenEndpointResponse tokenEndpointResponse, ProcessedSoftwareStatementProfile processedSoftwareStatementProfile, IInstrumentationClient instrumentationClient) => ApiRequests( paymentInitiationApi, variableRecurringPaymentsApi, bankFinancialId, tokenEndpointResponse, processedSoftwareStatementProfile, instrumentationClient); public ReadWriteApiType GetReadWriteApiType() => ReadWriteApiType.VariableRecurringPayments; } internal partial class DomesticVrpConsent : ISupportsFluentReadWriteGet<DomesticVrpConsentResponse, VariableRecurringPaymentsModelsPublic.OBVRPFundsConfirmationResponse> { public void UpdateAfterApiGet( VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse apiResponse, string? modifiedBy, ITimeProvider timeProvider) { BankApiResponse = new ReadWriteProperty<VariableRecurringPaymentsModelsPublic.OBDomesticVRPConsentResponse>( apiResponse, timeProvider, modifiedBy); } public void UpdateAfterApiGet( VariableRecurringPaymentsModelsPublic.OBVRPFundsConfirmationResponse apiResponse, string? modifiedBy, ITimeProvider timeProvider) { BankApiFundsConfirmationResponse = new ReadWriteProperty<VariableRecurringPaymentsModelsPublic.OBVRPFundsConfirmationResponse?>( apiResponse, timeProvider, modifiedBy); } IApiGetRequests<VariableRecurringPaymentsModelsPublic.OBVRPFundsConfirmationResponse> ISupportsFluentReadWriteGet<DomesticVrpConsentResponse, VariableRecurringPaymentsModelsPublic.OBVRPFundsConfirmationResponse>.ApiGetRequests( PaymentInitiationApi? paymentInitiationApi, VariableRecurringPaymentsApi? variableRecurringPaymentsApi, string bankFinancialId, TokenEndpointResponse tokenEndpointResponse, ProcessedSoftwareStatementProfile processedSoftwareStatementProfile, IInstrumentationClient instrumentationClient) => variableRecurringPaymentsApi?.VariableRecurringPaymentsApiVersion switch { VariableRecurringPaymentsApiVersion.Version3p1p8 => new ApiGetRequests< VariableRecurringPaymentsModelsPublic.OBVRPFundsConfirmationResponse, VariableRecurringPaymentsModelsPublic.OBVRPFundsConfirmationResponse>( new PaymentInitiationGetRequestProcessor( bankFinancialId, tokenEndpointResponse)), null => throw new NullReferenceException("No VRP API specified for this bank."), _ => throw new ArgumentOutOfRangeException( $"VRP API version {variableRecurringPaymentsApi.VariableRecurringPaymentsApiVersion} not supported.") }; } }
48.90678
121
0.695807
[ "MIT" ]
finlabsuk/open-banking-connector
src/OpenBanking.Library.Connector/Models/Persistent/VariableRecurringPayments/DomesticVrpConsent.cs
11,544
C#
using OpenQA.Selenium.Appium; using SpecFlow.Actions.Appium.Configuration.Android; using SpecFlow.Actions.Appium.Driver; using System; namespace SpecFlow.Actions.Android.Driver { public class AndroidAppDriverOptions : IDriverOptions { private readonly IAndroidConfiguration _androidConfiguration; private readonly Lazy<AppiumOptions> _appiumOptionsLazy; public AppiumOptions Current => _appiumOptionsLazy.Value; public AndroidAppDriverOptions(IAndroidConfiguration androidConfiguration) { _androidConfiguration = androidConfiguration; _appiumOptionsLazy = new Lazy<AppiumOptions>(GetOptions); } private AppiumOptions GetOptions() { var options = new AppiumOptions(); foreach (var capability in _androidConfiguration.Capabilities) { options.AddAdditionalCapability(capability.Key, capability.Value); } return options; } } }
30.69697
82
0.687068
[ "BSD-3-Clause" ]
AngHelll/SpectFlow
Plugins/SpecFlow.Actions.Android/SpecFlow.Actions.Android/Driver/AndroidAppDriverOptions.cs
1,015
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20170301.Outputs { [OutputType] public sealed class MonitorConfigResponse { /// <summary> /// Gets or sets the path relative to the endpoint domain name used to probe for endpoint health. /// </summary> public readonly string? Path; /// <summary> /// Gets or sets the TCP port used to probe for endpoint health. /// </summary> public readonly double? Port; /// <summary> /// Gets or sets the profile-level monitoring status of the Traffic Manager profile. /// </summary> public readonly string? ProfileMonitorStatus; /// <summary> /// Gets or sets the protocol (HTTP or HTTPS) used to probe for endpoint health. /// </summary> public readonly string? Protocol; [OutputConstructor] private MonitorConfigResponse( string? path, double? port, string? profileMonitorStatus, string? protocol) { Path = path; Port = port; ProfileMonitorStatus = profileMonitorStatus; Protocol = protocol; } } }
30.06
105
0.614105
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20170301/Outputs/MonitorConfigResponse.cs
1,503
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 ssm-2014-11-06.normal.json service model. */ using Amazon.Runtime; namespace Amazon.SimpleSystemsManagement.Model { /// <summary> /// Paginator for the DescribeMaintenanceWindowTasks operation ///</summary> public interface IDescribeMaintenanceWindowTasksPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<DescribeMaintenanceWindowTasksResponse> Responses { get; } /// <summary> /// Enumerable containing all of the Tasks /// </summary> IPaginatedEnumerable<MaintenanceWindowTask> Tasks { get; } } }
34.368421
101
0.699847
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/_bcl45+netstandard/IDescribeMaintenanceWindowTasksPaginator.cs
1,306
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 Scantegra.Core.Entities { [System.Runtime.Serialization.DataContractAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9154")] public enum selectedmobileofflineenabledentityrelationships { } }
33.526316
80
0.549451
[ "MIT" ]
scantegra/scantegra
src/Scantegra.Core/Entities/OptionSets/selectedmobileofflineenabledentityrelationships.cs
637
C#
using System.Threading.Tasks; namespace Atrea.PolicyEngine.Policies.Input { /// <summary> /// An async input policy, which can take in an item and return an <see cref="InputPolicyResult" /> to indicate /// whether the item should be processed or not by the policy engine. /// </summary> /// <typeparam name="T">The type of the item to be checked by the <see cref="IAsyncInputPolicy{T}" />.</typeparam> public interface IAsyncInputPolicy<in T> { /// <summary> /// Asynchronously determine whether the item should be processed by the policy engine. /// </summary> /// <param name="item">The item to check.</param> /// <returns>A <see cref="Task{InputPolicyResult}" /> to await, whose result is an <see cref="InputPolicyResult" />.</returns> Task<InputPolicyResult> ShouldProcessAsync(T item); } }
46.736842
134
0.652027
[ "MIT" ]
itabaiyu/atrea-policyengine
src/Atrea.PolicyEngine/Policies/Input/IAsyncInputPolicy.cs
890
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; namespace Microsoft.Practices.EnterpriseLibrary.Validation { /// <summary> /// Helps building validators composed by other validators. /// </summary> public class CompositeValidatorBuilder { private IValidatedElement validatedElement; private List<Validator> valueValidators; private Validator builtValidator; /// <summary> /// Initializes a new instance of the <see cref="CompositeValidatorBuilder"/> class. /// </summary> /// <param name="validatedElement">The element for which a composite validator will be created.</param> public CompositeValidatorBuilder(IValidatedElement validatedElement) { this.validatedElement = validatedElement; this.valueValidators = new List<Validator>(); } /// <summary> /// Returns the validator created by the builder. /// </summary> public Validator GetValidator() { this.builtValidator = this.DoGetValidator(); return this.builtValidator; } /// <summary> /// Creates the composite validator built by the builder. /// </summary> protected virtual Validator DoGetValidator() { // create the appropriate validator Validator validator; if (this.valueValidators.Count == 1) { validator = this.valueValidators[0]; } else { if (CompositionType.And == this.validatedElement.CompositionType) { validator = new AndCompositeValidator(this.valueValidators.ToArray()); } else { validator = new OrCompositeValidator(this.valueValidators.ToArray()); validator.MessageTemplate = this.validatedElement.CompositionMessageTemplate; validator.Tag = this.validatedElement.CompositionTag; } } // add support for ignoring nulls Validator valueValidator; if (this.validatedElement.IgnoreNulls) { valueValidator = new NullIgnoringValidatorWrapper(validator); } else { valueValidator = validator; } return valueValidator; } /// <summary> /// Adds a value validator to the composite validator. /// </summary> /// <param name="valueValidator">The validator to add.</param> public void AddValueValidator(Validator valueValidator) { this.valueValidators.Add(valueValidator); } #region test only properties /// <summary> /// This member supports the Enterprise Library infrastructure and is not intended to be used directly from your code. /// </summary> public bool IgnoreNulls { get { return this.validatedElement.IgnoreNulls; } } /// <summary> /// This member supports the Enterprise Library infrastructure and is not intended to be used directly from your code. /// </summary> public CompositionType CompositionType { get { return this.validatedElement.CompositionType; } } /// <summary> /// This member supports the Enterprise Library infrastructure and is not intended to be used directly from your code. /// </summary> public Validator BuiltValidator { get { return this.builtValidator; } } /// <summary> /// This member supports the Enterprise Library infrastructure and is not intended to be used directly from your code. /// </summary> public IList<Validator> ValueValidators { get { return this.valueValidators; } } #endregion } }
33.774194
126
0.591213
[ "Apache-2.0" ]
Microsoft/validation-application-block
source/Src/Validation/CompositeValidatorBuilder.cs
4,190
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using Knomes.Localize; namespace Knomes.Localize.DataAnnotations { public class LocStringLengthAttribute : StringLengthAttribute { public LocStringLengthAttribute(int maximumLength) : base(maximumLength) { } public string? LocalizationKeyPrefix { get; set; } public override string FormatErrorMessage(string name) { // ensure default value string errorMessage = ""; string localizationKey = ""; if (this.MinimumLength > 0) { if(this.MaximumLength == MinimumLength) { errorMessage = "The '{0}' value must have " + this.MaximumLength + " characters."; localizationKey = "Common.Validation.String.FixedLength"; } else if (this.MaximumLength > this.MaximumLength) { errorMessage = "The '{0}' value must have a minimum length of " + this.MinimumLength + " and may not exceed " + this.MaximumLength + " characters."; localizationKey = "Common.Validation.String.MinMaxLength"; } else { errorMessage = "The '{0}' value must have a minimum length of " + this.MinimumLength + "."; localizationKey = "Common.Validation.String.MinLength"; } } else { errorMessage = "The {0} value may not exceed " + this.MaximumLength + " characters."; localizationKey = "Common.Validation.String.MaxLength"; } // translate using localizer var textService = AnnotationHelper.GetTextService(this); if (!string.IsNullOrEmpty(base.ErrorMessageResourceName)) { errorMessage = textService.Localize(this.ErrorMessageResourceName, errorMessage, name); } else { errorMessage = textService.Localize(localizationKey, errorMessage, name); } return errorMessage; } } }
35.523077
168
0.56518
[ "MIT" ]
knoepdan/Bom
Source/Common/Knomes.Localize/DataAnnotations/LocStringLengthAttribute.cs
2,311
C#
using System; using Microsoft.AspNetCore.Mvc.Rendering; namespace AspNetCoreIdentityFido2Mfa.Areas.Identity.Pages.Account.Manage; public static class ManageNavPages { public static string Index => "Index"; public static string Email => "Email"; public static string ChangePassword => "ChangePassword"; public static string ExternalLogins => "ExternalLogins"; public static string PersonalData => "PersonalData"; public static string TwoFactorAuthentication => "TwoFactorAuthentication"; public static string Fido2Mfa => "Fido2Mfa"; public static string IndexNavClass(ViewContext viewContext) => PageNavClass(viewContext, Index); public static string EmailNavClass(ViewContext viewContext) => PageNavClass(viewContext, Email); public static string ChangePasswordNavClass(ViewContext viewContext) => PageNavClass(viewContext, ChangePassword); public static string ExternalLoginsNavClass(ViewContext viewContext) => PageNavClass(viewContext, ExternalLogins); public static string PersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, PersonalData); public static string TwoFactorAuthenticationNavClass(ViewContext viewContext) => PageNavClass(viewContext, TwoFactorAuthentication); public static string Fido2MfaNavClass(ViewContext viewContext) => PageNavClass(viewContext, Fido2Mfa); private static string PageNavClass(ViewContext viewContext, string page) { var activePage = viewContext.ViewData["ActivePage"] as string ?? System.IO.Path.GetFileNameWithoutExtension(viewContext.ActionDescriptor.DisplayName); return string.Equals(activePage, page, StringComparison.OrdinalIgnoreCase) ? "active" : null; } }
41.44186
137
0.760943
[ "MIT" ]
vanillajonathan/AspNetCoreIdentityFido2Mfa
AspNetCoreIdentityFido2Mfa/Areas/Identity/Pages/Account/Manage/ManageNavPages.cs
1,784
C#
namespace MiniRent.Application.Common.Models; public class Result { internal Result(bool succeeded, IEnumerable<string> errors) { Succeeded = succeeded; Errors = errors.ToArray(); } public bool Succeeded { get; set; } public string[] Errors { get; set; } public static Result Success() { return new Result(true, Array.Empty<string>()); } public static Result Failure(IEnumerable<string> errors) { return new Result(false, errors); } }
20.68
63
0.632495
[ "MIT" ]
r-ost/MiniRent
src/Application/Common/Models/Result.cs
519
C#
using Informapp.InformSystem.WebApi.Models.ExampleValues; using System.Collections.Generic; using System.Diagnostics; namespace Informapp.InformSystem.WebApi.Models.Version1.EndPoints.Tests.Values.TestBodyValues { public partial class TestBodyValuesV1Request : IExampleMemberProvider { static TestBodyValuesV1Request() { if (ExampleAttributeConfiguration.Enabled == true) { var dictionary = new Dictionary<int, int> { { 1, 10 }, { 2, 20 }, { 3, 30 }, }; var example = new TestBodyValuesV1Request { Dictionary = dictionary, }; _ = _container.Add(nameof(example.Dictionary), example.Dictionary); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static readonly ExampleValuesContainer _container = new ExampleValuesContainer(); #pragma warning disable CA1033 // Interface methods should be callable by child types object IExampleMemberProvider.GetExample(string name) #pragma warning restore CA1033 // Interface methods should be callable by child types { return _container.GetExample(name); } } }
33.25
97
0.609774
[ "MIT" ]
InformappNL/informapp-api-dotnet-client
src/WebApi.Models/Version1/EndPoints/Tests/Values/TestBodyValues/TestBodyValuesV1Request.Example.cs
1,332
C#
using DirSync.Interface; using System; using System.Threading.Tasks; namespace DirSync.Reporter { public class VoidSyncProgress : ISyncProgress { public async Task CompleteAsync(string message, TimeSpan elapsed, double ratesInBytesPerMs) { await Task.CompletedTask; } public async Task InitAsync(string message) { await Task.CompletedTask; } } }
22.736842
99
0.650463
[ "MIT" ]
JerryBian/dirsync
src/Reporter/VoidSyncProgress.cs
434
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ModelSetupJsonConverter.cs" company="Hukano"> // Copyright (c) Hukano. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Sundew.Generator.Converters.Json; using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Sundew.Generator.Input; using Sundew.Generator.Output; internal class ModelSetupJsonConverter : JsonConverter { private const string ProviderPropertyName = "Provider"; public override bool CanConvert(Type objectType) { return objectType == typeof(IWriterSetup); } public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { JsonHelper.WriteWithType(writer, value, serializer, ProviderPropertyName); } public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { JObject item = JObject.Load(reader); var modelSetupType = JsonHelper.GetType(item); if (modelSetupType == null) { var modelProviderToken = item[ProviderPropertyName]; if (modelProviderToken != null) { modelSetupType = JsonHelper.GetSetupTypeFromInterface(modelProviderToken, typeof(IModelProvider<,,>), 1); if (modelSetupType != null) { throw new JsonReaderException( $"Error: The model provider type: {modelProviderToken} is invalid or is a type that does not implement {typeof(IModelProvider<,,>)}."); } } } if (modelSetupType != null) { return (IWriterSetup?)item.ToObject(modelSetupType, serializer); } throw new JsonReaderException("Error: No model provider type was specified."); } }
38.818182
159
0.589227
[ "MIT" ]
hugener/Sundew.Generator
Source/Sundew.Generator/Converters/Json/ModelSetupJsonConverter.cs
2,137
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using JetBrains.Annotations; using Microsoft.Data.Entity.Identity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Utilities; using Microsoft.Framework.DependencyInjection; namespace Microsoft.Data.Entity.Storage { public abstract class DataStoreServices { public abstract DataStore Store { get; } public abstract DataStoreCreator Creator { get; } public abstract DataStoreConnection Connection { get; } public abstract ValueGeneratorCache ValueGeneratorCache { get; } public abstract Database Database { get; } public abstract IModelBuilderFactory ModelBuilderFactory { get; } public static Func<IServiceProvider, DbContextService<DataStoreServices>> DataStoreServicesFactory { get { return p => new DbContextService<DataStoreServices>(() => GetStoreServices(p)); } } public static Func<IServiceProvider, DbContextService<DataStore>> DataStoreFactory { get { return p => new DbContextService<DataStore>(() => GetStoreServices(p).Store); } } public static Func<IServiceProvider, DbContextService<Database>> DatabaseFactory { get { return p => new DbContextService<Database>(() => GetStoreServices(p).Database); } } public static Func<IServiceProvider, DbContextService<DataStoreCreator>> DataStoreCreatorFactory { get { return p => new DbContextService<DataStoreCreator>(() => GetStoreServices(p).Creator); } } public static Func<IServiceProvider, DbContextService<ValueGeneratorCache>> ValueGeneratorCacheFactory { get { return p => new DbContextService<ValueGeneratorCache>(() => GetStoreServices(p).ValueGeneratorCache); } } public static Func<IServiceProvider, DbContextService<DataStoreConnection>> ConnectionFactory { get { return p => new DbContextService<DataStoreConnection>(() => GetStoreServices(p).Connection); } } protected static DataStoreServices GetStoreServices([NotNull] IServiceProvider serviceProvider) { Check.NotNull(serviceProvider, "serviceProvider"); return serviceProvider.GetRequiredServiceChecked<DbContextServices>().DataStoreServices; } } }
42.04918
121
0.704094
[ "Apache-2.0" ]
mj1856/EntityFramework
src/EntityFramework.Core/Storage/DataStoreServices.cs
2,565
C#
// <auto-generated /> namespace WypozyczalniaSamochodow.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class moc_typ_opis_auta : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(moc_typ_opis_auta)); string IMigrationMetadata.Id { get { return "201803151748134_moc_typ_opis_auta"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
28.2
100
0.63357
[ "MIT" ]
miloszkulesza/WypozyczalniaSamochodow
WypozyczalniaSamochodow/Migrations/201803151748134_moc_typ_opis_auta.Designer.cs
846
C#
using MicroService.Data.Enums; using System; using System.Collections.Generic; using System.Text; namespace MicroService.Data.Validation { public class JsonResponse : IJsonResponse { /// <summary> /// 错误集合 /// </summary> /// <value>The errors.</value> public ValidationErrors Errors { get; set; } /// <summary> /// 系统错误信息 /// </summary> public string SystemErrorMessage { get; set; } /// <summary> /// 是否验证通过 /// </summary> /// <value><c>true</c> if this instance is valid; otherwise, <c>false</c>.</value> public bool IsValid { get { return Errors == null || Errors.IsValid; } } /// <summary> /// Gets the error property. /// </summary> /// <value>The error property.</value> public string ErrorProperty { get { if (Errors != null && !IsValid) { foreach (ValidationErrorItem validationErrorItem in Errors.ErrorItems) { if (validationErrorItem.PropertyName == "IsAlter") { return "IsAlter"; } } } return string.Empty; } } /// <summary> /// Initializes a new instance of the <see cref="JsonResponse"/> class. /// </summary> public JsonResponse() { Errors = new ValidationErrors(); } /// <summary> /// Gets the error messages. /// </summary> /// <value>The error messages.</value> public string ErrorMessages { get { var errorMessages = new StringBuilder(); if (Errors != null && !IsValid) { foreach (ValidationErrorItem validationErrorItem in Errors.ErrorItems) { errorMessages.AppendFormat("{0}", validationErrorItem.ErrorMessage); } } return errorMessages.ToString(); } } /// <summary> /// 跳转路径 /// </summary> /// <value>The redirect URL.</value> public string RedirectUrl { get; set; } /// <summary> /// 实体Id /// </summary> /// <value>The entity identifier.</value> public Guid EntityId { get; set; } /// <summary> /// 标签 /// </summary> /// <value>The code.</value> public string Code { get; set; } /// <summary> /// 错误类型 /// </summary> /// <value>The type of the error.</value> public ErrorType ErrorType { get; set; } public static JsonResponse Create(bool isValid) { var jsonResponse = new JsonResponse(); if (!isValid) { jsonResponse.Errors.AddSystemError(); } return jsonResponse; } } }
26.6
92
0.450501
[ "MIT" ]
DotNetExample/Surging.GoodDemo
SurgingDemo/01.Infrastructure/MicroService.Data/Validation/JsonResponse.cs
3,250
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityExample.Data; using IdentityExample.Middleware; using IdentityExample.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace IdentityExample { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDefaultIdentity<Student>(options => { options.Password.RequireDigit = true; options.Password.RequiredLength = 7; options.Password.RequireUppercase = true; options.User.RequireUniqueEmail = true; }) .AddEntityFrameworkStores<StudentContext>(); services.AddDbContext<StudentContext>(options => options.UseSqlite("Data Source=student.db")); services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, StudentContext studentContext) { studentContext.Database.EnsureDeleted(); studentContext.Database.EnsureCreated(); app.UseStaticFiles(); app.UseAuthentication(); app.UseNodeModules(env.ContentRootPath); app.UseMvc(routes => { routes.MapRoute( name: "StudentRoute", template: "{controller}/{action}/{id?}", defaults: new { controller = "Student", action = "Index" }, constraints: new { id = "[0-9]+" }); }); } } }
30.245614
110
0.609629
[ "MIT" ]
1RedOne/20486D-DevelopingASPNETMVCWebApplications
Allfiles/Mod11/Democode/01_IdentityExample_end/IdentityExample/Startup.cs
1,726
C#
#if false using NWheels.Compilation.Adapters.Roslyn.SyntaxEmitters; using MetaPrograms.Expressions; using MetaPrograms.Members; using System; using System.Collections.Generic; using System.Text; using Xunit; namespace NWheels.Compilation.Adapters.Roslyn.UnitTests.SyntaxEmitters { public class FieldSyntaxEmitterTests { [Fact] public void ClassWithFields() { //-- arrange var classMember = new TypeMember(MemberVisibility.Public, TypeMemberKind.Class, "ClassOne"); classMember.Members.Add(new FieldMember(classMember, MemberVisibility.Public, MemberModifier.None, typeof(int), "PublicNumber")); classMember.Members.Add(new FieldMember(classMember, MemberVisibility.Protected, MemberModifier.None, typeof(int), "ProtectedNumber")); classMember.Members.Add(new FieldMember(classMember, MemberVisibility.Internal, MemberModifier.None, typeof(int), "InternalNumber")); classMember.Members.Add(new FieldMember(classMember, MemberVisibility.InternalProtected, MemberModifier.None, typeof(int), "InternalProtectedNumber")); classMember.Members.Add(new FieldMember(classMember, MemberVisibility.Private, MemberModifier.None, typeof(int), "_privateNumber")); classMember.Members.Add(new FieldMember(classMember, MemberVisibility.Public, MemberModifier.Static, typeof(string), "PublicString")); classMember.Members.Add(new FieldMember(classMember, MemberVisibility.Protected, MemberModifier.Static, typeof(string), "ProtectedString")); classMember.Members.Add(new FieldMember(classMember, MemberVisibility.Internal, MemberModifier.Static, typeof(string), "InternalString")); classMember.Members.Add(new FieldMember(classMember, MemberVisibility.InternalProtected, MemberModifier.Static, typeof(string), "InternalProtectedString")); classMember.Members.Add(new FieldMember(classMember, MemberVisibility.Private, MemberModifier.Static, typeof(string), "_s_privateString")); var emitter = new ClassSyntaxEmitter(classMember); //-- act var syntax = emitter.EmitSyntax(); //-- assert syntax.Should().BeEquivalentToCode(@" public class ClassOne { public int PublicNumber; internal protected int InternalProtectedNumber; protected int ProtectedNumber; internal int InternalNumber; private int _privateNumber; public static string PublicString; internal protected static string InternalProtectedString; protected static string ProtectedString; internal static string InternalString; private static string _s_privateString; } "); } [Fact] public void FieldWithInitializer() { //-- arrange var classMember = new TypeMember(MemberVisibility.Public, TypeMemberKind.Class, "ClassOne"); var fieldMember = new FieldMember(classMember, MemberVisibility.Private, MemberModifier.None, typeof(int), "_number") { IsReadOnly = true, Initializer = new ConstantExpression { Value = 123 } }; classMember.Members.Add(fieldMember); var emitter = new ClassSyntaxEmitter(classMember); //-- act var syntax = emitter.EmitSyntax(); //-- assert syntax.Should().BeEquivalentToCode(@" public class ClassOne { private readonly int _number = 123; } "); } } } #endif
41.48913
168
0.645271
[ "MIT" ]
felix-b/MetaPrograms
Source/MetaPrograms.CSharp.Tests/Writer/SyntaxEmitters/FieldSyntaxEmitterTests.cs
3,819
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.ErrorReporting { internal static class WatsonExtensions { public static void SetCallstackIfEmpty(this Exception exception) { // There have been cases where a new, unthrown exception has been passed to this method. // In these cases the exception won't have a stack trace, which isn't very helpful. We // throw and catch the exception here as that will result in a stack trace that is // better than nothing. if (exception.StackTrace != null) { return; } try { throw exception; } catch { // Empty; we just need the exception to have a stack trace. } } } }
31.787879
100
0.586273
[ "MIT" ]
AlexanderSemenyak/roslyn
src/VisualStudio/Core/Def/Watson/WatsonExtensions.cs
1,051
C#
using System; using System.Collections.Generic; using System.Linq; public class AddingPolynomial { public static void Main() { var length = int.Parse(Console.ReadLine()); var first = Console.ReadLine(); var second = Console.ReadLine(); var sum = SumOfArrays(first, second, length); Console.WriteLine(string.Join(" ", sum)); } private static List<int> SumOfArrays(string first, string second, int length) { int[] firstNumber = ConvertToArray(first); int[] secondNumber = ConvertToArray(second); List<int> sum = new List<int>(); for (int i = 0; i < length; i++) { var temp = firstNumber[i] + secondNumber[i]; sum.Add(temp); } return sum; } private static int[] ConvertToArray(string number) { int[] num = number .Split(' ') .Select(int.Parse) .ToArray(); return num; } }
23.452381
81
0.559391
[ "MIT" ]
dushka-dragoeva/TelerikSeson2016
Programing C#/C # Part II/03. Methods-Homework/11. Adding-Polynomial/AddingPolynomial.cs
987
C#
using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; using SharpBrick.PoweredUp.Functions; using static SharpBrick.PoweredUp.Directions; namespace Example; public class ExampleCalibrationSteering : BaseExample { public override async Task ExecuteAsync() { using var technicMediumHub = Host.FindByType<TechnicMediumHub>(); var motor = technicMediumHub.A.GetDevice<TechnicLargeLinearMotor>(); var calibration = ServiceProvider.GetService<LinearMidCalibration>(); await calibration.ExecuteAsync(motor); await technicMediumHub.WaitButtonClickAsync(); await motor.GotoPositionAsync(CW * 50, 20, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile); await technicMediumHub.WaitButtonClickAsync(); await motor.GotoPositionAsync(CCW * 50, 20, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile); await Task.Delay(5000); await technicMediumHub.SwitchOffAsync(); } }
32
111
0.75293
[ "MIT" ]
Berdsen/powered-up
examples/SharpBrick.PoweredUp.Examples/ExampleCalibrationSteering.cs
1,024
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/UserEnv.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='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW"]/*' /> public unsafe partial struct GROUP_POLICY_OBJECTW { /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.dwOptions"]/*' /> [NativeTypeName("DWORD")] public uint dwOptions; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.dwVersion"]/*' /> [NativeTypeName("DWORD")] public uint dwVersion; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.lpDSPath"]/*' /> [NativeTypeName("LPWSTR")] public ushort* lpDSPath; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.lpFileSysPath"]/*' /> [NativeTypeName("LPWSTR")] public ushort* lpFileSysPath; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.lpDisplayName"]/*' /> [NativeTypeName("LPWSTR")] public ushort* lpDisplayName; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.szGPOName"]/*' /> [NativeTypeName("WCHAR [50]")] public fixed ushort szGPOName[50]; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.GPOLink"]/*' /> public GPO_LINK GPOLink; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.lParam"]/*' /> public LPARAM lParam; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.pNext"]/*' /> [NativeTypeName("struct _GROUP_POLICY_OBJECTW *")] public GROUP_POLICY_OBJECTW* pNext; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.pPrev"]/*' /> [NativeTypeName("struct _GROUP_POLICY_OBJECTW *")] public GROUP_POLICY_OBJECTW* pPrev; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.lpExtensions"]/*' /> [NativeTypeName("LPWSTR")] public ushort* lpExtensions; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.lParam2"]/*' /> public LPARAM lParam2; /// <include file='GROUP_POLICY_OBJECTW.xml' path='doc/member[@name="GROUP_POLICY_OBJECTW.lpLink"]/*' /> [NativeTypeName("LPWSTR")] public ushort* lpLink; }
45.1
145
0.715817
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/UserEnv/GROUP_POLICY_OBJECTW.cs
2,708
C#
namespace MoneyTracker.database { public class TransYear { public int Id {get;set;} public int Year {get;set;} } }
21.166667
34
0.669291
[ "MIT" ]
deandevl/MoneyTrackerApp
MoneyTrackerAppSol/MoneyTrackerApp/database/TransYear.cs
129
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 MileageTracker.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MileageTracker.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
44.59375
181
0.600561
[ "MIT" ]
StillLearnin/mileage-tracker
Mileage Tracker/Properties/Resources.Designer.cs
2,856
C#
using Abp; using Abp.Application.Services.Dto; namespace YiHan.Cms.Authorization.Users.Dto { public class UnlinkUserInput { public int? TenantId { get; set; } public long UserId { get; set; } public UserIdentifier ToUserIdentifier() { return new UserIdentifier(TenantId, UserId); } } }
20.764706
56
0.623229
[ "MIT" ]
Letheloney/YiHanCms
src/YiHan.Cms.Application/Authorization/Users/Dto/UnlinkUserInput.cs
355
C#
using System; namespace TokAboutIt.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
18.909091
70
0.668269
[ "MIT" ]
MichaelJolley/letstokaboutit
src/TokAboutIt/Models/ErrorViewModel.cs
208
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using Microsoft.Dynamics365.UIAutomation.Api; using Microsoft.Dynamics365.UIAutomation.Browser; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Security; namespace Microsoft.Dynamics365.UIAutomation.Sample.Web { [TestClass] public class InvalidBusinessProcessFlow { private readonly SecureString _username = System.Configuration.ConfigurationManager.AppSettings["OnlineUsername"].ToSecureString(); private readonly SecureString _password = System.Configuration.ConfigurationManager.AppSettings["OnlinePassword"].ToSecureString(); private readonly Uri _xrmUri = new Uri(System.Configuration.ConfigurationManager.AppSettings["OnlineCrmUrl"].ToString()); [TestMethod] public void WEBTestInvalidBusinessProcessFlow() { using (var xrmBrowser = new Api.Browser(TestSettings.Options)) { xrmBrowser.LoginPage.Login(_xrmUri, _username, _password); xrmBrowser.GuidedHelp.CloseGuidedHelp(); xrmBrowser.Navigation.OpenSubArea("Sales", "Accounts"); xrmBrowser.Grid.SwitchView("Active Accounts"); xrmBrowser.Grid.OpenRecord(0); try { xrmBrowser.BusinessProcessFlow.SelectStage(0); Assert.Fail("SelectStage is a process which does not exist and hence should have failed"); } catch (Exception e) { Assert.IsTrue(true, String.Format("Exception expected: {0}", e.Message)); } } } } }
38.12766
140
0.634487
[ "MIT" ]
operep/Easy-Repro-Example
Microsoft.Dynamics365.UIAutomation.Sample/Web/NegativeScenarios/BusinessProcessFlow/InvalidBusinessProcessFlow.cs
1,794
C#
namespace Reginald.Core.Products { using System; using System.Threading.Tasks; using System.Windows; using Microsoft.WindowsAPICodePack.Shell; using Reginald.Core.AbstractProducts; using Reginald.Core.Base; using Reginald.Core.Utilities; public class Application : ShellItem { private const string DefaultCaption = "Application"; public Application(ShellObject shellObject) { Name = shellObject.Name; Icon = shellObject.Thumbnail.MediumBitmapSource; Icon.Freeze(); Caption = DefaultCaption; Description = Name; Path = shellObject.Properties.System.Link.TargetParsingPath.Value is string path ? path : Constants.ShellAppsFolder + shellObject.ParsingName; } public override void EnterDown(bool isAltDown, Action action) { action(); if (isAltDown) { Clipboard.SetText(Path); } else { ProcessUtility.OpenFromPath(Path); } } public override Task<bool> EnterDownAsync(bool isAltDown, Action action, object o) { return Task.FromResult(true); } public override (string Description, string Caption) AltDown() { return (null, Path); } public override (string Description, string Caption) AltUp() { return (null, DefaultCaption); } } }
27.821429
92
0.572529
[ "MIT" ]
GBS3/reginald
Reginald.Core/Products/Application.cs
1,560
C#
using System.Collections.Generic; using System.Linq; namespace Items { #region ItemEntityType public class Item { private readonly int _id; private readonly List<Tag> _tags = new List<Tag>(); private Item(int id, string name) { _id = id; Name = name; } public Item(string name) { Name = name; } public Tag AddTag(string label) { var tag = _tags.FirstOrDefault(t => t.Label == label); if (tag == null) { tag = new Tag(label); _tags.Add(tag); } tag.Count++; return tag; } public string Name { get; } public IReadOnlyList<Tag> Tags => _tags; } #endregion }
24.029412
66
0.47858
[ "MIT" ]
medlab/320-online-prototype
TecPoints/Backend/AutoTest/Finally/ItemsWebApi/Item.cs
817
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; namespace Aspnetcore.OrderingApp.Models { public class Client { [Required] public string FirstName { get; set; } [Required] [Display(Name = "Last Name")] public string LastName { get; set; } [Required] public string CompanyName { get; set; } [Required] [EmailAddress] [Remote("VerifyEmail", "Client")] // must work with jquery-validation, when submitting form, check if email exists public string Email { get; set; } [Required] public string Phone { get; set; } [Required] [DataType(DataType.Date)] public DateTime? ContactDate { get; set; } [Required] public string ClientType { get; set; } [Required] public string NearestLocation { get; set; } [Required] [MaxLength(25)] [DataType(DataType.MultilineText)] [UIHint("MultilineTextLarge")] // UI hint, textarea when using EditorFor() public string Notes { get; set; } public List<EmailPromo> EmailPromos { get; set; } public Address BillingAddress { get; set; } public Address MailingAddress { get; set; } } }
34.948718
125
0.595745
[ "MIT" ]
wghglory/Aspnetcore.OrderingApp
Aspnetcore.OrderingApp/Models/Client.cs
1,365
C#
using System; namespace FxSsh.Messages.Connection { public class SessionOpenConfirmationMessage : ChannelOpenConfirmationMessage { } }
16.555556
80
0.765101
[ "MIT" ]
glmnet/FxSsh
FxSsh/Messages/Connection/SessionOpenConfirmationMessage.cs
151
C#
using System; using System.Collections.Generic; using NBitcoin.BouncyCastle.Math; using NBitcoin.Rules; namespace NBitcoin { public class Consensus : IConsensus { /// <inheritdoc /> public long CoinbaseMaturity { get; set; } /// <inheritdoc /> public Money PremineReward { get; } /// <inheritdoc /> public long PremineHeight { get; } /// <inheritdoc /> public Money ProofOfWorkReward { get; } /// <inheritdoc /> public Money ProofOfStakeReward { get; } /// <inheritdoc /> public uint MaxReorgLength { get; } /// <inheritdoc /> public long MaxMoney { get; } public ConsensusOptions Options { get; set; } public BuriedDeploymentsArray BuriedDeployments { get; } public BIP9DeploymentsArray BIP9Deployments { get; } public int SubsidyHalvingInterval { get; } public int MajorityEnforceBlockUpgrade { get; } public int MajorityRejectBlockOutdated { get; } public int MajorityWindow { get; } public uint256 BIP34Hash { get; } public Target PowLimit { get; } public TimeSpan PowTargetTimespan { get; } public TimeSpan PowTargetSpacing { get; } public bool PowAllowMinDifficultyBlocks { get; } public bool PowNoRetargeting { get; } public uint256 HashGenesisBlock { get; } /// <inheritdoc /> public uint256 MinimumChainWork { get; } public int MinerConfirmationWindow { get; set; } public int RuleChangeActivationThreshold { get; set; } /// <inheritdoc /> public int CoinType { get; } public BigInteger ProofOfStakeLimit { get; } public BigInteger ProofOfStakeLimitV2 { get; } /// <inheritdoc /> public int LastPOWBlock { get; set; } /// <inheritdoc /> public bool IsProofOfStake { get; } /// <inheritdoc /> public uint256 DefaultAssumeValid { get; } /// <inheritdoc /> public ConsensusFactory ConsensusFactory { get; } /// <inheritdoc /> public ICollection<IConsensusRule> Rules { get; set; } public Money ProofOfStakeRewardAfterSubsidyLimit { get; } public long SubsidyLimit { get; } /// <inheritdoc /> public Money LastProofOfStakeRewardHeight { get; } public Consensus( ConsensusFactory consensusFactory, ConsensusOptions consensusOptions, int coinType, uint256 hashGenesisBlock, int subsidyHalvingInterval, int majorityEnforceBlockUpgrade, int majorityRejectBlockOutdated, int majorityWindow, BuriedDeploymentsArray buriedDeployments, BIP9DeploymentsArray bip9Deployments, uint256 bip34Hash, int ruleChangeActivationThreshold, int minerConfirmationWindow, uint maxReorgLength, uint256 defaultAssumeValid, long maxMoney, long coinbaseMaturity, long premineHeight, Money premineReward, Money proofOfWorkReward, TimeSpan powTargetTimespan, TimeSpan powTargetSpacing, bool powAllowMinDifficultyBlocks, bool powNoRetargeting, Target powLimit, uint256 minimumChainWork, bool isProofOfStake, int lastPowBlock, BigInteger proofOfStakeLimit, BigInteger proofOfStakeLimitV2, Money proofOfStakeReward ) { this.Rules = new List<IConsensusRule>(); this.CoinbaseMaturity = coinbaseMaturity; this.PremineReward = premineReward; this.PremineHeight = premineHeight; this.ProofOfWorkReward = proofOfWorkReward; this.ProofOfStakeReward = proofOfStakeReward; this.MaxReorgLength = maxReorgLength; this.MaxMoney = maxMoney; this.Options = consensusOptions; this.BuriedDeployments = buriedDeployments; this.BIP9Deployments = bip9Deployments; this.SubsidyHalvingInterval = subsidyHalvingInterval; this.MajorityEnforceBlockUpgrade = majorityEnforceBlockUpgrade; this.MajorityRejectBlockOutdated = majorityRejectBlockOutdated; this.MajorityWindow = majorityWindow; this.BIP34Hash = bip34Hash; this.PowLimit = powLimit; this.PowTargetTimespan = powTargetTimespan; this.PowTargetSpacing = powTargetSpacing; this.PowAllowMinDifficultyBlocks = powAllowMinDifficultyBlocks; this.PowNoRetargeting = powNoRetargeting; this.HashGenesisBlock = hashGenesisBlock; this.MinimumChainWork = minimumChainWork; this.MinerConfirmationWindow = minerConfirmationWindow; this.RuleChangeActivationThreshold = ruleChangeActivationThreshold; this.CoinType = coinType; this.ProofOfStakeLimit = proofOfStakeLimit; this.ProofOfStakeLimitV2 = proofOfStakeLimitV2; this.LastPOWBlock = lastPowBlock; this.IsProofOfStake = isProofOfStake; this.DefaultAssumeValid = defaultAssumeValid; this.ConsensusFactory = consensusFactory; } } }
33.349693
79
0.621965
[ "MIT" ]
CPPDevCrypto/X42-FullNode
src/NBitcoin/Consensus.cs
5,438
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace WebApi { public abstract class ModuleType { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [MaxLength(100)] public string Name { get; set; } [ForeignKey(nameof(Module))] public int ModuleId { get; set; } [InverseProperty(nameof(WebApi.Module.ModuleTypes))] public virtual Module Module { get; set; } } }
24.625
55
0.744501
[ "MIT" ]
lboss75/issue24867
WebApi/Model/ModuleType.cs
593
C#
using Microsoft.AspNetCore.Components; using Money.Commands; using Money.Events; using Money.Queries; using Money.Services; using Neptuo.Commands; using Neptuo.Events; using Neptuo.Events.Handlers; using Neptuo.Logging; using Neptuo.Queries; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Money.Components { public partial class PwaInstall : ComponentBase, IDisposable, IEventHandler<PwaInstallable>, IEventHandler<PwaUpdateable> { [Inject] internal PwaInstallInterop Interop { get; set; } [Inject] internal ILog<PwaInstall> Log { get; set; } [Inject] internal Navigator Navigator { get; set; } [Inject] protected IEventHandlerCollection EventHandlers { get; set; } [Inject] protected ICommandDispatcher Commands { get; set; } [Inject] protected IQueryDispatcher Queries { get; set; } protected ElementReference Button { get; set; } protected bool IsInstallable { get; set; } protected bool IsUpdateable { get; set; } protected override async Task OnInitializedAsync() { Log.Debug("OnInitialized"); await base.OnInitializedAsync(); EventHandlers .Add<PwaInstallable>(this) .Add<PwaUpdateable>(this); var status = await Queries.QueryAsync(new GetPwaStatus()); IsInstallable = status.IsInstallable; IsUpdateable = status.IsUpdateable; } public void MakeInstallable() { Log.Debug("Installable=True"); IsInstallable = true; StateHasChanged(); } public void MakeUpdateable() { Log.Debug("Updateable=True"); IsUpdateable = true; StateHasChanged(); } protected async Task InstallAsync() { await Commands.HandleAsync(new InstallPwa()); } protected async Task UpdateAsync() { await Commands.HandleAsync(new UpdatePwa()); } Task IEventHandler<PwaInstallable>.HandleAsync(PwaInstallable payload) { MakeInstallable(); return Task.CompletedTask; } Task IEventHandler<PwaUpdateable>.HandleAsync(PwaUpdateable payload) { MakeUpdateable(); return Task.CompletedTask; } public void Dispose() { EventHandlers .Remove<PwaInstallable>(this) .Remove<PwaUpdateable>(this); } } }
25.064815
78
0.599557
[ "Apache-2.0" ]
ScriptBox21/Money
src/Money.Blazor.Host/Components/PwaInstall.razor.cs
2,709
C#
/* * Copyright (c) 2013-$Date: 2016-01-25 19:33:46 -0600 (Mon, 25 Jan 2016) $ TIBCO Software Inc. * Licensed under a BSD-style license. Refer to [LICENSE] * For more information, please contact: * TIBCO Software Inc., Palo Alto, California, USA * * $Id: UpgradeException.cs 83756 2016-01-26 01:33:46Z bmahurka $ * */ using System; namespace TIBCO.EFTL { public class UpgradeException: Exception { private int statusCode; public UpgradeException(int statusCode, String message): base(message) { this.statusCode = statusCode; } public int getStatusCode() { return statusCode; } } }
22.866667
95
0.625364
[ "BSD-3-Clause" ]
ehilly-tibco/TIBCO-Messaging
eftl-dotnet-sdk/TIBCO.EFTL.WINRT/websocket/UpgradeException.cs
686
C#
using System; using UnityEngine.Events; namespace JellyFish.Events.UnityEvents { [Serializable] public class StringEvent : UnityEvent<string> { } }
16.5
49
0.715152
[ "MIT" ]
Uncle-Uee/jellyfish-lite
Assets/JellyFish-Lite/Scripts/Runtime/Events/CustomUnityEvents/StringEvent.cs
167
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DelegatesAndEvents { //public delegate int WorkPerformedHandler(object sender, WorkerPerformedEventArgs e); class Worker { public event EventHandler<WorkerPerformedEventArgs> WorkPerformed; public event EventHandler WorkCompleted; public void DoWork(int hours, WorkType workType) { for (int i = 0; i < hours; i++) { System.Threading.Thread.Sleep(1000); OnWorkPerformed(i + 1, workType); } OnWorkCompleted(); } protected virtual void OnWorkPerformed(int hours, WorkType workType) { //if (WorkPerformed != null) //{ // WorkPerformed(hours, workType); //} var del = WorkPerformed as EventHandler<WorkerPerformedEventArgs>; if (del != null) { del(hours, new WorkerPerformedEventArgs(hours, workType)); } } protected virtual void OnWorkCompleted() { //if (WorkPerformed != null) //{ // WorkPerformed(hours, workType); //} var del = WorkCompleted as EventHandler; if (del != null) { del(this, EventArgs.Empty); } } } }
26.563636
90
0.540041
[ "MIT" ]
SamIge7/SideWork
DelegatesAndEvents/DelegatesAndEvents/Worker.cs
1,463
C#
using XMPPEngineer.Im; using System; using System.Collections.Generic; namespace XMPPEngineer.Extensions { /// <summary> /// Implements the 'Chat States Notifications' extension as defined in XEP-0085. /// </summary> internal class ChatStateNotifications : XmppExtension, IInputFilter<Message> { /// <summary> /// An enumerable collection of XMPP namespaces the extension implements. /// </summary> /// <remarks>This is used for compiling the list of supported extensions /// advertised by the 'Service Discovery' extension.</remarks> public override IEnumerable<string> Namespaces { get { return new string[] { "http://jabber.org/protocol/chatstates" }; } } /// <summary> /// The named constant of the Extension enumeration that corresponds to this /// extension. /// </summary> public override Extension Xep { get { return Extension.ChatStateNotifications; } } /// <summary> /// The event that is raised when the chat-state of an XMPP entity has /// changed. /// </summary> public event EventHandler<ChatStateChangedEventArgs> ChatStateChanged; /// <summary> /// Invoked when a message stanza has been received. /// </summary> /// <param name="stanza">The stanza which has been received.</param> /// <returns>true to intercept the stanza or false to pass the stanza /// on to the next handler.</returns> public bool Input(Message stanza) { // Look for chat-state elements. foreach (ChatState state in Enum.GetValues(typeof(ChatState))) { string name = state.ToString().ToLowerInvariant(); if (stanza.Data[name] != null && stanza.Data[name].NamespaceURI == "http://jabber.org/protocol/chatstates") { ChatStateChanged.Raise(this, new ChatStateChangedEventArgs(stanza.From, state)); } } // Pass the message on to the next handler. return false; } /// <summary> /// Sets the chat-state for the conversation with the XMPP user with the /// specified JID. /// </summary> /// <param name="jid">The JID of the XMPP user to set the chat-state /// for.</param> /// <param name="state">The new chat-state.</param> /// <exception cref="ArgumentNullException">The jid parameter is /// null.</exception> public void SetChatState(Jid jid, ChatState state) { jid.ThrowIfNull("jid"); Message m = new Message(jid); m.Type = MessageType.Chat; m.Data.Child(Xml.Element(state.ToString().ToLowerInvariant(), "http://jabber.org/protocol/chatstates")); im.SendMessage(m); } /// <summary> /// Initializes a new instance of the ChatStateNotifications class. /// </summary> /// <param name="im">A reference to the XmppIm instance on whose behalf this /// instance is created.</param> public ChatStateNotifications(XmppIm im) : base(im) { } } }
36.136842
84
0.55986
[ "MIT" ]
ParamountVentures/Sharp.Xmpp
Extensions/XEP-0085/ChatStateNotifications.cs
3,435
C#