content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Collections; using System.Collections.Generic; using Quester.QuestEditor; using UnityEngine; [CreateAssetMenu(fileName = "Asset Map", menuName = "Asset Map")] public class QuesterAssetMap : ScriptableObject { [SerializeField] private List<QuestGraph> _quests; private static Dictionary<int, QuestGraph> _questMap = new Dictionary<int, QuestGraph>(); private static bool _hasInitialized = false; public void Initialize() { foreach (var quest in _quests) { Register(quest); } } private void Register(QuestGraph graph) { _questMap[graph.PrimaryKey] = graph; } //public QuestGraph Retrieve(int primaryKey) //{ // if (_questMap.ContainsKey(primaryKey)) // { // return _questMap[primaryKey]; // } // Debug.LogError("Quest Asset Map does not contain primary key " + primaryKey); // return null; //} public bool TryRetrieve(int primaryKey, out QuestGraph graph) { graph = null; if (_questMap.ContainsKey(primaryKey)) { graph = _questMap[primaryKey]; return true; } return false; } }
23.326923
93
0.619126
[ "MIT" ]
nmacadam/Quester
Assets/Scripts/Scriptable Object Definitions/QuesterAssetMap.cs
1,215
C#
namespace VerifyTests; public abstract class WriteOnlyJsonConverter<T> : WriteOnlyJsonConverter { public sealed override void Write(VerifyJsonWriter writer, object value) => Write(writer, (T) value); public abstract void Write(VerifyJsonWriter writer, T value); static Type? nullableType; static WriteOnlyJsonConverter() { if (typeof(T).IsValueType) { nullableType = typeof(Nullable<>).MakeGenericType(typeof(T)); } } public sealed override bool CanConvert(Type type) { if (typeof(T).IsAssignableFrom(type)) { return true; } return nullableType != null && nullableType == type; } }
23.580645
79
0.616963
[ "MIT" ]
SimonCropp/Verify
src/Verify/Serialization/WriteOnlyJsonConverterT.cs
733
C#
namespace Domain.UseCases; [ServiceLifetime(ServiceLifetime.Singleton)] public class PublishQuestionAnsweredEventUseCaseHandler : ICommandHandler<PublishQuestionAnsweredEventUseCase> { private readonly IMediator mediator; public PublishQuestionAnsweredEventUseCaseHandler(IMediator mediator) => this.mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); [HasPermission("PUBLISH_QUESTION_ANSWERED_EVENT")] [Transactional] [MakeIdempotent] public async Task Handle(PublishQuestionAnsweredEventUseCase command, CancellationToken cancellationToken) { var question = await mediator.Ask(new GetQuestionAggregate(command.QuestionId), cancellationToken); var @event = question.IsAnswered(); await mediator.Send(new SaveQuestionAggregate(question), cancellationToken); await mediator.Send(new PublishEvent<QuestionAnswerdIntegrationEvent>(@event)); } }
40.73913
155
0.786553
[ "CC0-1.0" ]
arjangeertsema/hexagonal-architecture
Domain/Domain.UseCases/PublishQuestionAnsweredEventUseCaseHandler.cs
937
C#
namespace RedditBet.Areas.HelpPage.ModelDescriptions { public class EnumValueDescription { public string Documentation { get; set; } public string Name { get; set; } public string Value { get; set; } } }
22.818182
53
0.61753
[ "MIT" ]
robotnoises/rCfb_BetBot
RedditBet.API/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs
251
C#
using System.Collections.Generic; using Microsoft.Xna.Framework; namespace Pathoschild.Stardew.Common.Integrations.Cobalt { /// <summary>The API provided by the Cobalt mod.</summary> public interface ICobaltApi { /********* ** Public methods *********/ /// <summary>Get the cobalt sprinkler's object ID.</summary> int GetSprinklerId(); /// <summary>Get the cobalt sprinkler coverage.</summary> /// <param name="origin">The tile position containing the sprinkler.</param> IEnumerable<Vector2> GetSprinklerCoverage(Vector2 origin); } }
30.8
84
0.646104
[ "MIT" ]
Alexhia/StardewMods
Common/Integrations/Cobalt/ICobaltApi.cs
616
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace AlibabaCloud.SDK.ROS.CDK.Core { [JsiiByValue(fqn: "@alicloud/ros-cdk-core.RemovalPolicyOptions")] public class RemovalPolicyOptions : AlibabaCloud.SDK.ROS.CDK.Core.IRemovalPolicyOptions { [JsiiOptional] [JsiiProperty(name: "applyToUpdateReplacePolicy", typeJson: "{\"primitive\":\"boolean\"}", isOptional: true)] public bool? ApplyToUpdateReplacePolicy { get; set; } [JsiiOptional] [JsiiProperty(name: "defaultPolicy", typeJson: "{\"fqn\":\"@alicloud/ros-cdk-core.RemovalPolicy\"}", isOptional: true)] public AlibabaCloud.SDK.ROS.CDK.Core.RemovalPolicy? DefaultPolicy { get; set; } } }
30.444444
127
0.636253
[ "Apache-2.0" ]
piotr-kalanski/Resource-Orchestration-Service-Cloud-Development-Kit
multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Core/AlibabaCloud/SDK/ROS/CDK/Core/RemovalPolicyOptions.cs
822
C#
using System; using System.Linq; using System.Net; using System.Net.Http; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Mozu.Api.Resources.Platform; using Mozu.Api.Test.Factories.Platform; using Mozu.Api.Test.Factories.Platform.Entitylists; using Mozu.Api.Test.Helpers; using TestContext = Microsoft.VisualStudio.TestTools.UnitTesting.TestContext; namespace Mozu.Api.Test.MsTestCases { using System.Threading; /// <summary> /// Summary description for TenantDataTest /// </summary> [TestClass] public class TenantDataTest : MozuApiTestBase { #region NonTestCaseCode private static List<string> productCode1 = new List<string>(); private static List<int> productTypeId1 = new List<int>(); private static List<string> attributeFQN1 = new List<string>(); public TenantDataTest() { } #region Initializers /// <summary> /// This will run once before each test. /// </summary> [TestInitialize] public void TestMethodInit() { tenantId = Convert.ToInt32(Mozu.Api.Test.Helpers.Environment.GetConfigValueByEnvironment("TenantId")); ApiMsgHandler = ServiceClientMessageFactory.GetTestClientMessage(); TestBaseTenant = TenantFactory.GetTenant(handler: ApiMsgHandler,tenantId: tenantId); masterCatalogId = TestBaseTenant.MasterCatalogs.First().Id; catalogId = TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id; HttpRequestMessage msg = new HttpRequestMessage(); msg.Headers.Add(Headers.X_VOL_TENANT, TestBaseTenant.Id.ToString()); msg.Headers.Add(Headers.X_VOL_TENANT_DOMAIN, TestBaseTenant.Domain); msg.Headers.Add(Headers.X_VOL_SITE, TestBaseTenant.Sites[0].Id.ToString()); ApiMsgHandler = ServiceClientMessageFactory.GetTestClientMessage(msg.Headers); productCode1.Clear(); productTypeId1.Clear(); attributeFQN1.Clear(); } /// <summary> /// Runs once before any test is run. /// </summary> /// <param name="testContext"></param> [ClassInitialize] public static void InitializeBeforeRun(TestContext testContext) { //Call the base class's static initializer. MozuApiTestBase.TestClassInitialize(testContext); } #endregion #region CleanupMethods /// <summary> /// This will run once after each test. /// </summary> [TestCleanup] public void TestMethodCleanup() { CleanUpData.CleanUpProducts(ApiMsgHandler, productCode1); CleanUpData.CleanUpProductTypes(ApiMsgHandler, productTypeId1); CleanUpData.CleanUpAttributes(ApiMsgHandler, attributeFQN1); //Calls the base class's Test Cleanup base.TestCleanup(); } /// <summary> /// Runs once after all of the tests have run. /// </summary> [ClassCleanup] public static void TestsCleanup() { //Calls the Base class's static cleanup. MozuApiTestBase.TestClassCleanup(); } #endregion #endregion [TestMethod] public void GetDataTest() { //var prods = TenantDataFactory.GetDBValue(handler: ApiMsgHandler,dbEntryQuery: "test", expectedCode: 404, successCode:404 ); var data = SiteDataFactory.GetDBValue(handler: ApiMsgHandler, dbEntryQuery: "test", expectedCode: HttpStatusCode.NotFound, successCode: HttpStatusCode.NotFound); } [TestMethod] public void GetTenantAsyncTest() { var tenantResource = new TenantResource(); CancellationTokenSource cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(3)); var tenant = tenantResource.GetTenantAsync(8088, ct: cts.Token).Result; } [TestMethod] public void GetEntityList() { ApiMsgHandler.ApiContext.Locale = "en-US"; var entityList = EntityFactory.GetEntity(handler: ApiMsgHandler, entityListFullName: "bvavgproductreview@a0842dd", id: "ED-Herald-AmberTortoise", expectedCode: HttpStatusCode.OK, successCode: HttpStatusCode.OK); entityList = EntityFactory.GetEntity(handler: ApiMsgHandler, entityListFullName: "bvavgproductreview@a0842dd", id: "ED-Herald-AmberTortoise", expectedCode: HttpStatusCode.OK, successCode: HttpStatusCode.OK); entityList = EntityFactory.GetEntity(handler: ApiMsgHandler, entityListFullName: "bvavgproductreview@a0842dd", id: "GPG-Bul'+b-All", expectedCode: HttpStatusCode.OK, successCode: HttpStatusCode.OK); ApiMsgHandler.ApiContext.TenantId = 0; var countries = ReferenceDataFactory.GetCountries(handler: ApiMsgHandler); countries = ReferenceDataFactory.GetCountries(handler: ApiMsgHandler); } } }
36.239437
190
0.648853
[ "MIT" ]
GaryWayneSmith/mozu-dotnet
Mozu.Api.Test/MsTestCases/TenantDataTest.cs
5,148
C#
using System; using System.IO; using Microsoft.WindowsAzure.Storage; using Rebus.Exceptions; namespace Rebus.AzureStorage.Tests { public static class AzureConfig { public static CloudStorageAccount StorageAccount => CloudStorageAccount.Parse(ConnectionString); public static string ConnectionString => ConnectionStringFromFileOrNull(Path.Combine(GetBaseDirectory(), "azure_storage_connection_string.txt")) ?? ConnectionStringFromEnvironmentVariable("rebus2_storage_connection_string") ?? Throw("Could not find Azure Storage connection string!"); static string GetBaseDirectory() { #if NETSTANDARD1_6 return AppContext.BaseDirectory; #else return AppDomain.CurrentDomain.BaseDirectory; #endif } static string ConnectionStringFromFileOrNull(string filePath) { if (!File.Exists(filePath)) { Console.WriteLine("Could not find file {0}", filePath); return null; } Console.WriteLine("Using Azure Storage connection string from file {0}", filePath); return File.ReadAllText(filePath); } static string ConnectionStringFromEnvironmentVariable(string environmentVariableName) { var value = Environment.GetEnvironmentVariable(environmentVariableName); if (value == null) { Console.WriteLine("Could not find env variable {0}", environmentVariableName); return null; } Console.WriteLine("Using Azure Storage connection string from env variable {0}", environmentVariableName); return value; } static string Throw(string message) { throw new RebusConfigurationException(message); } } }
33.666667
152
0.628452
[ "MIT" ]
micdah/Rebus.AzureStorage
Rebus.AzureStorage.Tests/TestConfig.cs
1,921
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/MsHTML.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="DispDOMUIEvent" /> struct.</summary> public static unsafe partial class DispDOMUIEventTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="DispDOMUIEvent" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(DispDOMUIEvent).GUID, Is.EqualTo(IID_DispDOMUIEvent)); } /// <summary>Validates that the <see cref="DispDOMUIEvent" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<DispDOMUIEvent>(), Is.EqualTo(sizeof(DispDOMUIEvent))); } /// <summary>Validates that the <see cref="DispDOMUIEvent" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(DispDOMUIEvent).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="DispDOMUIEvent" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(DispDOMUIEvent), Is.EqualTo(8)); } else { Assert.That(sizeof(DispDOMUIEvent), Is.EqualTo(4)); } } }
34.647059
145
0.683079
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/MsHTML/DispDOMUIEventTests.cs
1,769
C#
#region license // Copyright (c) 2007-2010 Mauricio Scheffer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using SolrNet.Impl.FieldParsers; using SolrNet.Utils; namespace SolrNet.Impl.ResponseParsers { /// <summary> /// Parses facets from query response /// </summary> /// <typeparam name="T">Document type</typeparam> public class FacetsResponseParser<T> : ISolrAbstractResponseParser<T> { public void Parse(XDocument xml, AbstractSolrQueryResults<T> results) { var mainFacetNode = xml.Element("response") .Elements("lst") .FirstOrDefault(X.AttrEq("name", "facet_counts")); if (mainFacetNode != null) { results.FacetQueries = ParseFacetQueries(mainFacetNode); results.FacetFields = ParseFacetFields(mainFacetNode); results.FacetDates = ParseFacetDates(mainFacetNode); results.FacetPivots = ParseFacetPivots(mainFacetNode); results.FacetRanges = ParseFacetRanges(mainFacetNode); results.FacetIntervals = ParseFacetIntervals(mainFacetNode); } } /// <summary> /// Parses facet queries results /// </summary> /// <param name="node"></param> /// <returns></returns> public IDictionary<string, int> ParseFacetQueries(XElement node) { var d = new Dictionary<string, int>(); var facetQueries = node.Elements("lst") .Where(X.AttrEq("name", "facet_queries")) .Elements(); foreach (var fieldNode in facetQueries) { var key = fieldNode.Attribute("name").Value; var value = Convert.ToInt32(fieldNode.Value); d[key] = value; } return d; } /// <summary> /// Parses facet fields results /// </summary> /// <param name="node"></param> /// <returns></returns> public IDictionary<string, ICollection<KeyValuePair<string, int>>> ParseFacetFields(XElement node) { var d = new Dictionary<string, ICollection<KeyValuePair<string, int>>>(); var facetFields = node.Elements("lst") .Where(X.AttrEq("name", "facet_fields")) .SelectMany(x => x.Elements()); foreach (var fieldNode in facetFields) { var field = fieldNode.Attribute("name").Value; var c = new List<KeyValuePair<string, int>>(); foreach (var facetNode in fieldNode.Elements()) { var nameAttr = facetNode.Attribute("name"); var key = nameAttr == null ? "" : nameAttr.Value; var value = Convert.ToInt32(facetNode.Value); c.Add(new KeyValuePair<string, int>(key, value)); } d[field] = c; } return d; } /// <summary> /// Parses facet dates results /// </summary> /// <param name="node"></param> /// <returns></returns> [Obsolete("As of Solr 3.1 has been deprecated, as of Solr 6.6 unsupported.")] public IDictionary<string, DateFacetingResult> ParseFacetDates(XElement node) { var d = new Dictionary<string, DateFacetingResult>(); var facetDateNode = node.Elements("lst") .Where(X.AttrEq("name", "facet_dates")); if (facetDateNode != null) { foreach (var fieldNode in facetDateNode.Elements()) { var name = fieldNode.Attribute("name").Value; d[name] = ParseDateFacetingNode(fieldNode); } } return d; } /// <summary> /// Parses facet range results /// </summary> /// <param name="node"></param> /// <returns></returns> public IDictionary<string, RangeFacetingResult> ParseFacetRanges(XElement node) { var d = new Dictionary<string, RangeFacetingResult>(); var facetRangeNode = node.Elements("lst") .Where(X.AttrEq("name", "facet_ranges")); if (facetRangeNode != null) { foreach (var fieldNode in facetRangeNode.Elements()) { var name = fieldNode.Attribute("name").Value; d[name] = ParseRangeFacetingNode(fieldNode); } } return d; } [Obsolete("As of Solr 3.1 has been deprecated, as of Solr 6.6 unsupported.")] public DateFacetingResult ParseDateFacetingNode(XElement node) { var r = new DateFacetingResult(); var intParser = new IntFieldParser(); foreach (var dateFacetingNode in node.Elements()) { var name = dateFacetingNode.Attribute("name").Value; switch (name) { case "gap": r.Gap = dateFacetingNode.Value; break; case "end": r.End = DateTimeFieldParser.ParseDate(dateFacetingNode.Value); break; default: // Temp fix to support Solr 3.1, which has added a new element <date name="start">...</date> // not seen in Solr 1.4 to the facet date response – just ignore this element. if (dateFacetingNode.Name != "int") break; var count = (int) intParser.Parse(dateFacetingNode, typeof (int)); if (name == FacetDateOther.After.ToString()) r.OtherResults[FacetDateOther.After] = count; else if (name == FacetDateOther.Before.ToString()) r.OtherResults[FacetDateOther.Before] = count; else if (name == FacetDateOther.Between.ToString()) r.OtherResults[FacetDateOther.Between] = count; else { var d = DateTimeFieldParser.ParseDate(name); r.DateResults.Add(KV.Create(d, count)); } break; } } return r; } public RangeFacetingResult ParseRangeFacetingNode(XElement node) { var r = new RangeFacetingResult(); var intParser = new IntFieldParser(); foreach (var rangeFacetingNode in node.Elements()) { var name = rangeFacetingNode.Attribute("name").Value; switch (name) { case "gap": r.Gap = rangeFacetingNode.Value; break; case "start": r.Start = rangeFacetingNode.Value; break; case "end": r.End = rangeFacetingNode.Value; break; case "counts": foreach (var item in rangeFacetingNode.Elements()) { r.RangeResults.Add(KV.Create(item.Attribute("name").Value, (int)intParser.Parse(item, typeof(int)))); } break; default: //collect FacetRangeOther items if (rangeFacetingNode.Name != "int") break; var count = (int)intParser.Parse(rangeFacetingNode, typeof(int)); if (name == FacetDateOther.After.ToString()) r.OtherResults[FacetRangeOther.After] = count; else if (name == FacetDateOther.Before.ToString()) r.OtherResults[FacetRangeOther.Before] = count; else if (name == FacetDateOther.Between.ToString()) r.OtherResults[FacetRangeOther.Between] = count; break; } } return r; } /// <summary> /// Parses facet interval results /// </summary> /// <param name="node"></param> /// <returns></returns> public IDictionary<string, ICollection<KeyValuePair<string,int>>> ParseFacetIntervals(XElement node) { var d = new Dictionary<string, ICollection<KeyValuePair<string,int>>>(); var facetIntervals = node.Elements("lst") .Where(X.AttrEq("name", "facet_intervals")) .SelectMany(x=>x.Elements()); foreach (var fieldNode in facetIntervals) { var field = fieldNode.Attribute("name").Value; var c = new List<KeyValuePair<string, int>>(); foreach (var facetNode in fieldNode.Elements()) { var nameAttr = facetNode.Attribute("name"); var key = nameAttr?.Value ?? ""; var value = Convert.ToInt32(facetNode.Value); c.Add(new KeyValuePair<string, int>(key, value)); } d[field] = c; } return d; } /// <summary> /// Parses facet pivot results /// </summary> /// <param name="node"></param> /// <returns></returns> public IDictionary<string, IList<Pivot>> ParseFacetPivots(XElement node) { var d = new Dictionary<string, IList<Pivot>>(); var facetPivotNode = node.Elements("lst") .Where(X.AttrEq("name", "facet_pivot")); foreach (var fieldNode in facetPivotNode.Elements()) { var name = fieldNode.Attribute("name").Value; d[name] = fieldNode.Elements("lst").Select(ParsePivotNode).ToArray(); } return d; } public Pivot ParsePivotNode(XElement node) { Pivot pivot = new Pivot(); pivot.Field = node.Elements("str").First(X.AttrEq("name", "field")).Value; pivot.Value = node.Elements().First(X.AttrEq("name", "value")).Value; pivot.Count = int.Parse(node.Elements("int").First(X.AttrEq("name", "count")).Value); var childPivotNodes = node.Elements("arr").Where(X.AttrEq("name", "pivot")).ToList(); if (childPivotNodes.Count > 0) { pivot.HasChildPivots = true; pivot.ChildPivots = new List<Pivot>(); foreach (var childNode in childPivotNodes.Elements()) { pivot.ChildPivots.Add(ParsePivotNode(childNode)); } } return pivot; } } }
41.255396
130
0.522365
[ "Apache-2.0" ]
630383257/SolrNet
SolrNet/Impl/ResponseParsers/FacetsResponseParser.cs
11,473
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Orleans; using Orleans.Concurrency; using Orleans.Core; using Orleans.Runtime; namespace Squidex.Infrastructure.EventSourcing.Grains { public class EventConsumerManagerGrain : Grain, IEventConsumerManagerGrain, IRemindable { private readonly IEnumerable<IEventConsumer> eventConsumers; public EventConsumerManagerGrain(IEnumerable<IEventConsumer> eventConsumers) : this(eventConsumers, null, null) { } protected EventConsumerManagerGrain( IEnumerable<IEventConsumer> eventConsumers, IGrainIdentity identity, IGrainRuntime runtime) : base(identity, runtime) { Guard.NotNull(eventConsumers, nameof(eventConsumers)); this.eventConsumers = eventConsumers; } public override Task OnActivateAsync() { DelayDeactivation(TimeSpan.FromDays(1)); RegisterOrUpdateReminder("Default", TimeSpan.Zero, TimeSpan.FromMinutes(10)); RegisterTimer(x => ActivateAsync(null), null, TimeSpan.Zero, TimeSpan.FromSeconds(10)); return Task.FromResult(true); } public Task ActivateAsync(string streamName) { var tasks = eventConsumers .Where(c => streamName == null || Regex.IsMatch(streamName, c.EventsFilter)) .Select(c => GrainFactory.GetGrain<IEventConsumerGrain>(c.Name)) .Select(c => c.ActivateAsync()); return Task.WhenAll(tasks); } public async Task<Immutable<List<EventConsumerInfo>>> GetConsumersAsync() { var tasks = eventConsumers .Select(c => GrainFactory.GetGrain<IEventConsumerGrain>(c.Name)) .Select(c => c.GetStateAsync()); var consumerInfos = await Task.WhenAll(tasks); return new Immutable<List<EventConsumerInfo>>(consumerInfos.Select(r => r.Value).ToList()); } public Task StartAllAsync() { return Task.WhenAll( eventConsumers .Select(c => StartAsync(c.Name))); } public Task StopAllAsync() { return Task.WhenAll( eventConsumers .Select(c => StopAsync(c.Name))); } public Task<Immutable<EventConsumerInfo>> ResetAsync(string consumerName) { var eventConsumer = GrainFactory.GetGrain<IEventConsumerGrain>(consumerName); return eventConsumer.ResetAsync(); } public Task<Immutable<EventConsumerInfo>> StartAsync(string consumerName) { var eventConsumer = GrainFactory.GetGrain<IEventConsumerGrain>(consumerName); return eventConsumer.StartAsync(); } public Task<Immutable<EventConsumerInfo>> StopAsync(string consumerName) { var eventConsumer = GrainFactory.GetGrain<IEventConsumerGrain>(consumerName); return eventConsumer.StopAsync(); } public Task ActivateAsync() { return ActivateAsync(null); } public Task ReceiveReminder(string reminderName, TickStatus status) { return ActivateAsync(null); } } }
32.344538
103
0.577553
[ "MIT" ]
Avd6977/squidex
src/Squidex.Infrastructure/EventSourcing/Grains/EventConsumerManagerGrain.cs
3,852
C#
using System; class DeclareVariables { static void Main() { byte apples = 97; sbyte pearhes = -115; short pears = -10000; ushort blueberries = 52130; uint strowberries = 4825932; Console.WriteLine("In my life I eat " + apples + " apples " + pearhes + " pearches " + pears + " pears " + blueberries + " blueberries " + " and " + strowberries + " strowberries "); } }
24.666667
195
0.556306
[ "MIT" ]
Roskataa/Telerik-Homework-C-Part-1
Primitive Data Types and Variables/01.Declare Variables/DeclareVariables.cs
446
C#
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Axiverse.Services.Proto; using Grpc.Core; namespace Axiverse.Services.ChatService { public class ChatServiceImpl : Proto.ChatService.ChatServiceBase { ConcurrentDictionary<string, Client> clients = new ConcurrentDictionary<string, Client>(); public override Task<SendMessageResponse> SendMessage(SendMessageRequest request, ServerCallContext context) { var message = new Message(); message.Text = request.Message; foreach (var client in clients.Values) { client.Queue.Enqueue(message); client.Trigger.Set(); } return Task.FromResult(new SendMessageResponse()); } public override Task<JoinChannelResponse> JoinChannel(JoinChannelRequest request, ServerCallContext context) { return base.JoinChannel(request, context); } public override Task<LeaveChannelResponse> LeaveChannel(LeaveChannelRequest request, ServerCallContext context) { return base.LeaveChannel(request, context); } public override async Task Listen(ListenRequest request, IServerStreamWriter<ListenResponse> responseStream, ServerCallContext context) { var client = new Client(); client.Session = request.SessionToken; clients.TryAdd(client.Session, client); var connected = true; do { try { await client.Trigger.WaitAsync(); while (client.Queue.TryDequeue(out var message)) { var messageProto = new ChatMessage { Message = message.Text, Channel = " ", }; await responseStream.WriteAsync(new ListenResponse { Message = messageProto }); } client.Trigger.Reset(); } catch (Exception e) { connected = false; } } while (connected); clients.TryRemove(client.Session, out client); } } }
32.240506
143
0.543384
[ "MIT" ]
AxiverseCode/Axiverse
Source/Services/Axiverse.Services.ChatService/ChatServiceImpl.cs
2,549
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace P0_AndresOrozco.Migrations { public partial class m0 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "customers", columns: table => new { UserName = table.Column<string>(nullable: false), FName = table.Column<string>(nullable: true), LName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_customers", x => x.UserName); }); migrationBuilder.CreateTable( name: "inventory", columns: table => new { InventoryId = table.Column<Guid>(nullable: false), StoreId = table.Column<int>(nullable: false), ProductName = table.Column<string>(nullable: true), Quantity = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_inventory", x => x.InventoryId); }); migrationBuilder.CreateTable( name: "orderHistory", columns: table => new { OrderId = table.Column<Guid>(nullable: false), CommonId = table.Column<Guid>(nullable: false), StoreId = table.Column<int>(nullable: false), UserName = table.Column<string>(nullable: true), ProductName = table.Column<string>(nullable: true), ProductQuantity = table.Column<int>(nullable: false), ProductPrice = table.Column<double>(nullable: false), Timestamp = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_orderHistory", x => x.OrderId); }); migrationBuilder.CreateTable( name: "products", columns: table => new { ProductName = table.Column<string>(nullable: false), ProductPrice = table.Column<double>(nullable: false), ProductDescription = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_products", x => x.ProductName); }); migrationBuilder.CreateTable( name: "stores", columns: table => new { StoreId = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), StoreName = table.Column<string>(nullable: true), Address = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_stores", x => x.StoreId); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "customers"); migrationBuilder.DropTable( name: "inventory"); migrationBuilder.DropTable( name: "orderHistory"); migrationBuilder.DropTable( name: "products"); migrationBuilder.DropTable( name: "stores"); } } }
36.823529
77
0.476038
[ "MIT" ]
12142020-dotnet-uta/AndresOrozcoRepo1
P0_Store_Application/P0_AndresOrozco/Migrations/20201229212113_m0.cs
3,758
C#
using JetBrains.Annotations; using JetBrains.Application.Threading; using JetBrains.DocumentManagers; using JetBrains.DocumentManagers.Transactions; using JetBrains.DocumentModel; using JetBrains.DocumentModel.Impl; using JetBrains.Lifetimes; using JetBrains.ProjectModel; using JetBrains.RdBackend.Common.Features.Documents; using JetBrains.ReSharper.Plugins.Unity.ProjectModel; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Unity.Rider { /// <summary> /// Removes auto sync through disk for shared files, to avoid unity refresh /// </summary> [SolutionComponent] public class RiderUnitySharedFilesSavingSuppressor : IRiderDocumentSavingSuppressor { [NotNull] private readonly ISolution mySolution; [NotNull] private readonly UnitySolutionTracker myUnitySolutionTracker; [NotNull] private readonly DocumentToProjectFileMappingStorage myDocumentToProjectFileMappingStorage; [NotNull] private readonly ILogger myLogger; public RiderUnitySharedFilesSavingSuppressor( [NotNull] ISolution solution, [NotNull] UnitySolutionTracker unitySolutionTracker, [NotNull] DocumentToProjectFileMappingStorage documentToProjectFileMappingStorage, [NotNull] ILogger logger) { mySolution = solution; myUnitySolutionTracker = unitySolutionTracker; myDocumentToProjectFileMappingStorage = documentToProjectFileMappingStorage; myLogger = logger; } public bool ShouldSuppress(IDocument document, bool forceSaveOpenDocuments) { if (!forceSaveOpenDocuments) return false; var projectFile = myDocumentToProjectFileMappingStorage.TryGetProjectFile(document); var isUnitySharedProjectFile = projectFile != null && myUnitySolutionTracker.IsUnityGeneratedProject.Value && projectFile.IsShared(); if (isUnitySharedProjectFile) { if (!IsFileAssociatedWithOpenedEditor(document)) return true; mySolution.Locks.ExecuteOrQueueWithWriteLockWhenAvailableEx(Lifetime.Eternal, "Sync Unity shared files", () => { using (mySolution.CreateTransactionCookie(DefaultAction.Commit, "Sync Unity shared files")) { var text = projectFile.GetDocument().GetText(); foreach (var sharedProjectFile in projectFile.GetSharedProjectFiles()) { if (sharedProjectFile == projectFile) continue; sharedProjectFile.GetDocument().SetText(text); } } }); myLogger.Verbose("File is shared and contained in Unity project. Skip saving."); return true; } return false; } private bool IsFileAssociatedWithOpenedEditor(IDocument document) { var modifiedProjectFile = myDocumentToProjectFileMappingStorage.TryGetProjectFile(document); if (modifiedProjectFile == null) return false; var documentModel = modifiedProjectFile.GetData(DocumentHostBase.DocumentModelKey); return documentModel != null && !documentModel.TextControls.IsEmpty(); } } }
42.790123
126
0.651183
[ "Apache-2.0" ]
JetBrains/resharper-unity
resharper/resharper-unity/src/Rider/RiderUnitySharedFilesSavingSuppressor.cs
3,466
C#
using System; using OnlineChessCore.Game.Board; using OnlineChessCore.Game.Events.Args; using OnlineChessCore.Game.Pieces; namespace OnlineChessCore.Game.Events { public class GameEvents { public event EventHandler<PieceTakenOverArgs> PieceTakenOver; protected virtual void OnPieceTakenOver(Piece takenPiece, Coords coords) { PieceTakenOver?.Invoke(this, new PieceTakenOverArgs() { TakenPiece = takenPiece, TakenCoords = coords }); } public event EventHandler<PieceMovedArgs> PieceMoved; protected virtual void OnPieceMoved(Piece piece, Coords fromCoords, Coords newCoords) { PieceMoved?.Invoke(this, new PieceMovedArgs() { MovedPiece = piece, FromCoords = fromCoords, NewCoords = newCoords }); } public event EventHandler PawnUpgrading; protected virtual void OnPawnUpgrading() { PawnUpgrading?.Invoke(this, EventArgs.Empty); } public event EventHandler<PawnUpgradedArgs> PawnUpgraded; protected virtual void OnPawnUpgraded(Coords coords, Piece newPiece) { PawnUpgraded?.Invoke(this, new PawnUpgradedArgs() { Coords = coords, NewPiece = newPiece }); } public event EventHandler<LoadedArgs> Loaded; protected virtual void OnLoaded(Tile[] board) { Loaded?.Invoke(this, new LoadedArgs() { Board = board }); } } }
32.822222
130
0.657414
[ "MIT" ]
KYPremco/ChessCore
Game/Events/GameEvents.cs
1,479
C#
namespace HwProj.CourseWorkService.API.Models.DTO { public class OverviewApplicationDTO { public long Id { get; set; } public long CourseWorkId { get; set; } public string CourseWorkTitle { get; set; } public string StudentName { get; set; } public int StudentGroup { get; set; } public string Date { get; set; } } }
23.8125
51
0.614173
[ "MIT" ]
InteIIigeNET/HwProj-2.0.1
HwProj.CourseWorkService/HwProj.CourseWorkService.API/Models/DTO/OverviewApplicationDTO.cs
383
C#
using System; namespace Wox.Infrastructure { [Obsolete("This class is obsolete and should not be used. Please use the static function StringMatcher.FuzzySearch")] public class FuzzyMatcher { private string query; private MatchOption opt; private FuzzyMatcher(string query, MatchOption opt) { this.query = query.Trim(); this.opt = opt; } public static FuzzyMatcher Create(string query) { return new FuzzyMatcher(query, new MatchOption()); } public static FuzzyMatcher Create(string query, MatchOption opt) { return new FuzzyMatcher(query, opt); } public MatchResult Evaluate(string str) { return StringMatcher.Instance.FuzzyMatch(query, str, opt); } } }
25.666667
121
0.605667
[ "MIT" ]
01DKAC/PowerToys
src/modules/launcher/Wox.Infrastructure/FuzzyMatcher.cs
849
C#
using System; namespace IFY.Phorm.Connectivity { /// <summary> /// Handles provision of existing or new <see cref="IPhormDbConnection"/> instances. /// </summary> public interface IPhormDbConnectionProvider { /// <summary> /// Allow subscribers to perform actions when a connection is made. /// </summary> event EventHandler<IPhormDbConnection>? Connected; /// <summary> /// Get an existing or new connection for the connection context. /// </summary> /// <param name="connectionName">The name of the connection to scope this connection for.</param> /// <returns>A datasource connection for the given context.</returns> IPhormDbConnection GetConnection(string? connectionName = null); } }
34.608696
105
0.650754
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
IFYates/Phorm
src/IFY.Phorm/Connectivity/IPhormDbConnectionProvider.cs
798
C#
using ExitGames.Client.Photon; using ExitGames.Client.Photon.Lite; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using UnityEngine; internal class NetworkingPeer : LoadbalancingPeer, IPhotonPeerListener { private HashSet<int> allowedReceivingGroups; private HashSet<int> blockSendingGroups; protected internal short currentLevelPrefix; protected internal const string CurrentSceneProperty = "curScn"; private bool didAuthenticate; private IPhotonPeerListener externalListener; private string[] friendListRequested; private int friendListTimestamp; public bool hasSwitchedMC; public bool insideLobby; public Dictionary<int, GameObject> instantiatedObjects; private bool isFetchingFriends; public bool IsInitialConnect; protected internal bool loadingLevelAndPausedNetwork; public Dictionary<int, PhotonPlayer> mActors; protected internal string mAppId; protected internal string mAppVersion; public Dictionary<string, RoomInfo> mGameList; public RoomInfo[] mGameListCopy; private JoinType mLastJoinType; public PhotonPlayer mMasterClient; private Dictionary<System.Type, List<MethodInfo>> monoRPCMethodsCache; public PhotonPlayer[] mOtherPlayerListCopy; public PhotonPlayer[] mPlayerListCopy; private bool mPlayernameHasToBeUpdated; public string NameServerAddress; protected internal Dictionary<int, PhotonView> photonViewList; private string playername; public static Dictionary<string, GameObject> PrefabCache = new Dictionary<string, GameObject>(); private static readonly Dictionary<ConnectionProtocol, int> ProtocolToNameServerPort; public bool requestSecurity; private readonly Dictionary<string, int> rpcShortcuts; private Dictionary<int, object[]> tempInstantiationData; public static bool UsePrefabCache = true; static NetworkingPeer() { Dictionary<ConnectionProtocol, int> dictionary = new Dictionary<ConnectionProtocol, int>(); dictionary.Add(ConnectionProtocol.Udp, 0x13c2); dictionary.Add(ConnectionProtocol.Tcp, 0x11b5); ProtocolToNameServerPort = dictionary; } public NetworkingPeer(IPhotonPeerListener listener, string playername, ConnectionProtocol connectionProtocol) : base(listener, connectionProtocol) { this.playername = string.Empty; this.mActors = new Dictionary<int, PhotonPlayer>(); this.mOtherPlayerListCopy = new PhotonPlayer[0]; this.mPlayerListCopy = new PhotonPlayer[0]; this.requestSecurity = true; this.monoRPCMethodsCache = new Dictionary<System.Type, List<MethodInfo>>(); this.mGameList = new Dictionary<string, RoomInfo>(); this.mGameListCopy = new RoomInfo[0]; this.instantiatedObjects = new Dictionary<int, GameObject>(); this.allowedReceivingGroups = new HashSet<int>(); this.blockSendingGroups = new HashSet<int>(); this.photonViewList = new Dictionary<int, PhotonView>(); this.NameServerAddress = "ns.exitgamescloud.com"; this.tempInstantiationData = new Dictionary<int, object[]>(); if (PhotonHandler.PingImplementation == null) { PhotonHandler.PingImplementation = typeof(PingMono); } base.Listener = this; this.lobby = TypedLobby.Default; base.LimitOfUnreliableCommands = 40; this.externalListener = listener; this.PlayerName = playername; this.mLocalActor = new PhotonPlayer(true, -1, this.playername); this.AddNewPlayer(this.mLocalActor.ID, this.mLocalActor); this.rpcShortcuts = new Dictionary<string, int>(PhotonNetwork.PhotonServerSettings.RpcList.Count); for (int i = 0; i < PhotonNetwork.PhotonServerSettings.RpcList.Count; i++) { string str = PhotonNetwork.PhotonServerSettings.RpcList[i]; this.rpcShortcuts[str] = i; } this.State = PeerStates.PeerCreated; } private void AddNewPlayer(int ID, PhotonPlayer player) { if (!this.mActors.ContainsKey(ID)) { this.mActors[ID] = player; this.RebuildPlayerListCopies(); } else { Debug.LogError("Adding player twice: " + ID); } } private bool AlmostEquals(object[] lastData, object[] currentContent) { if ((lastData != null) || (currentContent != null)) { if (((lastData == null) || (currentContent == null)) || (lastData.Length != currentContent.Length)) { return false; } for (int i = 0; i < currentContent.Length; i++) { object one = currentContent[i]; object two = lastData[i]; if (!this.ObjectIsSameWithInprecision(one, two)) { return false; } } } return true; } public void ChangeLocalID(int newID) { if (this.mLocalActor == null) { Debug.LogWarning(string.Format("Local actor is null or not in mActors! mLocalActor: {0} mActors==null: {1} newID: {2}", this.mLocalActor, this.mActors == null, newID)); } if (this.mActors.ContainsKey(this.mLocalActor.ID)) { this.mActors.Remove(this.mLocalActor.ID); } this.mLocalActor.InternalChangeLocalID(newID); this.mActors[this.mLocalActor.ID] = this.mLocalActor; this.RebuildPlayerListCopies(); } public void checkLAN() { if ((((FengGameManagerMKII.OnPrivateServer && (this.MasterServerAddress != null)) && ((this.MasterServerAddress != string.Empty) && (this.mGameserver != null))) && (this.mGameserver != string.Empty)) && (this.MasterServerAddress.Contains(":") && this.mGameserver.Contains(":"))) { this.mGameserver = this.MasterServerAddress.Split(new char[] { ':' })[0] + ":" + this.mGameserver.Split(new char[] { ':' })[1]; } } private void CheckMasterClient(int leavingPlayerId) { bool flag = (this.mMasterClient != null) && (this.mMasterClient.ID == leavingPlayerId); bool flag2 = leavingPlayerId > 0; if (!flag2 || flag) { if (this.mActors.Count <= 1) { this.mMasterClient = this.mLocalActor; } else { int num = 0x7fffffff; foreach (int num2 in this.mActors.Keys) { if ((num2 < num) && (num2 != leavingPlayerId)) { num = num2; } } this.mMasterClient = this.mActors[num]; } if (flag2) { object[] parameters = new object[] { this.mMasterClient }; SendMonoMessage(PhotonNetworkingMessage.OnMasterClientSwitched, parameters); } } } private bool CheckTypeMatch(ParameterInfo[] methodParameters, System.Type[] callParameterTypes) { if (methodParameters.Length < callParameterTypes.Length) { return false; } for (int i = 0; i < callParameterTypes.Length; i++) { System.Type parameterType = methodParameters[i].ParameterType; if ((callParameterTypes[i] != null) && !parameterType.Equals(callParameterTypes[i])) { return false; } } return true; } public void CleanRpcBufferIfMine(PhotonView view) { if ((view.ownerId != this.mLocalActor.ID) && !this.mLocalActor.isMasterClient) { Debug.LogError(string.Concat(new object[] { "Cannot remove cached RPCs on a PhotonView thats not ours! ", view.owner, " scene: ", view.isSceneView })); } else { this.OpCleanRpcBuffer(view); } } public bool Connect(string serverAddress, ServerConnection type) { if (PhotonHandler.AppQuits) { Debug.LogWarning("Ignoring Connect() because app gets closed. If this is an error, check PhotonHandler.AppQuits."); return false; } if (PhotonNetwork.connectionStateDetailed == PeerStates.Disconnecting) { Debug.LogError("Connect() failed. Can't connect while disconnecting (still). Current state: " + PhotonNetwork.connectionStateDetailed); return false; } bool flag = base.Connect(serverAddress, string.Empty); if (flag) { switch (type) { case ServerConnection.MasterServer: this.State = PeerStates.ConnectingToMasterserver; return flag; case ServerConnection.GameServer: this.State = PeerStates.ConnectingToGameserver; return flag; case ServerConnection.NameServer: this.State = PeerStates.ConnectingToNameServer; return flag; } } return flag; } public override bool Connect(string serverAddress, string applicationName) { Debug.LogError("Avoid using this directly. Thanks."); return false; } public bool ConnectToNameServer() { if (PhotonHandler.AppQuits) { Debug.LogWarning("Ignoring Connect() because app gets closed. If this is an error, check PhotonHandler.AppQuits."); return false; } this.IsUsingNameServer = true; this.CloudRegion = CloudRegionCode.none; if (this.State != PeerStates.ConnectedToNameServer) { string nameServerAddress = this.NameServerAddress; if (!nameServerAddress.Contains(":")) { int num = 0; ProtocolToNameServerPort.TryGetValue(base.UsedProtocol, out num); nameServerAddress = string.Format("{0}:{1}", nameServerAddress, num); Debug.Log(string.Concat(new object[] { "Server to connect to: ", nameServerAddress, " settings protocol: ", PhotonNetwork.PhotonServerSettings.Protocol })); } if (!base.Connect(nameServerAddress, "ns")) { return false; } this.State = PeerStates.ConnectingToNameServer; } return true; } public bool ConnectToRegionMaster(CloudRegionCode region) { if (PhotonHandler.AppQuits) { Debug.LogWarning("Ignoring Connect() because app gets closed. If this is an error, check PhotonHandler.AppQuits."); return false; } this.IsUsingNameServer = true; this.CloudRegion = region; if (this.State == PeerStates.ConnectedToNameServer) { return this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, region.ToString()); } string nameServerAddress = this.NameServerAddress; if (!nameServerAddress.Contains(":")) { int num = 0; ProtocolToNameServerPort.TryGetValue(base.UsedProtocol, out num); nameServerAddress = string.Format("{0}:{1}", nameServerAddress, num); } if (!base.Connect(nameServerAddress, "ns")) { return false; } this.State = PeerStates.ConnectingToNameServer; return true; } public void DebugReturn(DebugLevel level, string message) { this.externalListener.DebugReturn(level, message); } private bool DeltaCompressionRead(PhotonView view, ExitGames.Client.Photon.Hashtable data) { if (!data.ContainsKey((byte) 1)) { if (view.lastOnSerializeDataReceived == null) { return false; } object[] objArray = data[(byte) 2] as object[]; if (objArray == null) { return false; } int[] target = data[(byte) 3] as int[]; if (target == null) { target = new int[0]; } object[] lastOnSerializeDataReceived = view.lastOnSerializeDataReceived; for (int i = 0; i < objArray.Length; i++) { if ((objArray[i] == null) && !target.Contains(i)) { objArray[i] = lastOnSerializeDataReceived[i]; } } data[(byte) 1] = objArray; } return true; } private bool DeltaCompressionWrite(PhotonView view, ExitGames.Client.Photon.Hashtable data) { if (view.lastOnSerializeDataSent != null) { object[] lastOnSerializeDataSent = view.lastOnSerializeDataSent; object[] objArray2 = data[(byte) 1] as object[]; if (objArray2 == null) { return false; } if (lastOnSerializeDataSent.Length != objArray2.Length) { return true; } object[] objArray3 = new object[objArray2.Length]; int num = 0; List<int> list = new List<int>(); for (int i = 0; i < objArray3.Length; i++) { object one = objArray2[i]; object two = lastOnSerializeDataSent[i]; if (this.ObjectIsSameWithInprecision(one, two)) { num++; } else { objArray3[i] = objArray2[i]; if (one == null) { list.Add(i); } } } if (num > 0) { data.Remove((byte) 1); if (num == objArray2.Length) { return false; } data[(byte) 2] = objArray3; if (list.Count > 0) { data[(byte) 3] = list.ToArray(); } } } return true; } public void DestroyAll(bool localOnly) { if (!localOnly) { this.OpRemoveCompleteCache(); this.SendDestroyOfAll(); } this.LocalCleanupAnythingInstantiated(true); } public void DestroyPlayerObjects(int playerId, bool localOnly) { if (playerId <= 0) { Debug.LogError("Failed to Destroy objects of playerId: " + playerId); } else { if (!localOnly) { this.OpRemoveFromServerInstantiationsOfPlayer(playerId); this.OpCleanRpcBuffer(playerId); this.SendDestroyOfPlayer(playerId); } Queue<GameObject> queue = new Queue<GameObject>(); int num = playerId * PhotonNetwork.MAX_VIEW_IDS; int num2 = num + PhotonNetwork.MAX_VIEW_IDS; foreach (KeyValuePair<int, GameObject> pair in this.instantiatedObjects) { if ((pair.Key > num) && (pair.Key < num2)) { queue.Enqueue(pair.Value); } } foreach (GameObject obj2 in queue) { this.RemoveInstantiatedGO(obj2, true); } } } public override void Disconnect() { if (base.PeerState == PeerStateValue.Disconnected) { if (!PhotonHandler.AppQuits) { Debug.LogWarning(string.Format("Can't execute Disconnect() while not connected. Nothing changed. State: {0}", this.State)); } } else { this.State = PeerStates.Disconnecting; base.Disconnect(); } } private void DisconnectToReconnect() { this.checkLAN(); switch (this.server) { case ServerConnection.MasterServer: this.State = FengGameManagerMKII.returnPeerState(2); base.Disconnect(); break; case ServerConnection.GameServer: this.State = FengGameManagerMKII.returnPeerState(3); base.Disconnect(); break; case ServerConnection.NameServer: this.State = FengGameManagerMKII.returnPeerState(4); base.Disconnect(); break; } } internal GameObject DoInstantiate(ExitGames.Client.Photon.Hashtable evData, PhotonPlayer photonPlayer, GameObject resourceGameObject) { Vector3 zero; int[] numArray; object[] objArray; string key = (string) evData[(byte) 0]; int timestamp = (int) evData[(byte) 6]; int instantiationId = (int) evData[(byte) 7]; if (evData.ContainsKey((byte) 1)) { zero = (Vector3) evData[(byte) 1]; } else { zero = Vector3.zero; } Quaternion identity = Quaternion.identity; if (evData.ContainsKey((byte) 2)) { identity = (Quaternion) evData[(byte) 2]; } int item = 0; if (evData.ContainsKey((byte) 3)) { item = (int) evData[(byte) 3]; } short num4 = 0; if (evData.ContainsKey((byte) 8)) { num4 = (short) evData[(byte) 8]; } if (evData.ContainsKey((byte) 4)) { numArray = (int[]) evData[(byte) 4]; } else { numArray = new int[] { instantiationId }; } if (!InstantiateTracker.instance.checkObj(key, photonPlayer, numArray)) { return null; } if (evData.ContainsKey((byte) 5)) { objArray = (object[]) evData[(byte) 5]; } else { objArray = null; } if (!((item == 0) || this.allowedReceivingGroups.Contains(item))) { return null; } if (resourceGameObject == null) { if (!UsePrefabCache || !PrefabCache.TryGetValue(key, out resourceGameObject)) { if (key.StartsWith("RCAsset/")) { resourceGameObject = FengGameManagerMKII.InstantiateCustomAsset(key); } else { resourceGameObject = (GameObject) Resources.Load(key, typeof(GameObject)); } if (UsePrefabCache) { PrefabCache.Add(key, resourceGameObject); } } if (resourceGameObject == null) { Debug.LogError("PhotonNetwork error: Could not Instantiate the prefab [" + key + "]. Please verify you have this gameobject in a Resources folder."); return null; } } PhotonView[] photonViewsInChildren = resourceGameObject.GetPhotonViewsInChildren(); if (photonViewsInChildren.Length != numArray.Length) { throw new Exception("Error in Instantiation! The resource's PhotonView count is not the same as in incoming data."); } for (int i = 0; i < numArray.Length; i++) { photonViewsInChildren[i].viewID = numArray[i]; photonViewsInChildren[i].prefix = num4; photonViewsInChildren[i].instantiationId = instantiationId; } this.StoreInstantiationData(instantiationId, objArray); GameObject obj3 = (GameObject) UnityEngine.Object.Instantiate(resourceGameObject, zero, identity); for (int j = 0; j < numArray.Length; j++) { photonViewsInChildren[j].viewID = 0; photonViewsInChildren[j].prefix = -1; photonViewsInChildren[j].prefixBackup = -1; photonViewsInChildren[j].instantiationId = -1; } this.RemoveInstantiationData(instantiationId); if (this.instantiatedObjects.ContainsKey(instantiationId)) { GameObject go = this.instantiatedObjects[instantiationId]; string str2 = string.Empty; if (go != null) { foreach (PhotonView view in go.GetPhotonViewsInChildren()) { if (view != null) { str2 = str2 + view.ToString() + ", "; } } } object[] args = new object[] { obj3, instantiationId, this.instantiatedObjects.Count, go, str2, PhotonNetwork.lastUsedViewSubId, PhotonNetwork.lastUsedViewSubIdStatic, this.photonViewList.Count }; Debug.LogError(string.Format("DoInstantiate re-defines a GameObject. Destroying old entry! New: '{0}' (instantiationID: {1}) Old: {3}. PhotonViews on old: {4}. instantiatedObjects.Count: {2}. PhotonNetwork.lastUsedViewSubId: {5} PhotonNetwork.lastUsedViewSubIdStatic: {6} this.photonViewList.Count {7}.)", args)); this.RemoveInstantiatedGO(go, true); } this.instantiatedObjects.Add(instantiationId, obj3); obj3.SendMessage(PhotonNetworkingMessage.OnPhotonInstantiate.ToString(), new PhotonMessageInfo(photonPlayer, timestamp, null), SendMessageOptions.DontRequireReceiver); return obj3; } public void ExecuteRPC(ExitGames.Client.Photon.Hashtable rpcData, PhotonPlayer sender) { if ((rpcData == null) || !rpcData.ContainsKey((byte) 0)) { Debug.LogError("Malformed RPC; this should never occur. Content: " + SupportClass.DictionaryToString(rpcData)); } else { string str; int viewID = (int) rpcData[(byte) 0]; int num2 = 0; if (rpcData.ContainsKey((byte) 1)) { num2 = (short) rpcData[(byte) 1]; } if (rpcData.ContainsKey((byte) 5)) { int num3 = (byte) rpcData[(byte) 5]; if (num3 > (PhotonNetwork.PhotonServerSettings.RpcList.Count - 1)) { Debug.LogError("Could not find RPC with index: " + num3 + ". Going to ignore! Check PhotonServerSettings.RpcList"); return; } str = PhotonNetwork.PhotonServerSettings.RpcList[num3]; } else { str = (string) rpcData[(byte) 3]; } object[] parameters = null; if (rpcData.ContainsKey((byte) 4)) { parameters = (object[]) rpcData[(byte) 4]; } if (parameters == null) { parameters = new object[0]; } PhotonView photonView = this.GetPhotonView(viewID); if (photonView == null) { int num4 = viewID / PhotonNetwork.MAX_VIEW_IDS; bool flag = num4 == this.mLocalActor.ID; bool flag2 = num4 == sender.ID; if (flag) { Debug.LogWarning(string.Concat(new object[] { "Received RPC \"", str, "\" for viewID ", viewID, " but this PhotonView does not exist! View was/is ours.", !flag2 ? " Remote called." : " Owner called." })); } else { Debug.LogError(string.Concat(new object[] { "Received RPC \"", str, "\" for viewID ", viewID, " but this PhotonView does not exist! Was remote PV.", !flag2 ? " Remote called." : " Owner called." })); } } else if (photonView.prefix != num2) { Debug.LogError(string.Concat(new object[] { "Received RPC \"", str, "\" on viewID ", viewID, " with a prefix of ", num2, ", our prefix is ", photonView.prefix, ". The RPC has been ignored." })); } else if (str == string.Empty) { Debug.LogError("Malformed RPC; this should never occur. Content: " + SupportClass.DictionaryToString(rpcData)); } else { if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) { Debug.Log("Received RPC: " + str); } if ((photonView.group == 0) || this.allowedReceivingGroups.Contains(photonView.group)) { System.Type[] callParameterTypes = new System.Type[0]; if (parameters.Length > 0) { callParameterTypes = new System.Type[parameters.Length]; int index = 0; for (int i = 0; i < parameters.Length; i++) { object obj2 = parameters[i]; if (obj2 == null) { callParameterTypes[index] = null; } else { callParameterTypes[index] = obj2.GetType(); } index++; } } int num7 = 0; int num8 = 0; foreach (MonoBehaviour behaviour in photonView.GetComponents<MonoBehaviour>()) { if (behaviour == null) { Debug.LogError("ERROR You have missing MonoBehaviours on your gameobjects!"); } else { System.Type key = behaviour.GetType(); List<MethodInfo> list = null; if (this.monoRPCMethodsCache.ContainsKey(key)) { list = this.monoRPCMethodsCache[key]; } if (list == null) { List<MethodInfo> methods = SupportClass.GetMethods(key, typeof(UnityEngine.RPC)); this.monoRPCMethodsCache[key] = methods; list = methods; } if (list != null) { for (int j = 0; j < list.Count; j++) { MethodInfo info = list[j]; if (info.Name == str) { num8++; ParameterInfo[] methodParameters = info.GetParameters(); if (methodParameters.Length == callParameterTypes.Length) { if (this.CheckTypeMatch(methodParameters, callParameterTypes)) { num7++; object obj3 = info.Invoke(behaviour, parameters); if (info.ReturnType == typeof(IEnumerator)) { behaviour.StartCoroutine((IEnumerator) obj3); } } } else if ((methodParameters.Length - 1) == callParameterTypes.Length) { if (this.CheckTypeMatch(methodParameters, callParameterTypes) && (methodParameters[methodParameters.Length - 1].ParameterType == typeof(PhotonMessageInfo))) { num7++; int timestamp = (int) rpcData[(byte) 2]; object[] array = new object[parameters.Length + 1]; parameters.CopyTo(array, 0); array[array.Length - 1] = new PhotonMessageInfo(sender, timestamp, photonView); object obj4 = info.Invoke(behaviour, array); if (info.ReturnType == typeof(IEnumerator)) { behaviour.StartCoroutine((IEnumerator) obj4); } } } else if ((methodParameters.Length == 1) && methodParameters[0].ParameterType.IsArray) { num7++; object[] objArray5 = new object[] { parameters }; object obj5 = info.Invoke(behaviour, objArray5); if (info.ReturnType == typeof(IEnumerator)) { behaviour.StartCoroutine((IEnumerator) obj5); } } } } } } } if (num7 != 1) { string str2 = string.Empty; for (int k = 0; k < callParameterTypes.Length; k++) { System.Type type2 = callParameterTypes[k]; if (str2 != string.Empty) { str2 = str2 + ", "; } if (type2 == null) { str2 = str2 + "null"; } else { str2 = str2 + type2.Name; } } if (num7 == 0) { if (num8 == 0) { Debug.LogError(string.Concat(new object[] { "PhotonView with ID ", viewID, " has no method \"", str, "\" marked with the [RPC](C#) or @RPC(JS) property! Args: ", str2 })); } else { Debug.LogError(string.Concat(new object[] { "PhotonView with ID ", viewID, " has no method \"", str, "\" that takes ", callParameterTypes.Length, " argument(s): ", str2 })); } } else { Debug.LogError(string.Concat(new object[] { "PhotonView with ID ", viewID, " has ", num7, " methods \"", str, "\" that takes ", callParameterTypes.Length, " argument(s): ", str2, ". Should be just one?" })); } } } } } } public object[] FetchInstantiationData(int instantiationId) { object[] objArray = null; if (instantiationId == 0) { return null; } this.tempInstantiationData.TryGetValue(instantiationId, out objArray); return objArray; } private void GameEnteredOnGameServer(OperationResponse operationResponse) { if (operationResponse.ReturnCode == 0) { this.State = PeerStates.Joined; this.mRoomToGetInto.isLocalClientInside = true; ExitGames.Client.Photon.Hashtable pActorProperties = (ExitGames.Client.Photon.Hashtable) operationResponse[0xf9]; ExitGames.Client.Photon.Hashtable gameProperties = (ExitGames.Client.Photon.Hashtable) operationResponse[0xf8]; this.ReadoutProperties(gameProperties, pActorProperties, 0); int newID = (int) operationResponse[0xfe]; this.ChangeLocalID(newID); this.CheckMasterClient(-1); if (this.mPlayernameHasToBeUpdated) { this.SendPlayerName(); } switch (operationResponse.OperationCode) { case 0xe3: SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom, new object[0]); break; } } else { switch (operationResponse.OperationCode) { case 0xe1: { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log("Join failed on GameServer. Changing back to MasterServer. Msg: " + operationResponse.DebugMessage); if (operationResponse.ReturnCode == 0x7ff6) { Debug.Log("Most likely the game became empty during the switch to GameServer."); } } object[] parameters = new object[] { operationResponse.ReturnCode, operationResponse.DebugMessage }; SendMonoMessage(PhotonNetworkingMessage.OnPhotonRandomJoinFailed, parameters); break; } case 0xe2: { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log("Join failed on GameServer. Changing back to MasterServer. Msg: " + operationResponse.DebugMessage); if (operationResponse.ReturnCode == 0x7ff6) { Debug.Log("Most likely the game became empty during the switch to GameServer."); } } object[] objArray2 = new object[] { operationResponse.ReturnCode, operationResponse.DebugMessage }; SendMonoMessage(PhotonNetworkingMessage.OnPhotonJoinRoomFailed, objArray2); break; } case 0xe3: { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log("Create failed on GameServer. Changing back to MasterServer. Msg: " + operationResponse.DebugMessage); } object[] objArray1 = new object[] { operationResponse.ReturnCode, operationResponse.DebugMessage }; SendMonoMessage(PhotonNetworkingMessage.OnPhotonCreateRoomFailed, objArray1); break; } } this.DisconnectToReconnect(); } } private ExitGames.Client.Photon.Hashtable GetActorPropertiesForActorNr(ExitGames.Client.Photon.Hashtable actorProperties, int actorNr) { if (actorProperties.ContainsKey(actorNr)) { return (ExitGames.Client.Photon.Hashtable) actorProperties[actorNr]; } return actorProperties; } public int GetInstantiatedObjectsId(GameObject go) { int num = -1; if (go == null) { Debug.LogError("GetInstantiatedObjectsId() for GO == null."); return num; } PhotonView[] photonViewsInChildren = go.GetPhotonViewsInChildren(); if (((photonViewsInChildren != null) && (photonViewsInChildren.Length > 0)) && (photonViewsInChildren[0] != null)) { return photonViewsInChildren[0].instantiationId; } if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log("GetInstantiatedObjectsId failed for GO: " + go); } return num; } private ExitGames.Client.Photon.Hashtable GetLocalActorProperties() { if (PhotonNetwork.player != null) { return PhotonNetwork.player.allProperties; } ExitGames.Client.Photon.Hashtable hashtable = new ExitGames.Client.Photon.Hashtable(); hashtable[(byte) 0xff] = this.PlayerName; return hashtable; } protected internal static bool GetMethod(MonoBehaviour monob, string methodType, out MethodInfo mi) { mi = null; if ((monob != null) && !string.IsNullOrEmpty(methodType)) { List<MethodInfo> methods = SupportClass.GetMethods(monob.GetType(), null); for (int i = 0; i < methods.Count; i++) { MethodInfo info = methods[i]; if (info.Name.Equals(methodType)) { mi = info; return true; } } } return false; } public PhotonView GetPhotonView(int viewID) { PhotonView view = null; this.photonViewList.TryGetValue(viewID, out view); if (view == null) { PhotonView[] viewArray = UnityEngine.Object.FindObjectsOfType(typeof(PhotonView)) as PhotonView[]; foreach (PhotonView view2 in viewArray) { if (view2.viewID == viewID) { if (view2.didAwake) { Debug.LogWarning("Had to lookup view that wasn't in dict: " + view2); } return view2; } } } return view; } private PhotonPlayer GetPlayerWithID(int number) { if ((this.mActors != null) && this.mActors.ContainsKey(number)) { return this.mActors[number]; } return null; } public bool GetRegions() { if (this.server != ServerConnection.NameServer) { return false; } bool flag = this.OpGetRegions(this.mAppId); if (flag) { this.AvailableRegions = null; } return flag; } private void HandleEventLeave(int actorID) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log("HandleEventLeave for player ID: " + actorID); } if ((actorID < 0) || !this.mActors.ContainsKey(actorID)) { Debug.LogError(string.Format("Received event Leave for unknown player ID: {0}", actorID)); } else { PhotonPlayer playerWithID = this.GetPlayerWithID(actorID); if (playerWithID == null) { Debug.LogError("HandleEventLeave for player ID: " + actorID + " has no PhotonPlayer!"); } this.CheckMasterClient(actorID); if ((this.mCurrentGame != null) && this.mCurrentGame.autoCleanUp) { this.DestroyPlayerObjects(actorID, true); } this.RemovePlayer(actorID, playerWithID); object[] parameters = new object[] { playerWithID }; SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerDisconnected, parameters); } } private void LeftLobbyCleanup() { this.mGameList = new Dictionary<string, RoomInfo>(); this.mGameListCopy = new RoomInfo[0]; if (this.insideLobby) { this.insideLobby = false; SendMonoMessage(PhotonNetworkingMessage.OnLeftLobby, new object[0]); } } private void LeftRoomCleanup() { bool flag = this.mRoomToGetInto != null; bool flag2 = (this.mRoomToGetInto == null) ? PhotonNetwork.autoCleanUpPlayerObjects : this.mRoomToGetInto.autoCleanUp; this.hasSwitchedMC = false; this.mRoomToGetInto = null; this.mActors = new Dictionary<int, PhotonPlayer>(); this.mPlayerListCopy = new PhotonPlayer[0]; this.mOtherPlayerListCopy = new PhotonPlayer[0]; this.mMasterClient = null; this.allowedReceivingGroups = new HashSet<int>(); this.blockSendingGroups = new HashSet<int>(); this.mGameList = new Dictionary<string, RoomInfo>(); this.mGameListCopy = new RoomInfo[0]; this.isFetchingFriends = false; this.ChangeLocalID(-1); if (flag2) { this.LocalCleanupAnythingInstantiated(true); PhotonNetwork.manuallyAllocatedViewIds = new List<int>(); } if (flag) { SendMonoMessage(PhotonNetworkingMessage.OnLeftRoom, new object[0]); } } protected internal void LoadLevelIfSynced() { if (((PhotonNetwork.automaticallySyncScene && !PhotonNetwork.isMasterClient) && (PhotonNetwork.room != null)) && PhotonNetwork.room.customProperties.ContainsKey("curScn")) { object obj2 = PhotonNetwork.room.customProperties["curScn"]; if (obj2 is int) { if (Application.loadedLevel != ((int) obj2)) { PhotonNetwork.LoadLevel((int) obj2); } } else if ((obj2 is string) && (Application.loadedLevelName != ((string) obj2))) { PhotonNetwork.LoadLevel((string) obj2); } } } public void LocalCleanPhotonView(PhotonView view) { view.destroyedByPhotonNetworkOrQuit = true; this.photonViewList.Remove(view.viewID); } protected internal void LocalCleanupAnythingInstantiated(bool destroyInstantiatedGameObjects) { if (this.tempInstantiationData.Count > 0) { Debug.LogWarning("It seems some instantiation is not completed, as instantiation data is used. You should make sure instantiations are paused when calling this method. Cleaning now, despite this."); } if (destroyInstantiatedGameObjects) { HashSet<GameObject> set = new HashSet<GameObject>(this.instantiatedObjects.Values); foreach (GameObject obj2 in set) { this.RemoveInstantiatedGO(obj2, true); } } this.tempInstantiationData.Clear(); this.instantiatedObjects = new Dictionary<int, GameObject>(); PhotonNetwork.lastUsedViewSubId = 0; PhotonNetwork.lastUsedViewSubIdStatic = 0; } public void NewSceneLoaded() { if (this.loadingLevelAndPausedNetwork) { this.loadingLevelAndPausedNetwork = false; PhotonNetwork.isMessageQueueRunning = true; } List<int> list = new List<int>(); foreach (KeyValuePair<int, PhotonView> pair in this.photonViewList) { if (pair.Value == null) { list.Add(pair.Key); } } for (int i = 0; i < list.Count; i++) { int key = list[i]; this.photonViewList.Remove(key); } if ((list.Count > 0) && (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)) { Debug.Log("New level loaded. Removed " + list.Count + " scene view IDs from last level."); } } private bool ObjectIsSameWithInprecision(object one, object two) { if ((one == null) || (two == null)) { return ((one == null) && (two == null)); } if (one.Equals(two)) { return true; } if (one is Vector3) { Vector3 target = (Vector3) one; Vector3 second = (Vector3) two; if (target.AlmostEquals(second, PhotonNetwork.precisionForVectorSynchronization)) { return true; } } else if (one is Vector2) { Vector2 vector3 = (Vector2) one; Vector2 vector4 = (Vector2) two; if (vector3.AlmostEquals(vector4, PhotonNetwork.precisionForVectorSynchronization)) { return true; } } else if (one is Quaternion) { Quaternion quaternion = (Quaternion) one; Quaternion quaternion2 = (Quaternion) two; if (quaternion.AlmostEquals(quaternion2, PhotonNetwork.precisionForQuaternionSynchronization)) { return true; } } else if (one is float) { float num = (float) one; float num2 = (float) two; if (num.AlmostEquals(num2, PhotonNetwork.precisionForFloatSynchronization)) { return true; } } return false; } public void OnEvent(EventData photonEvent) { ExitGames.Client.Photon.Hashtable hashtable3; object obj7; object obj8; object obj9; int key = -1; PhotonPlayer sender = null; if (photonEvent.Parameters.ContainsKey(0xfe)) { key = (int) photonEvent[0xfe]; if (this.mActors.ContainsKey(key)) { sender = this.mActors[key]; } } else if (photonEvent.Parameters.Count == 0) { return; } switch (photonEvent.Code) { case 200: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { this.ExecuteRPC(photonEvent[0xf5] as ExitGames.Client.Photon.Hashtable, sender); break; } return; case 0xc9: case 0xce: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { object obj2 = photonEvent[0xf5]; if ((obj2 != null) && (obj2 is ExitGames.Client.Photon.Hashtable)) { ExitGames.Client.Photon.Hashtable hashtable = (ExitGames.Client.Photon.Hashtable) photonEvent[0xf5]; if (!(hashtable[(byte) 0] is int)) { return; } int networkTime = (int) hashtable[(byte) 0]; short correctPrefix = -1; short num6 = 1; if (hashtable.ContainsKey((byte) 1)) { if (!(hashtable[(byte) 1] is short)) { return; } correctPrefix = (short) hashtable[(byte) 1]; num6 = 2; } for (short i = num6; i < hashtable.Count; i = (short) (i + 1)) { this.OnSerializeRead(hashtable[i] as ExitGames.Client.Photon.Hashtable, sender, networkTime, correctPrefix); } } break; } return; case 0xca: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { if (photonEvent[0xf5] is ExitGames.Client.Photon.Hashtable) { ExitGames.Client.Photon.Hashtable evData = (ExitGames.Client.Photon.Hashtable) photonEvent[0xf5]; if (evData[(byte) 0] is string) { string str = (string) evData[(byte) 0]; if (str != null) { this.DoInstantiate(evData, sender, null); } } } break; } return; case 0xcb: if ((sender != null) && (sender.isMasterClient && !sender.isLocal)) { PhotonNetwork.LeaveRoom(); } break; case 0xcc: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { if (photonEvent[0xf5] is ExitGames.Client.Photon.Hashtable) { hashtable3 = (ExitGames.Client.Photon.Hashtable) photonEvent[0xf5]; if (hashtable3[(byte) 0] is int) { int num8 = (int) hashtable3[(byte) 0]; GameObject obj3 = null; this.instantiatedObjects.TryGetValue(num8, out obj3); if ((obj3 != null) && (sender != null)) { this.RemoveInstantiatedGO(obj3, true); } } } break; } return; case 0xcf: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { if (photonEvent[0xf5] is ExitGames.Client.Photon.Hashtable) { hashtable3 = (ExitGames.Client.Photon.Hashtable) photonEvent[0xf5]; if (hashtable3[(byte) 0] is int) { int playerId = (int) hashtable3[(byte) 0]; if ((playerId < 0) && ((sender != null) && (sender.isMasterClient || sender.isLocal))) { this.DestroyAll(true); } else if ((sender != null) && ((sender.isMasterClient || sender.isLocal) || (playerId != PhotonNetwork.player.ID))) { this.DestroyPlayerObjects(playerId, true); } } } break; } return; case 0xd0: { if (!(photonEvent[0xf5] is ExitGames.Client.Photon.Hashtable)) { break; } hashtable3 = (ExitGames.Client.Photon.Hashtable) photonEvent[0xf5]; if (!(hashtable3[(byte) 1] is int)) { break; } int num10 = (int) hashtable3[(byte) 1]; if (((sender == null) || !sender.isMasterClient) || (num10 != sender.ID)) { if (!(((sender == null) || sender.isMasterClient) || sender.isLocal)) { if (PhotonNetwork.isMasterClient) { FengGameManagerMKII.noRestart = true; PhotonNetwork.SetMasterClient(PhotonNetwork.player); FengGameManagerMKII.instance.kickPlayerRC(sender, true, "stealing MC."); } return; } if (num10 == this.mLocalActor.ID) { this.SetMasterClient(num10, false); } else if (((sender == null) || sender.isMasterClient) || sender.isLocal) { this.SetMasterClient(num10, false); } break; } return; } case 0xe2: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { object obj4 = photonEvent[0xe5]; object obj5 = photonEvent[0xe3]; object obj6 = photonEvent[0xe4]; if (((obj4 is int) && (obj5 is int)) && (obj6 is int)) { this.mPlayersInRoomsCount = (int) obj4; this.mPlayersOnMasterCount = (int) obj5; this.mGameCount = (int) obj6; } break; } return; case 0xe4: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { if (photonEvent.Parameters.ContainsKey(0xdf)) { obj7 = photonEvent[0xdf]; if (obj7 is int) { this.mQueuePosition = (int) obj7; } } if (this.mQueuePosition == 0) { if (PhotonNetwork.autoJoinLobby) { this.State = FengGameManagerMKII.returnPeerState(0); this.OpJoinLobby(this.lobby); } else { this.State = FengGameManagerMKII.returnPeerState(1); SendMonoMessage(PhotonNetworkingMessage.OnConnectedToMaster, new object[0]); } } break; } return; case 0xe5: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { obj7 = photonEvent[0xde]; if (obj7 is ExitGames.Client.Photon.Hashtable) { foreach (DictionaryEntry entry in (ExitGames.Client.Photon.Hashtable) obj7) { string roomName = (string) entry.Key; RoomInfo info = new RoomInfo(roomName, (ExitGames.Client.Photon.Hashtable) entry.Value); if (info.removedFromList) { this.mGameList.Remove(roomName); } else { this.mGameList[roomName] = info; } } this.mGameListCopy = new RoomInfo[this.mGameList.Count]; this.mGameList.Values.CopyTo(this.mGameListCopy, 0); SendMonoMessage(PhotonNetworkingMessage.OnReceivedRoomListUpdate, new object[0]); } break; } return; case 230: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { obj7 = photonEvent[0xde]; if (obj7 is ExitGames.Client.Photon.Hashtable) { this.mGameList = new Dictionary<string, RoomInfo>(); foreach (DictionaryEntry entry2 in (ExitGames.Client.Photon.Hashtable) obj7) { string str3 = (string) entry2.Key; this.mGameList[str3] = new RoomInfo(str3, (ExitGames.Client.Photon.Hashtable) entry2.Value); } this.mGameListCopy = new RoomInfo[this.mGameList.Count]; this.mGameList.Values.CopyTo(this.mGameListCopy, 0); SendMonoMessage(PhotonNetworkingMessage.OnReceivedRoomListUpdate, new object[0]); } break; } return; case 0xfd: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { obj8 = photonEvent[0xfd]; if (obj8 is int) { int iD = (int) obj8; ExitGames.Client.Photon.Hashtable gameProperties = null; ExitGames.Client.Photon.Hashtable pActorProperties = null; if (iD != 0) { obj9 = photonEvent[0xfb]; if (obj9 is ExitGames.Client.Photon.Hashtable) { pActorProperties = (ExitGames.Client.Photon.Hashtable) obj9; if (sender != null) { pActorProperties["sender"] = sender; if (((PhotonNetwork.isMasterClient && !sender.isLocal) && (iD == sender.ID)) && (((pActorProperties.ContainsKey("statACL") || pActorProperties.ContainsKey("statBLA")) || pActorProperties.ContainsKey("statGAS")) || pActorProperties.ContainsKey("statSPD"))) { PhotonPlayer player2 = sender; if (pActorProperties.ContainsKey("statACL") && (RCextensions.returnIntFromObject(pActorProperties["statACL"]) > 150)) { FengGameManagerMKII.instance.kickPlayerRC(sender, true, "excessive stats."); return; } if (pActorProperties.ContainsKey("statBLA") && (RCextensions.returnIntFromObject(pActorProperties["statBLA"]) > 0x7d)) { FengGameManagerMKII.instance.kickPlayerRC(sender, true, "excessive stats."); return; } if (pActorProperties.ContainsKey("statGAS") && (RCextensions.returnIntFromObject(pActorProperties["statGAS"]) > 150)) { FengGameManagerMKII.instance.kickPlayerRC(sender, true, "excessive stats."); return; } if (pActorProperties.ContainsKey("statSPD") && (RCextensions.returnIntFromObject(pActorProperties["statSPD"]) > 140)) { FengGameManagerMKII.instance.kickPlayerRC(sender, true, "excessive stats."); return; } } if (pActorProperties.ContainsKey("name")) { if (iD != sender.ID) { InstantiateTracker.instance.resetPropertyTracking(iD); } else if (!InstantiateTracker.instance.PropertiesChanged(sender)) { return; } } } } } else { obj9 = photonEvent[0xfb]; if ((obj9 != null) && (obj9 is ExitGames.Client.Photon.Hashtable)) { gameProperties = (ExitGames.Client.Photon.Hashtable) obj9; } else { return; } } this.ReadoutProperties(gameProperties, pActorProperties, iD); } break; } return; case 0xfe: this.HandleEventLeave(key); break; case 0xff: if ((sender == null) || !FengGameManagerMKII.ignoreList.Contains(sender.ID)) { obj8 = photonEvent[0xf9]; if ((obj8 == null) || (obj8 is ExitGames.Client.Photon.Hashtable)) { ExitGames.Client.Photon.Hashtable properties = (ExitGames.Client.Photon.Hashtable) obj8; if (sender == null) { bool isLocal = this.mLocalActor.ID == key; this.AddNewPlayer(key, new PhotonPlayer(isLocal, key, properties)); this.ResetPhotonViewsOnSerialize(); } if (key != this.mLocalActor.ID) { object[] parameters = new object[] { this.mActors[key] }; SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerConnected, parameters); } else { obj9 = photonEvent[0xfc]; if (obj9 is int[]) { int[] numArray = (int[]) obj9; foreach (int num17 in numArray) { if (!((this.mLocalActor.ID == num17) || this.mActors.ContainsKey(num17))) { this.AddNewPlayer(num17, new PhotonPlayer(false, num17, string.Empty)); } } if ((this.mLastJoinType == JoinType.JoinOrCreateOnDemand) && (this.mLocalActor.ID == 1)) { SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom, new object[0]); } SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom, new object[0]); } } } break; } return; default: if ((sender != null) && FengGameManagerMKII.ignoreList.Contains(sender.ID)) { return; } if ((photonEvent.Code < 200) && (PhotonNetwork.OnEventCall != null)) { object content = photonEvent[0xf5]; PhotonNetwork.OnEventCall(photonEvent.Code, content, key); } break; } this.externalListener.OnEvent(photonEvent); } public void OnOperationResponse(OperationResponse operationResponse) { if (PhotonNetwork.networkingPeer.State == PeerStates.Disconnecting) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log("OperationResponse ignored while disconnecting. Code: " + operationResponse.OperationCode); } return; } if (operationResponse.ReturnCode == 0) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log(operationResponse.ToString()); } } else if (operationResponse.ReturnCode == -3) { Debug.LogError("Operation " + operationResponse.OperationCode + " could not be executed (yet). Wait for state JoinedLobby or ConnectedToMaster and their callbacks before calling operations. WebRPCs need a server-side configuration. Enum OperationCode helps identify the operation."); } else if (operationResponse.ReturnCode == 0x7ff0) { Debug.LogError(string.Concat(new object[] { "Operation ", operationResponse.OperationCode, " failed in a server-side plugin. Check the configuration in the Dashboard. Message from server-plugin: ", operationResponse.DebugMessage })); } else if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.LogError(string.Concat(new object[] { "Operation failed: ", operationResponse.ToStringFull(), " Server: ", this.server })); } if (operationResponse.Parameters.ContainsKey(0xdd)) { if (this.CustomAuthenticationValues == null) { this.CustomAuthenticationValues = new AuthenticationValues(); } this.CustomAuthenticationValues.Secret = operationResponse[0xdd] as string; } byte operationCode = operationResponse.OperationCode; switch (operationCode) { case 0xdb: { object[] parameters = new object[] { operationResponse }; SendMonoMessage(PhotonNetworkingMessage.OnWebRpcResponse, parameters); goto Label_0955; } case 220: { if (operationResponse.ReturnCode != 0x7fff) { string[] strArray = operationResponse[210] as string[]; string[] strArray2 = operationResponse[230] as string[]; if (((strArray == null) || (strArray2 == null)) || (strArray.Length != strArray2.Length)) { Debug.LogError("The region arrays from Name Server are not ok. Must be non-null and same length."); } else { this.AvailableRegions = new List<Region>(strArray.Length); for (int i = 0; i < strArray.Length; i++) { string str = strArray[i]; if (!string.IsNullOrEmpty(str)) { CloudRegionCode code = Region.Parse(str.ToLower()); Region item = new Region { Code = code, HostAndPort = strArray2[i] }; this.AvailableRegions.Add(item); } } if (PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.BestRegion) { PhotonHandler.PingAvailableRegionsAndConnectToBest(); } } goto Label_0955; } Debug.LogError(string.Format("The appId this client sent is unknown on the server (Cloud). Check settings. If using the Cloud, check account.", new object[0])); object[] objArray8 = new object[] { DisconnectCause.InvalidAuthentication }; SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, objArray8); this.State = PeerStates.Disconnecting; this.Disconnect(); return; } case 0xde: { bool[] flagArray = operationResponse[1] as bool[]; string[] strArray3 = operationResponse[2] as string[]; if (((flagArray == null) || (strArray3 == null)) || ((this.friendListRequested == null) || (flagArray.Length != this.friendListRequested.Length))) { Debug.LogError("FindFriends failed to apply the result, as a required value wasn't provided or the friend list length differed from result."); } else { List<FriendInfo> list = new List<FriendInfo>(this.friendListRequested.Length); for (int j = 0; j < this.friendListRequested.Length; j++) { FriendInfo info = new FriendInfo { Name = this.friendListRequested[j], Room = strArray3[j], IsOnline = flagArray[j] }; list.Insert(j, info); } PhotonNetwork.Friends = list; } this.friendListRequested = null; this.isFetchingFriends = false; this.friendListTimestamp = Environment.TickCount; if (this.friendListTimestamp == 0) { this.friendListTimestamp = 1; } SendMonoMessage(PhotonNetworkingMessage.OnUpdatedFriendList, new object[0]); goto Label_0955; } case 0xe1: if (operationResponse.ReturnCode == 0) { string str3 = (string) operationResponse[0xff]; this.mRoomToGetInto.name = str3; this.mGameserver = (string) operationResponse[230]; this.DisconnectToReconnect(); } else { if (operationResponse.ReturnCode != 0x7ff8) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.LogWarning(string.Format("JoinRandom failed: {0}.", operationResponse.ToStringFull())); } } else if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) { Debug.Log("JoinRandom failed: No open game. Calling: OnPhotonRandomJoinFailed() and staying on master server."); } SendMonoMessage(PhotonNetworkingMessage.OnPhotonRandomJoinFailed, new object[0]); } goto Label_0955; case 0xe2: if (this.server == ServerConnection.GameServer) { this.GameEnteredOnGameServer(operationResponse); } else if (operationResponse.ReturnCode == 0) { this.mGameserver = (string) operationResponse[230]; this.DisconnectToReconnect(); } else { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log(string.Format("JoinRoom failed (room maybe closed by now). Client stays on masterserver: {0}. State: {1}", operationResponse.ToStringFull(), this.State)); } SendMonoMessage(PhotonNetworkingMessage.OnPhotonJoinRoomFailed, new object[0]); } goto Label_0955; case 0xe3: if (this.server != ServerConnection.GameServer) { if (operationResponse.ReturnCode != 0) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.LogWarning(string.Format("CreateRoom failed, client stays on masterserver: {0}.", operationResponse.ToStringFull())); } SendMonoMessage(PhotonNetworkingMessage.OnPhotonCreateRoomFailed, new object[0]); } else { string str2 = (string) operationResponse[0xff]; if (!string.IsNullOrEmpty(str2)) { this.mRoomToGetInto.name = str2; } this.mGameserver = (string) operationResponse[230]; this.DisconnectToReconnect(); } } else { this.GameEnteredOnGameServer(operationResponse); } goto Label_0955; case 0xe4: this.State = PeerStates.Authenticated; this.LeftLobbyCleanup(); goto Label_0955; case 0xe5: this.State = PeerStates.JoinedLobby; this.insideLobby = true; SendMonoMessage(PhotonNetworkingMessage.OnJoinedLobby, new object[0]); goto Label_0955; case 230: if (operationResponse.ReturnCode == 0) { if (this.server == ServerConnection.NameServer) { this.MasterServerAddress = operationResponse[230] as string; this.DisconnectToReconnect(); } else if (this.server == ServerConnection.MasterServer) { if (PhotonNetwork.autoJoinLobby) { this.State = PeerStates.Authenticated; this.OpJoinLobby(this.lobby); } else { this.State = PeerStates.ConnectedToMaster; SendMonoMessage(PhotonNetworkingMessage.OnConnectedToMaster, new object[0]); } } else if (this.server == ServerConnection.GameServer) { this.State = PeerStates.Joining; if (((this.mLastJoinType == JoinType.JoinGame) || (this.mLastJoinType == JoinType.JoinRandomGame)) || (this.mLastJoinType == JoinType.JoinOrCreateOnDemand)) { this.OpJoinRoom(this.mRoomToGetInto.name, this.mRoomOptionsForCreate, this.mRoomToEnterLobby, this.mLastJoinType == JoinType.JoinOrCreateOnDemand); } else if (this.mLastJoinType == JoinType.CreateGame) { this.OpCreateGame(this.mRoomToGetInto.name, this.mRoomOptionsForCreate, this.mRoomToEnterLobby); } } goto Label_0955; } if (operationResponse.ReturnCode != -2) { if (operationResponse.ReturnCode == 0x7fff) { Debug.LogError(string.Format("The appId this client sent is unknown on the server (Cloud). Check settings. If using the Cloud, check account.", new object[0])); object[] objArray3 = new object[] { DisconnectCause.InvalidAuthentication }; SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, objArray3); } else if (operationResponse.ReturnCode == 0x7ff3) { Debug.LogError(string.Format("Custom Authentication failed (either due to user-input or configuration or AuthParameter string format). Calling: OnCustomAuthenticationFailed()", new object[0])); object[] objArray4 = new object[] { operationResponse.DebugMessage }; SendMonoMessage(PhotonNetworkingMessage.OnCustomAuthenticationFailed, objArray4); } else { Debug.LogError(string.Format("Authentication failed: '{0}' Code: {1}", operationResponse.DebugMessage, operationResponse.ReturnCode)); } } else { Debug.LogError(string.Format("If you host Photon yourself, make sure to start the 'Instance LoadBalancing' " + base.ServerAddress, new object[0])); } break; default: switch (operationCode) { case 0xfb: { ExitGames.Client.Photon.Hashtable pActorProperties = (ExitGames.Client.Photon.Hashtable) operationResponse[0xf9]; ExitGames.Client.Photon.Hashtable gameProperties = (ExitGames.Client.Photon.Hashtable) operationResponse[0xf8]; this.ReadoutProperties(gameProperties, pActorProperties, 0); goto Label_0955; } case 0xfc: case 0xfd: goto Label_0955; case 0xfe: this.DisconnectToReconnect(); goto Label_0955; default: Debug.LogWarning(string.Format("OperationResponse unhandled: {0}", operationResponse.ToString())); goto Label_0955; } } this.State = PeerStates.Disconnecting; this.Disconnect(); if (operationResponse.ReturnCode == 0x7ff5) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.LogWarning(string.Format("Currently, the limit of users is reached for this title. Try again later. Disconnecting", new object[0])); } SendMonoMessage(PhotonNetworkingMessage.OnPhotonMaxCccuReached, new object[0]); object[] objArray5 = new object[] { DisconnectCause.MaxCcuReached }; SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, objArray5); } else if (operationResponse.ReturnCode == 0x7ff4) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.LogError(string.Format("The used master server address is not available with the subscription currently used. Got to Photon Cloud Dashboard or change URL. Disconnecting.", new object[0])); } object[] objArray6 = new object[] { DisconnectCause.InvalidRegion }; SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, objArray6); } else if (operationResponse.ReturnCode == 0x7ff1) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.LogError(string.Format("The authentication ticket expired. You need to connect (and authenticate) again. Disconnecting.", new object[0])); } object[] objArray7 = new object[] { DisconnectCause.AuthenticationTicketExpired }; SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, objArray7); } Label_0955: this.externalListener.OnOperationResponse(operationResponse); } private void OnSerializeRead(ExitGames.Client.Photon.Hashtable data, PhotonPlayer sender, int networkTime, short correctPrefix) { int viewID = (int) data[(byte) 0]; PhotonView photonView = this.GetPhotonView(viewID); if (photonView == null) { Debug.LogWarning(string.Concat(new object[] { "Received OnSerialization for view ID ", viewID, ". We have no such PhotonView! Ignored this if you're leaving a room. State: ", this.State })); } else if ((photonView.prefix > 0) && (correctPrefix != photonView.prefix)) { Debug.LogError(string.Concat(new object[] { "Received OnSerialization for view ID ", viewID, " with prefix ", correctPrefix, ". Our prefix is ", photonView.prefix })); } else if ((photonView.group == 0) || this.allowedReceivingGroups.Contains(photonView.group)) { if (photonView.synchronization == ViewSynchronization.ReliableDeltaCompressed) { if (!this.DeltaCompressionRead(photonView, data)) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log(string.Concat(new object[] { "Skipping packet for ", photonView.name, " [", photonView.viewID, "] as we haven't received a full packet for delta compression yet. This is OK if it happens for the first few frames after joining a game." })); } return; } photonView.lastOnSerializeDataReceived = data[(byte) 1] as object[]; } if (photonView.observed is MonoBehaviour) { object[] incomingData = data[(byte) 1] as object[]; PhotonStream pStream = new PhotonStream(false, incomingData); PhotonMessageInfo info = new PhotonMessageInfo(sender, networkTime, photonView); photonView.ExecuteOnSerialize(pStream, info); } else if (photonView.observed is Transform) { object[] objArray2 = data[(byte) 1] as object[]; Transform observed = (Transform) photonView.observed; if ((objArray2.Length >= 1) && (objArray2[0] != null)) { observed.localPosition = (Vector3) objArray2[0]; } if ((objArray2.Length >= 2) && (objArray2[1] != null)) { observed.localRotation = (Quaternion) objArray2[1]; } if ((objArray2.Length >= 3) && (objArray2[2] != null)) { observed.localScale = (Vector3) objArray2[2]; } } else if (photonView.observed is Rigidbody) { object[] objArray3 = data[(byte) 1] as object[]; Rigidbody rigidbody = (Rigidbody) photonView.observed; if ((objArray3.Length >= 1) && (objArray3[0] != null)) { rigidbody.velocity = (Vector3) objArray3[0]; } if ((objArray3.Length >= 2) && (objArray3[1] != null)) { rigidbody.angularVelocity = (Vector3) objArray3[1]; } } else { Debug.LogError("Type of observed is unknown when receiving."); } } } private ExitGames.Client.Photon.Hashtable OnSerializeWrite(PhotonView view) { List<object> list = new List<object>(); if (view.observed is MonoBehaviour) { PhotonStream pStream = new PhotonStream(true, null); PhotonMessageInfo info = new PhotonMessageInfo(this.mLocalActor, base.ServerTimeInMilliSeconds, view); view.ExecuteOnSerialize(pStream, info); if (pStream.Count == 0) { return null; } list = pStream.data; } else if (view.observed is Transform) { Transform observed = (Transform) view.observed; if (((view.onSerializeTransformOption == OnSerializeTransform.OnlyPosition) || (view.onSerializeTransformOption == OnSerializeTransform.PositionAndRotation)) || (view.onSerializeTransformOption == OnSerializeTransform.All)) { list.Add(observed.localPosition); } else { list.Add(null); } if (((view.onSerializeTransformOption == OnSerializeTransform.OnlyRotation) || (view.onSerializeTransformOption == OnSerializeTransform.PositionAndRotation)) || (view.onSerializeTransformOption == OnSerializeTransform.All)) { list.Add(observed.localRotation); } else { list.Add(null); } if ((view.onSerializeTransformOption == OnSerializeTransform.OnlyScale) || (view.onSerializeTransformOption == OnSerializeTransform.All)) { list.Add(observed.localScale); } } else if (view.observed is Rigidbody) { Rigidbody rigidbody = (Rigidbody) view.observed; if (view.onSerializeRigidBodyOption != OnSerializeRigidBody.OnlyAngularVelocity) { list.Add(rigidbody.velocity); } else { list.Add(null); } if (view.onSerializeRigidBodyOption != OnSerializeRigidBody.OnlyVelocity) { list.Add(rigidbody.angularVelocity); } } else { Debug.LogError("Observed type is not serializable: " + view.observed.GetType()); return null; } object[] lastData = list.ToArray(); if (view.synchronization == ViewSynchronization.UnreliableOnChange) { if (this.AlmostEquals(lastData, view.lastOnSerializeDataSent)) { if (view.mixedModeIsReliable) { return null; } view.mixedModeIsReliable = true; view.lastOnSerializeDataSent = lastData; } else { view.mixedModeIsReliable = false; view.lastOnSerializeDataSent = lastData; } } ExitGames.Client.Photon.Hashtable data = new ExitGames.Client.Photon.Hashtable(); data[(byte) 0] = view.viewID; data[(byte) 1] = lastData; if (view.synchronization == ViewSynchronization.ReliableDeltaCompressed) { bool flag = this.DeltaCompressionWrite(view, data); view.lastOnSerializeDataSent = lastData; if (!flag) { return null; } } return data; } public void OnStatusChanged(StatusCode statusCode) { DisconnectCause cause; if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log(string.Format("OnStatusChanged: {0}", statusCode.ToString())); } switch (statusCode) { case StatusCode.SecurityExceptionOnConnect: case StatusCode.ExceptionOnConnect: { this.State = PeerStates.PeerCreated; if (this.CustomAuthenticationValues != null) { this.CustomAuthenticationValues.Secret = null; } cause = (DisconnectCause) statusCode; object[] parameters = new object[] { cause }; SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, parameters); goto Label_055E; } case StatusCode.Connect: if (this.State == PeerStates.ConnectingToNameServer) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) { Debug.Log("Connected to NameServer."); } this.server = ServerConnection.NameServer; if (this.CustomAuthenticationValues != null) { this.CustomAuthenticationValues.Secret = null; } } if (this.State == PeerStates.ConnectingToGameserver) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) { Debug.Log("Connected to gameserver."); } this.server = ServerConnection.GameServer; this.State = PeerStates.ConnectedToGameserver; } if (this.State == PeerStates.ConnectingToMasterserver) { if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) { Debug.Log("Connected to masterserver."); } this.server = ServerConnection.MasterServer; this.State = PeerStates.ConnectedToMaster; if (this.IsInitialConnect) { this.IsInitialConnect = false; SendMonoMessage(PhotonNetworkingMessage.OnConnectedToPhoton, new object[0]); } } base.EstablishEncryption(); if (this.IsAuthorizeSecretAvailable) { this.didAuthenticate = this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString()); if (this.didAuthenticate) { this.State = PeerStates.Authenticating; } } goto Label_055E; case StatusCode.Disconnect: this.didAuthenticate = false; this.isFetchingFriends = false; if (this.server == ServerConnection.GameServer) { this.LeftRoomCleanup(); } if (this.server == ServerConnection.MasterServer) { this.LeftLobbyCleanup(); } if (this.State == PeerStates.DisconnectingFromMasterserver) { if (this.Connect(this.mGameserver, ServerConnection.GameServer)) { this.State = PeerStates.ConnectingToGameserver; } } else if ((this.State == PeerStates.DisconnectingFromGameserver) || (this.State == PeerStates.DisconnectingFromNameServer)) { if (this.Connect(this.MasterServerAddress, ServerConnection.MasterServer)) { this.State = PeerStates.ConnectingToMasterserver; } } else { if (this.CustomAuthenticationValues != null) { this.CustomAuthenticationValues.Secret = null; } this.State = PeerStates.PeerCreated; SendMonoMessage(PhotonNetworkingMessage.OnDisconnectedFromPhoton, new object[0]); } goto Label_055E; case StatusCode.Exception: { if (!this.IsInitialConnect) { this.State = PeerStates.PeerCreated; cause = (DisconnectCause) statusCode; object[] objArray3 = new object[] { cause }; SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, objArray3); break; } Debug.LogError("Exception while connecting to: " + base.ServerAddress + ". Check if the server is available."); if ((base.ServerAddress == null) || base.ServerAddress.StartsWith("127.0.0.1")) { Debug.LogWarning("The server address is 127.0.0.1 (localhost): Make sure the server is running on this machine. Android and iOS emulators have their own localhost."); if (base.ServerAddress == this.mGameserver) { Debug.LogWarning("This might be a misconfiguration in the game server config. You need to edit it to a (public) address."); } } this.State = PeerStates.PeerCreated; cause = (DisconnectCause) statusCode; object[] objArray2 = new object[] { cause }; SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, objArray2); break; } case StatusCode.QueueOutgoingReliableWarning: case StatusCode.QueueOutgoingUnreliableWarning: case StatusCode.QueueOutgoingAcksWarning: case StatusCode.QueueSentWarning: case StatusCode.SendError: goto Label_055E; case StatusCode.QueueIncomingReliableWarning: case StatusCode.QueueIncomingUnreliableWarning: Debug.Log(statusCode + ". This client buffers many incoming messages. This is OK temporarily. With lots of these warnings, check if you send too much or execute messages too slow. " + (!PhotonNetwork.isMessageQueueRunning ? "Your isMessageQueueRunning is false. This can cause the issue temporarily." : string.Empty)); goto Label_055E; case StatusCode.ExceptionOnReceive: case StatusCode.TimeoutDisconnect: case StatusCode.DisconnectByServer: case StatusCode.DisconnectByServerUserLimit: case StatusCode.DisconnectByServerLogic: if (!this.IsInitialConnect) { cause = (DisconnectCause) statusCode; object[] objArray6 = new object[] { cause }; SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, objArray6); } else { Debug.LogWarning(string.Concat(new object[] { statusCode, " while connecting to: ", base.ServerAddress, ". Check if the server is available." })); cause = (DisconnectCause) statusCode; object[] objArray5 = new object[] { cause }; SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, objArray5); } if (this.CustomAuthenticationValues != null) { this.CustomAuthenticationValues.Secret = null; } this.Disconnect(); goto Label_055E; case StatusCode.EncryptionEstablished: if (this.server == ServerConnection.NameServer) { this.State = PeerStates.ConnectedToNameServer; if (!this.didAuthenticate && (this.CloudRegion == CloudRegionCode.none)) { this.OpGetRegions(this.mAppId); } } if (!this.didAuthenticate && (!this.IsUsingNameServer || (this.CloudRegion != CloudRegionCode.none))) { this.didAuthenticate = this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString()); if (this.didAuthenticate) { this.State = PeerStates.Authenticating; } } goto Label_055E; case StatusCode.EncryptionFailedToEstablish: Debug.LogError("Encryption wasn't established: " + statusCode + ". Going to authenticate anyways."); this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString()); goto Label_055E; default: Debug.LogError("Received unknown status code: " + statusCode); goto Label_055E; } this.Disconnect(); Label_055E: this.externalListener.OnStatusChanged(statusCode); } public void OpCleanRpcBuffer(PhotonView view) { ExitGames.Client.Photon.Hashtable customEventContent = new ExitGames.Client.Photon.Hashtable(); customEventContent[(byte) 0] = view.viewID; RaiseEventOptions raiseEventOptions = new RaiseEventOptions { CachingOption = EventCaching.RemoveFromRoomCache }; this.OpRaiseEvent(200, customEventContent, true, raiseEventOptions); } public void OpCleanRpcBuffer(int actorNumber) { RaiseEventOptions options = new RaiseEventOptions { CachingOption = EventCaching.RemoveFromRoomCache }; options.TargetActors = new int[] { actorNumber }; RaiseEventOptions raiseEventOptions = options; this.OpRaiseEvent(200, null, true, raiseEventOptions); } public bool OpCreateGame(string roomName, RoomOptions roomOptions, TypedLobby typedLobby) { bool onGameServer = this.server == ServerConnection.GameServer; if (!onGameServer) { this.mRoomOptionsForCreate = roomOptions; this.mRoomToGetInto = new Room(roomName, roomOptions); if (typedLobby == null) { } this.mRoomToEnterLobby = !this.insideLobby ? null : this.lobby; } this.mLastJoinType = JoinType.CreateGame; return base.OpCreateRoom(roomName, roomOptions, this.mRoomToEnterLobby, this.GetLocalActorProperties(), onGameServer); } public override bool OpFindFriends(string[] friendsToFind) { if (this.isFetchingFriends) { return false; } this.friendListRequested = friendsToFind; this.isFetchingFriends = true; return base.OpFindFriends(friendsToFind); } public override bool OpJoinRandomRoom(ExitGames.Client.Photon.Hashtable expectedCustomRoomProperties, byte expectedMaxPlayers, ExitGames.Client.Photon.Hashtable playerProperties, MatchmakingMode matchingType, TypedLobby typedLobby, string sqlLobbyFilter) { this.mRoomToGetInto = new Room(null, null); this.mRoomToEnterLobby = null; this.mLastJoinType = JoinType.JoinRandomGame; return base.OpJoinRandomRoom(expectedCustomRoomProperties, expectedMaxPlayers, playerProperties, matchingType, typedLobby, sqlLobbyFilter); } public bool OpJoinRoom(string roomName, RoomOptions roomOptions, TypedLobby typedLobby, bool createIfNotExists) { bool onGameServer = this.server == ServerConnection.GameServer; if (!onGameServer) { this.mRoomOptionsForCreate = roomOptions; this.mRoomToGetInto = new Room(roomName, roomOptions); this.mRoomToEnterLobby = null; if (createIfNotExists) { if (typedLobby == null) { } this.mRoomToEnterLobby = !this.insideLobby ? null : this.lobby; } } this.mLastJoinType = !createIfNotExists ? JoinType.JoinGame : JoinType.JoinOrCreateOnDemand; return base.OpJoinRoom(roomName, roomOptions, this.mRoomToEnterLobby, createIfNotExists, this.GetLocalActorProperties(), onGameServer); } public virtual bool OpLeave() { if (this.State != PeerStates.Joined) { Debug.LogWarning("Not sending leave operation. State is not 'Joined': " + this.State); return false; } return this.OpCustom(0xfe, null, true, 0); } public override bool OpRaiseEvent(byte eventCode, object customEventContent, bool sendReliable, RaiseEventOptions raiseEventOptions) { if (PhotonNetwork.offlineMode) { return false; } return base.OpRaiseEvent(eventCode, customEventContent, sendReliable, raiseEventOptions); } public void OpRemoveCompleteCache() { RaiseEventOptions raiseEventOptions = new RaiseEventOptions { CachingOption = EventCaching.RemoveFromRoomCache, Receivers = ReceiverGroup.MasterClient }; this.OpRaiseEvent(0, null, true, raiseEventOptions); } public void OpRemoveCompleteCacheOfPlayer(int actorNumber) { RaiseEventOptions options = new RaiseEventOptions { CachingOption = EventCaching.RemoveFromRoomCache }; options.TargetActors = new int[] { actorNumber }; RaiseEventOptions raiseEventOptions = options; this.OpRaiseEvent(0, null, true, raiseEventOptions); } private void OpRemoveFromServerInstantiationsOfPlayer(int actorNr) { RaiseEventOptions options = new RaiseEventOptions { CachingOption = EventCaching.RemoveFromRoomCache }; options.TargetActors = new int[] { actorNr }; RaiseEventOptions raiseEventOptions = options; this.OpRaiseEvent(0xca, null, true, raiseEventOptions); } private void ReadoutProperties(ExitGames.Client.Photon.Hashtable gameProperties, ExitGames.Client.Photon.Hashtable pActorProperties, int targetActorNr) { if ((this.mCurrentGame != null) && (gameProperties != null)) { this.mCurrentGame.CacheProperties(gameProperties); object[] parameters = new object[] { gameProperties }; SendMonoMessage(PhotonNetworkingMessage.OnPhotonCustomRoomPropertiesChanged, parameters); if (PhotonNetwork.automaticallySyncScene) { this.LoadLevelIfSynced(); } } if ((pActorProperties != null) && (pActorProperties.Count > 0)) { if (targetActorNr > 0) { PhotonPlayer playerWithID = this.GetPlayerWithID(targetActorNr); if (playerWithID != null) { ExitGames.Client.Photon.Hashtable actorPropertiesForActorNr = this.GetActorPropertiesForActorNr(pActorProperties, targetActorNr); playerWithID.InternalCacheProperties(actorPropertiesForActorNr); object[] objArray2 = new object[] { playerWithID, actorPropertiesForActorNr }; SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerPropertiesChanged, objArray2); } } else { foreach (object obj2 in pActorProperties.Keys) { int number = (int) obj2; ExitGames.Client.Photon.Hashtable properties = (ExitGames.Client.Photon.Hashtable) pActorProperties[obj2]; string name = (string) properties[(byte) 0xff]; PhotonPlayer player = this.GetPlayerWithID(number); if (player == null) { player = new PhotonPlayer(false, number, name); this.AddNewPlayer(number, player); } player.InternalCacheProperties(properties); object[] objArray3 = new object[] { player, properties }; SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerPropertiesChanged, objArray3); } } } } private void RebuildPlayerListCopies() { this.mPlayerListCopy = new PhotonPlayer[this.mActors.Count]; this.mActors.Values.CopyTo(this.mPlayerListCopy, 0); List<PhotonPlayer> list = new List<PhotonPlayer>(); foreach (PhotonPlayer player in this.mPlayerListCopy) { if (!player.isLocal) { list.Add(player); } } this.mOtherPlayerListCopy = list.ToArray(); } public void RegisterPhotonView(PhotonView netView) { if (!Application.isPlaying) { this.photonViewList = new Dictionary<int, PhotonView>(); } else if (netView.subId != 0) { if (this.photonViewList.ContainsKey(netView.viewID)) { if (netView != this.photonViewList[netView.viewID]) { Debug.LogError(string.Format("PhotonView ID duplicate found: {0}. New: {1} old: {2}. Maybe one wasn't destroyed on scene load?! Check for 'DontDestroyOnLoad'. Destroying old entry, adding new.", netView.viewID, netView, this.photonViewList[netView.viewID])); } this.RemoveInstantiatedGO(this.photonViewList[netView.viewID].gameObject, true); } this.photonViewList.Add(netView.viewID, netView); if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) { Debug.Log("Registered PhotonView: " + netView.viewID); } } } public void RemoveAllInstantiatedObjects() { GameObject[] array = new GameObject[this.instantiatedObjects.Count]; this.instantiatedObjects.Values.CopyTo(array, 0); for (int i = 0; i < array.Length; i++) { GameObject go = array[i]; if (go != null) { this.RemoveInstantiatedGO(go, false); } } if (this.instantiatedObjects.Count > 0) { Debug.LogError("RemoveAllInstantiatedObjects() this.instantiatedObjects.Count should be 0 by now."); } this.instantiatedObjects = new Dictionary<int, GameObject>(); } private void RemoveCacheOfLeftPlayers() { Dictionary<byte, object> customOpParameters = new Dictionary<byte, object>(); customOpParameters[0xf4] = (byte) 0; customOpParameters[0xf7] = (byte) 7; this.OpCustom(0xfd, customOpParameters, true, 0); } public void RemoveInstantiatedGO(GameObject go, bool localOnly) { if (go == null) { Debug.LogError("Failed to 'network-remove' GameObject because it's null."); } else { PhotonView[] componentsInChildren = go.GetComponentsInChildren<PhotonView>(); if ((componentsInChildren == null) || (componentsInChildren.Length <= 0)) { Debug.LogError("Failed to 'network-remove' GameObject because has no PhotonView components: " + go); } else { PhotonView view = componentsInChildren[0]; int ownerActorNr = view.OwnerActorNr; int instantiationId = view.instantiationId; if (!localOnly) { if (!view.isMine && (!this.mLocalActor.isMasterClient || this.mActors.ContainsKey(ownerActorNr))) { Debug.LogError("Failed to 'network-remove' GameObject. Client is neither owner nor masterClient taking over for owner who left: " + view); return; } if (instantiationId < 1) { Debug.LogError("Failed to 'network-remove' GameObject because it is missing a valid InstantiationId on view: " + view + ". Not Destroying GameObject or PhotonViews!"); return; } } if (!localOnly) { this.ServerCleanInstantiateAndDestroy(instantiationId, ownerActorNr); } this.instantiatedObjects.Remove(instantiationId); for (int i = componentsInChildren.Length - 1; i >= 0; i--) { PhotonView view2 = componentsInChildren[i]; if (view2 != null) { if (view2.instantiationId >= 1) { this.LocalCleanPhotonView(view2); } if (!localOnly) { this.OpCleanRpcBuffer(view2); } } } if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) { Debug.Log("Network destroy Instantiated GO: " + go.name); } UnityEngine.Object.Destroy(go); } } } private void RemoveInstantiationData(int instantiationId) { this.tempInstantiationData.Remove(instantiationId); } private void RemovePlayer(int ID, PhotonPlayer player) { this.mActors.Remove(ID); if (!player.isLocal) { this.RebuildPlayerListCopies(); } } public void RemoveRPCsInGroup(int group) { foreach (KeyValuePair<int, PhotonView> pair in this.photonViewList) { PhotonView view = pair.Value; if (view.group == group) { this.CleanRpcBufferIfMine(view); } } } private void ResetPhotonViewsOnSerialize() { foreach (PhotonView view in this.photonViewList.Values) { view.lastOnSerializeDataSent = null; } } private static int ReturnLowestPlayerId(PhotonPlayer[] players, int playerIdToIgnore) { if ((players == null) || (players.Length == 0)) { return -1; } int iD = 0x7fffffff; for (int i = 0; i < players.Length; i++) { PhotonPlayer player = players[i]; if ((player.ID != playerIdToIgnore) && (player.ID < iD)) { iD = player.ID; } } return iD; } internal void RPC(PhotonView view, string methodName, PhotonPlayer player, params object[] parameters) { if (!this.blockSendingGroups.Contains(view.group)) { if (view.viewID < 1) { Debug.LogError(string.Concat(new object[] { "Illegal view ID:", view.viewID, " method: ", methodName, " GO:", view.gameObject.name })); } if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) { Debug.Log(string.Concat(new object[] { "Sending RPC \"", methodName, "\" to player[", player, "]" })); } ExitGames.Client.Photon.Hashtable rpcData = new ExitGames.Client.Photon.Hashtable(); rpcData[(byte) 0] = view.viewID; if (view.prefix > 0) { rpcData[(byte) 1] = (short) view.prefix; } rpcData[(byte) 2] = base.ServerTimeInMilliSeconds; int num = 0; if (this.rpcShortcuts.TryGetValue(methodName, out num)) { rpcData[(byte) 5] = (byte) num; } else { rpcData[(byte) 3] = methodName; } if ((parameters != null) && (parameters.Length > 0)) { rpcData[(byte) 4] = parameters; } if (this.mLocalActor == player) { this.ExecuteRPC(rpcData, player); } else { RaiseEventOptions options = new RaiseEventOptions(); options.TargetActors = new int[] { player.ID }; RaiseEventOptions raiseEventOptions = options; this.OpRaiseEvent(200, rpcData, true, raiseEventOptions); } } } internal void RPC(PhotonView view, string methodName, PhotonTargets target, params object[] parameters) { if (!this.blockSendingGroups.Contains(view.group)) { RaiseEventOptions options; if (view.viewID < 1) { Debug.LogError(string.Concat(new object[] { "Illegal view ID:", view.viewID, " method: ", methodName, " GO:", view.gameObject.name })); } if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) { Debug.Log(string.Concat(new object[] { "Sending RPC \"", methodName, "\" to ", target })); } ExitGames.Client.Photon.Hashtable customEventContent = new ExitGames.Client.Photon.Hashtable(); customEventContent[(byte) 0] = view.viewID; if (view.prefix > 0) { customEventContent[(byte) 1] = (short) view.prefix; } customEventContent[(byte) 2] = base.ServerTimeInMilliSeconds; int num = 0; if (this.rpcShortcuts.TryGetValue(methodName, out num)) { customEventContent[(byte) 5] = (byte) num; } else { customEventContent[(byte) 3] = methodName; } if ((parameters != null) && (parameters.Length > 0)) { customEventContent[(byte) 4] = parameters; } if (target == PhotonTargets.All) { options = new RaiseEventOptions { InterestGroup = (byte) view.group }; RaiseEventOptions raiseEventOptions = options; this.OpRaiseEvent(200, customEventContent, true, raiseEventOptions); this.ExecuteRPC(customEventContent, this.mLocalActor); } else if (target == PhotonTargets.Others) { options = new RaiseEventOptions { InterestGroup = (byte) view.group }; RaiseEventOptions options3 = options; this.OpRaiseEvent(200, customEventContent, true, options3); } else if (target == PhotonTargets.AllBuffered) { options = new RaiseEventOptions { CachingOption = EventCaching.AddToRoomCache }; RaiseEventOptions options4 = options; this.OpRaiseEvent(200, customEventContent, true, options4); this.ExecuteRPC(customEventContent, this.mLocalActor); } else if (target == PhotonTargets.OthersBuffered) { options = new RaiseEventOptions { CachingOption = EventCaching.AddToRoomCache }; RaiseEventOptions options5 = options; this.OpRaiseEvent(200, customEventContent, true, options5); } else if (target == PhotonTargets.MasterClient) { if (this.mMasterClient == this.mLocalActor) { this.ExecuteRPC(customEventContent, this.mLocalActor); } else { options = new RaiseEventOptions { Receivers = ReceiverGroup.MasterClient }; RaiseEventOptions options6 = options; this.OpRaiseEvent(200, customEventContent, true, options6); } } else if (target == PhotonTargets.AllViaServer) { options = new RaiseEventOptions { InterestGroup = (byte) view.group, Receivers = ReceiverGroup.All }; RaiseEventOptions options7 = options; this.OpRaiseEvent(200, customEventContent, true, options7); } else if (target == PhotonTargets.AllBufferedViaServer) { options = new RaiseEventOptions { InterestGroup = (byte) view.group, Receivers = ReceiverGroup.All, CachingOption = EventCaching.AddToRoomCache }; RaiseEventOptions options8 = options; this.OpRaiseEvent(200, customEventContent, true, options8); } else { Debug.LogError("Unsupported target enum: " + target); } } } public void RunViewUpdate() { if ((PhotonNetwork.connected && !PhotonNetwork.offlineMode) && ((this.mActors != null) && (this.mActors.Count > 1))) { Dictionary<int, ExitGames.Client.Photon.Hashtable> dictionary = new Dictionary<int, ExitGames.Client.Photon.Hashtable>(); Dictionary<int, ExitGames.Client.Photon.Hashtable> dictionary2 = new Dictionary<int, ExitGames.Client.Photon.Hashtable>(); foreach (KeyValuePair<int, PhotonView> pair in this.photonViewList) { PhotonView view = pair.Value; if (((((view.observed != null) && (view.synchronization != ViewSynchronization.Off)) && ((view.ownerId == this.mLocalActor.ID) || (view.isSceneView && (this.mMasterClient == this.mLocalActor)))) && view.gameObject.activeInHierarchy) && !this.blockSendingGroups.Contains(view.group)) { ExitGames.Client.Photon.Hashtable hashtable = this.OnSerializeWrite(view); if (hashtable != null) { if ((view.synchronization == ViewSynchronization.ReliableDeltaCompressed) || view.mixedModeIsReliable) { if (hashtable.ContainsKey((byte) 1) || hashtable.ContainsKey((byte) 2)) { if (!dictionary.ContainsKey(view.group)) { dictionary[view.group] = new ExitGames.Client.Photon.Hashtable(); dictionary[view.group][(byte) 0] = base.ServerTimeInMilliSeconds; if (this.currentLevelPrefix >= 0) { dictionary[view.group][(byte) 1] = this.currentLevelPrefix; } } ExitGames.Client.Photon.Hashtable hashtable2 = dictionary[view.group]; hashtable2.Add((short) hashtable2.Count, hashtable); } } else { if (!dictionary2.ContainsKey(view.group)) { dictionary2[view.group] = new ExitGames.Client.Photon.Hashtable(); dictionary2[view.group][(byte) 0] = base.ServerTimeInMilliSeconds; if (this.currentLevelPrefix >= 0) { dictionary2[view.group][(byte) 1] = this.currentLevelPrefix; } } ExitGames.Client.Photon.Hashtable hashtable3 = dictionary2[view.group]; hashtable3.Add((short) hashtable3.Count, hashtable); } } } } RaiseEventOptions raiseEventOptions = new RaiseEventOptions(); foreach (KeyValuePair<int, ExitGames.Client.Photon.Hashtable> pair2 in dictionary) { raiseEventOptions.InterestGroup = (byte) pair2.Key; this.OpRaiseEvent(0xce, pair2.Value, true, raiseEventOptions); } foreach (KeyValuePair<int, ExitGames.Client.Photon.Hashtable> pair3 in dictionary2) { raiseEventOptions.InterestGroup = (byte) pair3.Key; this.OpRaiseEvent(0xc9, pair3.Value, false, raiseEventOptions); } } } private void SendDestroyOfAll() { ExitGames.Client.Photon.Hashtable customEventContent = new ExitGames.Client.Photon.Hashtable(); customEventContent[(byte) 0] = -1; this.OpRaiseEvent(0xcf, customEventContent, true, null); } private void SendDestroyOfPlayer(int actorNr) { ExitGames.Client.Photon.Hashtable customEventContent = new ExitGames.Client.Photon.Hashtable(); customEventContent[(byte) 0] = actorNr; this.OpRaiseEvent(0xcf, customEventContent, true, null); } internal ExitGames.Client.Photon.Hashtable SendInstantiate(string prefabName, Vector3 position, Quaternion rotation, int group, int[] viewIDs, object[] data, bool isGlobalObject) { int num = viewIDs[0]; ExitGames.Client.Photon.Hashtable customEventContent = new ExitGames.Client.Photon.Hashtable(); customEventContent[(byte) 0] = prefabName; if (position != Vector3.zero) { customEventContent[(byte) 1] = position; } if (rotation != Quaternion.identity) { customEventContent[(byte) 2] = rotation; } if (group != 0) { customEventContent[(byte) 3] = group; } if (viewIDs.Length > 1) { customEventContent[(byte) 4] = viewIDs; } if (data != null) { customEventContent[(byte) 5] = data; } if (this.currentLevelPrefix > 0) { customEventContent[(byte) 8] = this.currentLevelPrefix; } customEventContent[(byte) 6] = base.ServerTimeInMilliSeconds; customEventContent[(byte) 7] = num; RaiseEventOptions raiseEventOptions = new RaiseEventOptions { CachingOption = !isGlobalObject ? EventCaching.AddToRoomCache : EventCaching.AddToRoomCacheGlobal }; this.OpRaiseEvent(0xca, customEventContent, true, raiseEventOptions); return customEventContent; } public static void SendMonoMessage(PhotonNetworkingMessage methodString, params object[] parameters) { HashSet<GameObject> sendMonoMessageTargets; if (PhotonNetwork.SendMonoMessageTargets != null) { sendMonoMessageTargets = PhotonNetwork.SendMonoMessageTargets; } else { sendMonoMessageTargets = new HashSet<GameObject>(); Component[] componentArray = (Component[]) UnityEngine.Object.FindObjectsOfType(typeof(MonoBehaviour)); for (int i = 0; i < componentArray.Length; i++) { sendMonoMessageTargets.Add(componentArray[i].gameObject); } } string methodName = methodString.ToString(); foreach (GameObject obj2 in sendMonoMessageTargets) { if ((parameters != null) && (parameters.Length == 1)) { obj2.SendMessage(methodName, parameters[0], SendMessageOptions.DontRequireReceiver); } else { obj2.SendMessage(methodName, parameters, SendMessageOptions.DontRequireReceiver); } } } private void SendPlayerName() { if (this.State == PeerStates.Joining) { this.mPlayernameHasToBeUpdated = true; } else if (this.mLocalActor != null) { this.mLocalActor.name = this.PlayerName; ExitGames.Client.Photon.Hashtable actorProperties = new ExitGames.Client.Photon.Hashtable(); actorProperties[(byte) 0xff] = this.PlayerName; if (this.mLocalActor.ID > 0) { base.OpSetPropertiesOfActor(this.mLocalActor.ID, actorProperties, true, 0); this.mPlayernameHasToBeUpdated = false; } } } private void ServerCleanInstantiateAndDestroy(int instantiateId, int actorNr) { ExitGames.Client.Photon.Hashtable customEventContent = new ExitGames.Client.Photon.Hashtable(); customEventContent[(byte) 7] = instantiateId; RaiseEventOptions options = new RaiseEventOptions { CachingOption = EventCaching.RemoveFromRoomCache }; options.TargetActors = new int[] { actorNr }; RaiseEventOptions raiseEventOptions = options; this.OpRaiseEvent(0xca, customEventContent, true, raiseEventOptions); ExitGames.Client.Photon.Hashtable hashtable2 = new ExitGames.Client.Photon.Hashtable(); hashtable2[(byte) 0] = instantiateId; this.OpRaiseEvent(0xcc, hashtable2, true, null); } public void SetApp(string appId, string gameVersion) { this.mAppId = appId.Trim(); if (!string.IsNullOrEmpty(gameVersion)) { this.mAppVersion = gameVersion.Trim(); } } protected internal void SetLevelInPropsIfSynced(object levelId) { if ((PhotonNetwork.automaticallySyncScene && PhotonNetwork.isMasterClient) && (PhotonNetwork.room != null)) { if (levelId == null) { Debug.LogError("Parameter levelId can't be null!"); } else { if (PhotonNetwork.room.customProperties.ContainsKey("curScn")) { object obj2 = PhotonNetwork.room.customProperties["curScn"]; if ((obj2 is int) && (Application.loadedLevel == ((int) obj2))) { return; } if ((obj2 is string) && Application.loadedLevelName.Equals((string) obj2)) { return; } } ExitGames.Client.Photon.Hashtable propertiesToSet = new ExitGames.Client.Photon.Hashtable(); if (levelId is int) { propertiesToSet["curScn"] = (int) levelId; } else if (levelId is string) { propertiesToSet["curScn"] = (string) levelId; } else { Debug.LogError("Parameter levelId must be int or string!"); } PhotonNetwork.room.SetCustomProperties(propertiesToSet); this.SendOutgoingCommands(); } } } public void SetLevelPrefix(short prefix) { this.currentLevelPrefix = prefix; } protected internal bool SetMasterClient(int playerId, bool sync) { if (((this.mMasterClient == null) || (this.mMasterClient.ID == -1)) || !this.mActors.ContainsKey(playerId)) { return false; } if (sync) { ExitGames.Client.Photon.Hashtable customEventContent = new ExitGames.Client.Photon.Hashtable(); customEventContent.Add((byte) 1, playerId); if (!this.OpRaiseEvent(0xd0, customEventContent, true, null)) { return false; } } this.hasSwitchedMC = true; this.mMasterClient = this.mActors[playerId]; object[] parameters = new object[] { this.mMasterClient }; SendMonoMessage(PhotonNetworkingMessage.OnMasterClientSwitched, parameters); return true; } public void SetReceivingEnabled(int group, bool enabled) { if (group <= 0) { Debug.LogError("Error: PhotonNetwork.SetReceivingEnabled was called with an illegal group number: " + group + ". The group number should be at least 1."); } else if (enabled) { if (!this.allowedReceivingGroups.Contains(group)) { this.allowedReceivingGroups.Add(group); byte[] groupsToAdd = new byte[] { (byte) group }; this.OpChangeGroups(null, groupsToAdd); } } else if (this.allowedReceivingGroups.Contains(group)) { this.allowedReceivingGroups.Remove(group); byte[] groupsToRemove = new byte[] { (byte) group }; this.OpChangeGroups(groupsToRemove, null); } } public void SetReceivingEnabled(int[] enableGroups, int[] disableGroups) { List<byte> list = new List<byte>(); List<byte> list2 = new List<byte>(); if (enableGroups != null) { for (int i = 0; i < enableGroups.Length; i++) { int item = enableGroups[i]; if (item <= 0) { Debug.LogError("Error: PhotonNetwork.SetReceivingEnabled was called with an illegal group number: " + item + ". The group number should be at least 1."); } else if (!this.allowedReceivingGroups.Contains(item)) { this.allowedReceivingGroups.Add(item); list.Add((byte) item); } } } if (disableGroups != null) { for (int j = 0; j < disableGroups.Length; j++) { int num4 = disableGroups[j]; if (num4 <= 0) { Debug.LogError("Error: PhotonNetwork.SetReceivingEnabled was called with an illegal group number: " + num4 + ". The group number should be at least 1."); } else if (list.Contains((byte) num4)) { Debug.LogError("Error: PhotonNetwork.SetReceivingEnabled disableGroups contains a group that is also in the enableGroups: " + num4 + "."); } else if (this.allowedReceivingGroups.Contains(num4)) { this.allowedReceivingGroups.Remove(num4); list2.Add((byte) num4); } } } this.OpChangeGroups((list2.Count <= 0) ? null : list2.ToArray(), (list.Count <= 0) ? null : list.ToArray()); } public void SetSendingEnabled(int group, bool enabled) { if (!enabled) { this.blockSendingGroups.Add(group); } else { this.blockSendingGroups.Remove(group); } } public void SetSendingEnabled(int[] enableGroups, int[] disableGroups) { if (enableGroups != null) { foreach (int num2 in enableGroups) { if (this.blockSendingGroups.Contains(num2)) { this.blockSendingGroups.Remove(num2); } } } if (disableGroups != null) { foreach (int num4 in disableGroups) { if (!this.blockSendingGroups.Contains(num4)) { this.blockSendingGroups.Add(num4); } } } } private void StoreInstantiationData(int instantiationId, object[] instantiationData) { this.tempInstantiationData[instantiationId] = instantiationData; } public bool WebRpc(string uriPath, object parameters) { Dictionary<byte, object> customOpParameters = new Dictionary<byte, object>(); customOpParameters.Add(0xd1, uriPath); customOpParameters.Add(0xd0, parameters); return this.OpCustom(0xdb, customOpParameters, true); } public List<Region> AvailableRegions { get; protected internal set; } public CloudRegionCode CloudRegion { get; protected internal set; } public AuthenticationValues CustomAuthenticationValues { get; set; } protected internal int FriendsListAge { get { return ((!this.isFetchingFriends && (this.friendListTimestamp != 0)) ? (Environment.TickCount - this.friendListTimestamp) : 0); } } public bool IsAuthorizeSecretAvailable { get { return false; } } public bool IsUsingNameServer { get; protected internal set; } public TypedLobby lobby { get; set; } protected internal string mAppVersionPun { get { return string.Format("{0}_{1}", this.mAppVersion, "1.28"); } } public string MasterServerAddress { get; protected internal set; } public Room mCurrentGame { get { if ((this.mRoomToGetInto != null) && this.mRoomToGetInto.isLocalClientInside) { return this.mRoomToGetInto; } return null; } } public int mGameCount { get; internal set; } public string mGameserver { get; internal set; } public PhotonPlayer mLocalActor { get; internal set; } public int mPlayersInRoomsCount { get; internal set; } public int mPlayersOnMasterCount { get; internal set; } public int mQueuePosition { get; internal set; } internal RoomOptions mRoomOptionsForCreate { get; set; } internal TypedLobby mRoomToEnterLobby { get; set; } internal Room mRoomToGetInto { get; set; } public string PlayerName { get { return this.playername; } set { if (!string.IsNullOrEmpty(value) && !value.Equals(this.playername)) { if (this.mLocalActor != null) { this.mLocalActor.name = value; } this.playername = value; if (this.mCurrentGame != null) { this.SendPlayerName(); } } } } protected internal ServerConnection server { get; private set; } public PeerStates State { get; internal set; } }
42.707424
335
0.497378
[ "MIT" ]
Jagerente/RCFixed
Source/NetworkingPeer.cs
136,922
C#
namespace RdcMan { internal class PluginContext : IPluginContext { IMainForm IPluginContext.MainForm => Program.TheForm; IServerTree IPluginContext.Tree => ServerTree.Instance; } }
19.8
58
0.742424
[ "MIT" ]
jiangfangzheng/RDCMan-mod
RdcMan/ConfigForm/PluginContext.cs
198
C#
using Bj.Essentials.Entities; using Bjx.WCF.Contracts; using System; using System.Collections.Generic; using System.ServiceModel; namespace Bj.Essentials.Proxies { public class HoldReasonClient : ClientBase<IHoldReasonService>, IHoldReasonService { public IEnumerable<HoldReason> GetAll(string company) { return Channel.GetAll(company); } public HoldReason Get(string company, int id) { return Channel.Get(company, id); } public IEnumerable<HoldReason> GetByNum(string company, int num) { return Channel.GetByNum(company, num); } } }
26.2
86
0.653435
[ "BSD-3-Clause" ]
brownjordaninternational/OrchardCMS
src/Orchard.Web/Modules/Entiat.CustomSettings/HoldReasonClient.cs
655
C#
#region Imports using System; using System.Data; using System.Linq; #endregion namespace CrazyflieDotNet.Crazyflie.TransferProtocol { /// <summary> /// Commander Payload Format: /// Name | Index | Type | Size (bytes) /// roll 0 float 4 /// pitch 4 float 4 /// yaw 8 float 4 /// thurst 12 ushort 2 /// .............................total: 14 bytes /// </summary> public class CommanderPacketPayload : PacketPayload, ICommanderPacketPayload { private static readonly int _floatSize = sizeof(float); private static readonly int _shortSize = sizeof(ushort); private static readonly int _commanderPayloadSize = _floatSize * 3 + _shortSize; /// <summary> /// Commander Payload Format: /// Name | Index | Type | Size (bytes) /// roll 0 float 4 /// pitch 4 float 4 /// yaw 8 float 4 /// thurst 12 ushort 2 /// .............................total: 14 bytes /// </summary> /// <param name="payloadBytes"> </param> public CommanderPacketPayload(byte[] payloadBytes) { if (payloadBytes == null) { throw new ArgumentNullException(nameof(payloadBytes)); } if (payloadBytes.Length != _commanderPayloadSize) { throw new ArgumentException(string.Format("Commander packet payload size must be {0} bytes.", _commanderPayloadSize)); } Roll = ParseRoll(payloadBytes); Pitch = ParsePitch(payloadBytes); Yaw = ParseYaw(payloadBytes); Thrust = ParseThrust(payloadBytes); } /// <summary> /// Initializes a new instance of the /// <see cref="T:CrazyflieDotNet.Crazyflie.TransferProtocol.CommanderPacketPayload"/> class. /// </summary> /// <param name="roll">Roll.</param> /// <param name="pitch">Pitch.</param> /// <param name="yaw">Yaw.</param> /// <param name="thrust">Thrust.</param> public CommanderPacketPayload(float roll, float pitch, float yaw, ushort thrust) { Roll = roll; Pitch = pitch; Yaw = yaw; Thrust = thrust; } /// <summary> /// Gets the roll. /// </summary> /// <value>The roll.</value> public float Roll { get; } /// <summary> /// Gets the pitch. /// </summary> /// <value>The pitch.</value> public float Pitch { get; } /// <summary> /// Gets the yaw. /// </summary> /// <value>The yaw.</value> public float Yaw { get; } /// <summary> /// Gets the thrust. /// </summary> /// <value>The thrust.</value> public ushort Thrust { get; } /// <summary> /// Gets the packet payload bytes. /// </summary> /// <returns>The packet payload bytes.</returns> protected override byte[] GetPacketPayloadBytes() { try { var rollBytes = BitConverter.GetBytes(Roll); var pitchBytes = BitConverter.GetBytes(Pitch); var yawBytes = BitConverter.GetBytes(Yaw); var thrustBytes = BitConverter.GetBytes(Thrust); var commanderPayloadBytes = new byte[_commanderPayloadSize]; Array.Copy(rollBytes, 0, commanderPayloadBytes, 0, rollBytes.Length); Array.Copy(pitchBytes, 0, commanderPayloadBytes, rollBytes.Length, pitchBytes.Length); Array.Copy(yawBytes, 0, commanderPayloadBytes, rollBytes.Length + pitchBytes.Length, yawBytes.Length); Array.Copy(thrustBytes, 0, commanderPayloadBytes, rollBytes.Length + pitchBytes.Length + yawBytes.Length, thrustBytes.Length); return commanderPayloadBytes; } catch (Exception ex) { throw new DataException("Error converting commander packet payload to bytes.", ex); } } /// <summary> /// Parses the roll. /// </summary> /// <returns>The roll.</returns> /// <param name="payloadBytes">Payload bytes.</param> private float ParseRoll(byte[] payloadBytes) { if (payloadBytes == null) { throw new ArgumentNullException(nameof(payloadBytes)); } try { var rollBytes = payloadBytes.Take(_floatSize).ToArray(); var roll = BitConverter.ToSingle(rollBytes, 0); return roll; } catch (Exception ex) { throw new DataException("Error getting commander packet header roll value from header byte", ex); } } /// <summary> /// Parses the pitch. /// </summary> /// <returns>The pitch.</returns> /// <param name="payloadBytes">Payload bytes.</param> private float ParsePitch(byte[] payloadBytes) { if (payloadBytes == null) { throw new ArgumentNullException(nameof(payloadBytes)); } try { var pitchBytes = payloadBytes.Skip(_floatSize).Take(_floatSize).ToArray(); var pitch = BitConverter.ToSingle(pitchBytes, 0); return pitch; } catch (Exception ex) { throw new DataException("Error getting commander packet header pitch value from header byte", ex); } } /// <summary> /// Parses the yaw. /// </summary> /// <returns>The yaw.</returns> /// <param name="payloadBytes">Payload bytes.</param> private float ParseYaw(byte[] payloadBytes) { if (payloadBytes == null) { throw new ArgumentNullException(nameof(payloadBytes)); } try { var yawBytes = payloadBytes.Skip(_floatSize * 2).Take(_floatSize).ToArray(); var yaw = BitConverter.ToSingle(yawBytes, 0); return yaw; } catch (Exception ex) { throw new DataException("Error getting commander packet header yaw value from header byte", ex); } } /// <summary> /// Parses the thrust. /// </summary> /// <returns>The thrust.</returns> /// <param name="payloadBytes">Payload bytes.</param> private ushort ParseThrust(byte[] payloadBytes) { if (payloadBytes == null) { throw new ArgumentNullException(nameof(payloadBytes)); } try { var thrustBytes = payloadBytes.Skip(_floatSize * 3).Take(_shortSize).ToArray(); var thrust = BitConverter.ToUInt16(thrustBytes, 0); return thrust; } catch (Exception ex) { throw new DataException("Error getting commander packet header thrust value from header byte", ex); } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:CrazyflieDotNet.Crazyflie.TransferProtocol.CommanderPacketPayload"/>. /// </summary> /// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:CrazyflieDotNet.Crazyflie.TransferProtocol.CommanderPacketPayload"/>.</returns> public override string ToString() { return string.Format("[Roll={0}, Pitch={1}, Yaw={2}, Thrust={3}]", Roll, Pitch, Yaw, Thrust); } } }
28.697368
167
0.638545
[ "MIT" ]
SupraBitKid/CrazyflieDotNet
CrazyflieDotNet/Source/CrazyflieDotNet.Crazyflie/TransferProtocol/CommanderPacketPayload.cs
6,543
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace DemLib { public class Ribbon { private Dictionary<int, Color> mRibbon = null; private int step = 0; public int Step { set { step = value; } } public Ribbon(int STEP) { this.step = STEP; mRibbon = InitializeRibbon(); } private Dictionary<int, Color> InitializeRibbon() { Dictionary<int, Color> pRibbon = new Dictionary<int, Color>(); int R, G, B; Random mRandom = new Random(); if (step == 20) { pRibbon.Add(0, Color.FromArgb(0, 0, 255)); pRibbon.Add(1, Color.FromArgb(173, 246, 177)); pRibbon.Add(2, Color.FromArgb(183, 246, 237)); pRibbon.Add(3, Color.FromArgb(186, 254, 197)); pRibbon.Add(4, Color.FromArgb(227, 255, 183)); pRibbon.Add(5, Color.FromArgb(252, 255, 184)); pRibbon.Add(6, Color.FromArgb(187, 223, 113)); pRibbon.Add(7, Color.FromArgb(44, 177, 52)); pRibbon.Add(8, Color.FromArgb(0, 133, 64)); pRibbon.Add(9, Color.FromArgb(158, 164, 40)); pRibbon.Add(10, Color.FromArgb(241, 187, 19)); pRibbon.Add(11, Color.FromArgb(219, 103, 0)); pRibbon.Add(12, Color.FromArgb(179, 43, 3)); pRibbon.Add(13, Color.FromArgb(122, 10, 0)); pRibbon.Add(14, Color.FromArgb(117, 25, 0)); pRibbon.Add(15, Color.FromArgb(109, 44, 12)); pRibbon.Add(16, Color.FromArgb(210, 82, 0)); pRibbon.Add(17, Color.FromArgb(132, 81, 52)); pRibbon.Add(18, Color.FromArgb(167, 149, 135)); pRibbon.Add(19, Color.FromArgb(206, 202, 203)); pRibbon.Add(20, Color.FromArgb(241, 231, 242)); pRibbon.Add(21, Color.White); } else { for (int i = 0; i <= step; i++) { R = mRandom.Next((int)255 / step * i,(int)255 / step * i+1); G = mRandom.Next((int)255 / (step * 2) * i, (int)255 / (step * 2) * i + 1); B = mRandom.Next((int)255 / (step * 3) * i, (int)255 / (step * 3) * i + 1); pRibbon.Add(i, Color.FromArgb(R, G, B)); } } return pRibbon; } public Color GetColor(int index) { return mRibbon[index]; } } }
36.27027
95
0.477645
[ "Apache-2.0" ]
henshin123/dem-
DemLib/Ribbon.cs
2,686
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace FinnovationLabs.OpenBanking.Library.BankApiModels.UkObRw.V3p1p2.Pisp.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; public partial class OBWriteInternationalScheduledResponse3Data { /// <summary> /// Initializes a new instance of the /// OBWriteInternationalScheduledResponse3Data class. /// </summary> public OBWriteInternationalScheduledResponse3Data() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// OBWriteInternationalScheduledResponse3Data class. /// </summary> /// <param name="internationalScheduledPaymentId">OB: Unique /// identification as assigned by the ASPSP to uniquely identify the /// international scheduled payment resource.</param> /// <param name="consentId">OB: Unique identification as assigned by /// the ASPSP to uniquely identify the consent resource.</param> /// <param name="creationDateTime">Date and time at which the message /// was created.All dates in the JSON payloads are represented in ISO /// 8601 date-time format. /// All date-time fields in responses must include the timezone. An /// example is below: /// 2017-04-05T10:43:07+00:00</param> /// <param name="status">Specifies the status of the payment order /// resource. Possible values include: 'Cancelled', /// 'InitiationCompleted', 'InitiationFailed', /// 'InitiationPending'</param> /// <param name="statusUpdateDateTime">Date and time at which the /// resource status was updated.All dates in the JSON payloads are /// represented in ISO 8601 date-time format. /// All date-time fields in responses must include the timezone. An /// example is below: /// 2017-04-05T10:43:07+00:00</param> /// <param name="initiation">The Initiation payload is sent by the /// initiating party to the ASPSP. It is used to request movement of /// funds from the debtor account to a creditor for a single scheduled /// international payment.</param> /// <param name="expectedExecutionDateTime">Expected execution date and /// time for the payment resource.All dates in the JSON payloads are /// represented in ISO 8601 date-time format. /// All date-time fields in responses must include the timezone. An /// example is below: /// 2017-04-05T10:43:07+00:00</param> /// <param name="expectedSettlementDateTime">Expected settlement date /// and time for the payment resource.All dates in the JSON payloads /// are represented in ISO 8601 date-time format. /// All date-time fields in responses must include the timezone. An /// example is below: /// 2017-04-05T10:43:07+00:00</param> /// <param name="exchangeRateInformation">Further detailed information /// on the exchange rate that has been used in the payment /// transaction.</param> /// <param name="multiAuthorisation">The multiple authorisation flow /// response from the ASPSP.</param> public OBWriteInternationalScheduledResponse3Data(string internationalScheduledPaymentId, string consentId, System.DateTimeOffset creationDateTime, OBWriteInternationalScheduledResponse3DataStatusEnum status, System.DateTimeOffset statusUpdateDateTime, OBWriteInternationalScheduledResponse3DataInitiation initiation, System.DateTimeOffset? expectedExecutionDateTime = default(System.DateTimeOffset?), System.DateTimeOffset? expectedSettlementDateTime = default(System.DateTimeOffset?), IList<OBWriteInternationalScheduledResponse3DataChargesItem> charges = default(IList<OBWriteInternationalScheduledResponse3DataChargesItem>), OBWriteInternationalScheduledResponse3DataExchangeRateInformation exchangeRateInformation = default(OBWriteInternationalScheduledResponse3DataExchangeRateInformation), OBWriteInternationalScheduledResponse3DataMultiAuthorisation multiAuthorisation = default(OBWriteInternationalScheduledResponse3DataMultiAuthorisation)) { InternationalScheduledPaymentId = internationalScheduledPaymentId; ConsentId = consentId; CreationDateTime = creationDateTime; Status = status; StatusUpdateDateTime = statusUpdateDateTime; ExpectedExecutionDateTime = expectedExecutionDateTime; ExpectedSettlementDateTime = expectedSettlementDateTime; Charges = charges; ExchangeRateInformation = exchangeRateInformation; Initiation = initiation; MultiAuthorisation = multiAuthorisation; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets OB: Unique identification as assigned by the ASPSP to /// uniquely identify the international scheduled payment resource. /// </summary> [JsonProperty(PropertyName = "InternationalScheduledPaymentId")] public string InternationalScheduledPaymentId { get; set; } /// <summary> /// Gets or sets OB: Unique identification as assigned by the ASPSP to /// uniquely identify the consent resource. /// </summary> [JsonProperty(PropertyName = "ConsentId")] public string ConsentId { get; set; } /// <summary> /// Gets or sets date and time at which the message was created.All /// dates in the JSON payloads are represented in ISO 8601 date-time /// format. /// All date-time fields in responses must include the timezone. An /// example is below: /// 2017-04-05T10:43:07+00:00 /// </summary> [JsonProperty(PropertyName = "CreationDateTime")] public System.DateTimeOffset CreationDateTime { get; set; } /// <summary> /// Gets or sets specifies the status of the payment order resource. /// Possible values include: 'Cancelled', 'InitiationCompleted', /// 'InitiationFailed', 'InitiationPending' /// </summary> [JsonProperty(PropertyName = "Status")] public OBWriteInternationalScheduledResponse3DataStatusEnum Status { get; set; } /// <summary> /// Gets or sets date and time at which the resource status was /// updated.All dates in the JSON payloads are represented in ISO 8601 /// date-time format. /// All date-time fields in responses must include the timezone. An /// example is below: /// 2017-04-05T10:43:07+00:00 /// </summary> [JsonProperty(PropertyName = "StatusUpdateDateTime")] public System.DateTimeOffset StatusUpdateDateTime { get; set; } /// <summary> /// Gets or sets expected execution date and time for the payment /// resource.All dates in the JSON payloads are represented in ISO 8601 /// date-time format. /// All date-time fields in responses must include the timezone. An /// example is below: /// 2017-04-05T10:43:07+00:00 /// </summary> [JsonProperty(PropertyName = "ExpectedExecutionDateTime")] public System.DateTimeOffset? ExpectedExecutionDateTime { get; set; } /// <summary> /// Gets or sets expected settlement date and time for the payment /// resource.All dates in the JSON payloads are represented in ISO 8601 /// date-time format. /// All date-time fields in responses must include the timezone. An /// example is below: /// 2017-04-05T10:43:07+00:00 /// </summary> [JsonProperty(PropertyName = "ExpectedSettlementDateTime")] public System.DateTimeOffset? ExpectedSettlementDateTime { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Charges")] public IList<OBWriteInternationalScheduledResponse3DataChargesItem> Charges { get; set; } /// <summary> /// Gets or sets further detailed information on the exchange rate that /// has been used in the payment transaction. /// </summary> [JsonProperty(PropertyName = "ExchangeRateInformation")] public OBWriteInternationalScheduledResponse3DataExchangeRateInformation ExchangeRateInformation { get; set; } /// <summary> /// Gets or sets the Initiation payload is sent by the initiating party /// to the ASPSP. It is used to request movement of funds from the /// debtor account to a creditor for a single scheduled international /// payment. /// </summary> [JsonProperty(PropertyName = "Initiation")] public OBWriteInternationalScheduledResponse3DataInitiation Initiation { get; set; } /// <summary> /// Gets or sets the multiple authorisation flow response from the /// ASPSP. /// </summary> [JsonProperty(PropertyName = "MultiAuthorisation")] public OBWriteInternationalScheduledResponse3DataMultiAuthorisation MultiAuthorisation { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (InternationalScheduledPaymentId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "InternationalScheduledPaymentId"); } if (ConsentId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ConsentId"); } if (Initiation == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Initiation"); } if (Charges != null) { foreach (var element in Charges) { if (element != null) { element.Validate(); } } } if (ExchangeRateInformation != null) { ExchangeRateInformation.Validate(); } if (Initiation != null) { Initiation.Validate(); } if (MultiAuthorisation != null) { MultiAuthorisation.Validate(); } } } }
47.340517
957
0.642174
[ "MIT" ]
finlabsuk/open-banking-connector
src/OpenBanking.Library.BankApiModels/UkObRw/V3p1p2/Pisp/Models/OBWriteInternationalScheduledResponse3Data.cs
10,983
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Composition; using StarkPlatform.Compiler.AddMissingImports; using StarkPlatform.Compiler.Stark.AddImport; using StarkPlatform.Compiler.Host.Mef; namespace StarkPlatform.Compiler.Stark.AddMissingImports { [ExportLanguageService(typeof(IAddMissingImportsFeatureService), LanguageNames.Stark), Shared] internal class CSharpAddMissingImportsFeatureService : AbstractAddMissingImportsFeatureService { protected sealed override ImmutableArray<string> FixableDiagnosticIds => AddImportDiagnosticIds.FixableDiagnosticIds; } }
44.470588
161
0.822751
[ "BSD-2-Clause", "MIT" ]
encrypt0r/stark
src/compiler/StarkPlatform.Compiler.Stark.Features/AddImport/CSharpAddMissingImportsFeatureService.cs
758
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hl7-org:v3")] public enum Consent_codeSystem { /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("2.16.840.1.113883.2.1.3.2.4.16.2")] Item216840111388321324162, } }
82.071429
1,358
0.748912
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/Consent_codeSystem.cs
2,298
C#
#nullable enable using System; using System.Dynamic; using DevToys.Core; using DevToys.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using YamlDotNet.Core; using YamlDotNet.Serialization; namespace DevToys.Helpers.JsonYaml { internal static class YamlHelper { /// <summary> /// Detects whether the given string is a valid YAML or not. /// </summary> internal static bool IsValidYaml(string? input) { if (string.IsNullOrWhiteSpace(input)) { return false; } input = input!.Trim(); if (long.TryParse(input, out _)) { return false; } try { object? result = new DeserializerBuilder().Build().Deserialize<object>(input); return result is not null and not string; } catch (Exception) { return false; } } /// <summary> /// Convert a Json string to Yaml /// </summary> internal static string? ConvertFromJson(string? input, Indentation indentationMode) { if (string.IsNullOrWhiteSpace(input)) { return string.Empty; } try { object? jsonObject = null; var token = JToken.Parse(input!); if (token is null) { return string.Empty; } JsonSerializerSettings defaultJsonSerializerSettings = new() { FloatParseHandling = FloatParseHandling.Decimal }; if (token is JArray) { jsonObject = JsonConvert.DeserializeObject<ExpandoObject[]>(input!, defaultJsonSerializerSettings); } else { jsonObject = JsonConvert.DeserializeObject<ExpandoObject>(input!, defaultJsonSerializerSettings); } if (jsonObject is not null and not string) { int indent = 0; indent = indentationMode switch { Indentation.TwoSpaces => 2, Indentation.FourSpaces => 4, _ => throw new NotSupportedException(), }; var serializer = Serializer.FromValueSerializer( new SerializerBuilder().BuildValueSerializer(), EmitterSettings.Default.WithBestIndent(indent).WithIndentedSequences()); string? yaml = serializer.Serialize(jsonObject); if (string.IsNullOrWhiteSpace(yaml)) { return string.Empty; } return yaml; } return string.Empty; } catch (JsonReaderException ex) { return ex.Message; } catch (Exception ex) { Logger.LogFault("Yaml to Json Converter", ex); return string.Empty; } } } }
29.191304
119
0.467084
[ "MIT" ]
DDC-NDRS/DevToys
src/dev/impl/DevToys/Helpers/JsonYaml/YamlHelper.cs
3,359
C#
using System; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using StatusGeneric; namespace GenericServices.Unity { /// <summary> /// This is the sync interface to CrudServicesAsync, which assumes you have one DbContext which the CrudServices setup code will register to the DbContext type /// You should use this with dependency injection to get an instance of the sync CrudServices /// </summary> public interface ICrudServicesAsync : IStatusGeneric { /// <summary> /// This allows you to access the current DbContext that this instance of the CrudServices is using. /// That is useful if you need to set up some properties in the DTO that cannot be found in the Entity /// For instance, setting up a dropdownlist based on some other database data /// </summary> DbContext Context { get; } /// <summary> /// This reads async a single entity or DTO given the key(s) of the entity you want to load /// </summary> /// <typeparam name="T">This should either be an entity class or a CrudServices DTO which has a <see cref="ILinkToEntity{TEntity}"/> interface</typeparam> /// <param name="keys">The key(s) value. If there are multiple keys they must be in the correct order as defined by EF Core</param> /// <returns>A task with a single entity or DTO that was found by the keys. If its an entity class then it is tracked</returns> Task<T> ReadSingleAsync<T>(params object[] keys) where T : class; /// <summary> /// This reads async a single entity or DTO using a where clause /// </summary> /// <typeparam name="T">This should either be an entity class or a CrudServices DTO which has a <see cref="ILinkToEntity{TEntity}"/> interface</typeparam> /// <param name="whereExpression">The where expression should return a single instance, otherwise you get a </param> /// <returns>A task with a single entity or DTO that was found by the where clause. If its an entity class then it is tracked</returns> Task<T> ReadSingleAsync<T>(Expression<Func<T, bool>> whereExpression) where T : class; /// <summary> /// This returns an <see cref="IQueryable{T}"/> result, where T can be either an actual entity class, /// or if a CrudServices DTO is provided then the linked entity class will be projected via AutoMapper to the DTO /// Apply an async method such as ToListAsync to execute the query asynchrously /// </summary> /// <typeparam name="T">This should either be an entity class or a CrudServices DTO which has a <see cref="ILinkToEntity{TEntity}"/> interface</typeparam> /// <returns>an <see cref="IQueryable{T}"/> result. You should apply a execute method, e.g. .ToList() or .ToListAsync() to execute the result</returns> IQueryable<T> ReadManyNoTracked<T>() where T : class; /// <summary> /// This allows you to read data with a query prior to the projection to a DTO. /// This is useful if you want to filter the data on properties not in the final DTO. /// It is also useful when wanting to apply a method such as IgnoreQueryFilters /// </summary> /// <typeparam name="TEntity">This must be a entity or query class in the current DbContext</typeparam> /// <typeparam name="TDto">This should be a class with an <see cref="ILinkToEntity{TEntity}"/> </typeparam> /// <param name="query">The queryable source will come from an entity or query class in the current DbContext</param> /// <returns></returns> IQueryable<TDto> ProjectFromEntityToDto<TEntity, TDto>(Func<IQueryable<TEntity>, IQueryable<TEntity>> query) where TEntity : class; /// <summary> /// This will create async a new entity in the database. If you provide class which is an entity class (i.e. in your EF Core database) then /// the method will add, and then call SaveChanges. If the class you provide is a CrudServices DTO which has a <see cref="ILinkToEntity{TEntity}"/> interface /// it will use that to create the entity by matching the DTOs properties to either, a) a public static method, b) a public ctor, or /// c) by setting the properties with public setters in the entity (using AutoMapper) /// </summary> /// <typeparam name="T">This type is found from the input instance</typeparam> /// <param name="entityOrDto">This should either be an instance of a entity class or a CrudServices DTO which has a <see cref="ILinkToEntity{TEntity}"/> interface</param> /// <param name="ctorOrStaticMethodName">Optional: you can tell GenericServices which static method, ctor or CrudValues.UseAutoMapper to use</param> /// <returns>It returns a task with the class you provided. It will contain the primary key defined after the database. /// If its a DTO then GenericServices will have copied the keys from the entity added back into the DTO</returns> Task<T> CreateAndSaveAsync<T>(T entityOrDto, string ctorOrStaticMethodName = null) where T : class; /// <summary> /// This will update the entity referred to by the keys in the given class instance. /// For a entity class instance it will check the state of the instance. If its detached it will call Update, otherwise it assumes its tracked and calls SaveChanges /// For a CrudServices DTO it will: /// a) load the existing entity class using the primary key(s) in the DTO /// b) This it will look for a public method that match the DTO's properties to do the update, or if no method is found it will try to use AutoMapper to copy the data over to the e /// c) finally it will call SaveChanges /// </summary> /// <typeparam name="T">This type is found from the input instance</typeparam> /// <param name="entityOrDto">This should either be an instance of a entity class or a CrudServices DTO which has a <see cref="ILinkToEntity{TEntity}"/> interface</param> /// <param name="methodName">Optional: you can give the method name to be used for the update, or CrudValues.UseAutoMapper to make it use AutoMapper to update the entity.</param> /// <returns>Task, async</returns> Task UpdateAndSaveAsync<T>(T entityOrDto, string methodName = null) where T : class; ///// <summary> ///// This allows you to update properties with public setters using a JsonPatch <cref>http://jsonpatch.com/</cref> ///// The keys allow you to define which entity class you want updated ///// </summary> ///// <typeparam name="TEntity">The entity class you want to update. It should be an entity in the DbContext you are referring to.</typeparam> ///// <param name="patch">this is a JsonPatch containing "replace" operations</param> ///// <param name="keys">These are the primary key(s) to access the entity</param> ///// <returns></returns> //Task<TEntity> UpdateAndSaveAsync<TEntity>(JsonPatchDocument<TEntity> patch, params object[] keys) where TEntity : class; ///// <summary> ///// This allows you to update properties with public setters using a JsonPatch <cref>http://jsonpatch.com/</cref> ///// The whereExpression allow you to define which entity class you want updated ///// </summary> ///// <typeparam name="TEntity">The entity class you want to update. It should be an entity in the DbContext you are referring to.</typeparam> ///// <param name="patch">this is a JsonPatch containing "replace" operations</param> ///// <param name="whereExpression">This is a filter command that will return a single entity (or no entity)</param> ///// <returns></returns> //Task<TEntity> UpdateAndSaveAsync<TEntity>(JsonPatchDocument<TEntity> patch, Expression<Func<TEntity, bool>> whereExpression) where TEntity : class; /// <summary> /// This will delete async the entity class with the given primary key /// </summary> /// <typeparam name="TEntity">The entity class you want to delete. It should be an entity in the DbContext you are referring to.</typeparam> /// <param name="keys">The key(s) value. If there are multiple keys they must be in the correct order as defined by EF Core</param> /// <returns>Task, async</returns> Task DeleteAndSaveAsync<TEntity>(params object[] keys) where TEntity : class; /// <summary> /// This will find entity class async with the given primary key, then call the method you provide before calling the Remove method + SaveChanges. /// Your method has access to the database and can handle any relationships, and returns an <see cref="IStatusGeneric"/>. The Remove will /// only go ahead if the status your method returns is Valid, i.e. no errors /// NOTE: This method ignore any query filters when deleting. If you are working in a multi-tenant system you should include a test /// that the entity you are deleting has the correct TenantId /// </summary> /// <typeparam name="TEntity">The entity class you want to delete. It should be an entity in the DbContext you are referring to.</typeparam> /// <param name="runBeforeDelete">You provide an async method, which is called after the entity to delete has been loaded, but before the Remove method is called. /// Your method has access to the database and can handle any relationships, and returns an <see cref="IStatusGeneric"/>. The Remove will /// only go ahead if the status your method returns is Valid, i.e. no errors</param> /// <param name="keys">The key(s) value. If there are multiple keys they must be in the correct order as defined by EF Core</param> /// <returns>Task, async</returns> Task DeleteWithActionAndSaveAsync<TEntity>(Func<DbContext, TEntity, Task<IStatusGeneric>> runBeforeDelete, params object[] keys) where TEntity : class; } }
77.106061
188
0.68373
[ "MIT" ]
JanKupke1/EfCore.GenericServices.Unity
GenericServices/ICrudServicesAsync.cs
10,180
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("SharedWeekends.Data")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharedWeekends.Data")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("4f2cb379-72e3-47cc-857f-ef64fb75c89f")] // 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.135135
84
0.746279
[ "MIT" ]
kalinalazarova1/SharedWeekends
SharedWeekends.Data/Properties/AssemblyInfo.cs
1,414
C#
//-------------------------------------------------- // <copyright file="FileLogger.cs" company="Magenic"> // Copyright 2020 Magenic, All rights Reserved // </copyright> // <summary>Writes event logs to plain text file</summary> //-------------------------------------------------- using Magenic.Maqs.Utilities.Data; using System; using System.Globalization; using System.IO; using System.Text.RegularExpressions; namespace Magenic.Maqs.Utilities.Logging { /// <summary> /// Helper class for adding logs to a plain text file. Allows configurable file path. /// </summary> public class FileLogger : Logger { /// <summary> /// The default log file save location /// </summary> protected readonly string DEFAULTLOGFOLDER = Path.GetTempPath(); /// <summary> /// Object for locking the log file so /// pending tasks will wait for file to be freed /// </summary> protected readonly object FileLock = new object(); /// <summary> /// Initializes a new instance of the FileLogger class /// </summary> private const string DEFAULTLOGNAME = "FileLog.txt"; /// <summary> /// Initializes a new instance of the FileLogger class /// </summary> /// <param name="logFolder">Where log files should be saved</param> /// <param name="name">File Name</param> /// <param name="messageLevel">Messaging level</param> /// <param name="append">True to append to an existing log file or false to overwrite it - If the file does not exist this, flag will have no affect</param> public FileLogger(string logFolder = "", string name = DEFAULTLOGNAME, MessageType messageLevel = MessageType.INFORMATION, bool append = false) : base(messageLevel) { string directory; if (string.IsNullOrEmpty(logFolder)) { directory = this.DEFAULTLOGFOLDER; } else { directory = logFolder; } if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (!name.EndsWith(this.Extension, StringComparison.CurrentCultureIgnoreCase)) { name += this.Extension; } this.FilePath = Path.Combine(directory, MakeValidFileName(name)); if (File.Exists(this.FilePath) && !append) { StreamWriter writer = new StreamWriter(this.FilePath, false); writer.Write(string.Empty); writer.Flush(); writer.Close(); } } /// <summary> /// Gets or sets the FilePath value /// </summary> public string FilePath { get; set; } /// <summary> /// Gets the file extension /// </summary> protected virtual string Extension { get { return ".txt"; } } /// <summary> /// Write the formatted message (one line) to the console as the specified type /// </summary> /// <param name="message">The message text</param> /// <param name="args">String format arguments</param> public override void LogMessage(string message, params object[] args) { this.LogMessage(MessageType.INFORMATION, message, args); } /// <summary> /// Write the formatted message (one line) to the console as a generic message /// </summary> /// <param name="messageType">The type of message</param> /// <param name="message">The message text</param> /// <param name="args">String format arguments</param> public override void LogMessage(MessageType messageType, string message, params object[] args) { // If the message level is greater that the current log level then do not log it. if (this.ShouldMessageBeLogged(messageType)) { // Log the message lock (this.FileLock) { try { using (StreamWriter writer = new StreamWriter(this.FilePath, true)) { string date = DateTime.UtcNow.ToString(Logger.DEFAULTDATEFORMAT, CultureInfo.InvariantCulture); writer.WriteLine(StringProcessor.SafeFormatter("{0}{1}", Environment.NewLine, date)); writer.Write(StringProcessor.SafeFormatter("{0}:\t", messageType.ToString())); writer.WriteLine(StringProcessor.SafeFormatter(message, args)); } } catch (Exception e) { // Failed to write to the event log, write error to the console instead ConsoleLogger console = new ConsoleLogger(); console.LogMessage(MessageType.ERROR, StringProcessor.SafeFormatter("Failed to write to event log because: {0}", e.Message)); console.LogMessage(messageType, message, args); } } } } /// <summary> /// Take a name sting and make it a valid file name /// </summary> /// <param name="name">The string to cleanup</param> /// <returns>The string as a valid file name</returns> private static string MakeValidFileName(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Blank file name was provide"); } // Create a regex to replace invalid characters string charsToReplace = string.Format(@"([{0}]*\.+$)|([{0}]+)", Regex.Escape(new string(Path.GetInvalidFileNameChars()))); // Replace invalid characters return Regex.Replace(name, charsToReplace, "~"); } } }
38.987179
164
0.544722
[ "MIT" ]
BrannenGH/MAQS
Framework/Utilities/Logging/FileLogger.cs
6,084
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Mvc; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Editors; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.WebApi; using Umbraco.Web.WebApi.Filters; namespace Umbraco.Web.Editors { /// <summary> /// An abstract base controller used for media/content (and probably members) to try to reduce code replication. /// </summary> [OutgoingDateTimeFormat] public abstract class ContentControllerBase : BackOfficeNotificationsController { /// <summary> /// Constructor /// </summary> protected ContentControllerBase() : this(UmbracoContext.Current) { } /// <summary> /// Constructor /// </summary> /// <param name="umbracoContext"></param> protected ContentControllerBase(UmbracoContext umbracoContext) : base(umbracoContext) { } protected HttpResponseMessage HandleContentNotFound(object id, bool throwException = true) { ModelState.AddModelError("id", string.Format("content with id: {0} was not found", id)); var errorResponse = Request.CreateErrorResponse( HttpStatusCode.NotFound, ModelState); if (throwException) { throw new HttpResponseException(errorResponse); } return errorResponse; } protected void UpdateName<TPersisted>(ContentBaseItemSave<TPersisted> contentItem) where TPersisted : IContentBase { //Don't update the name if it is empty if (!contentItem.Name.IsNullOrWhiteSpace()) { contentItem.PersistedContent.Name = contentItem.Name; } } protected HttpResponseMessage PerformSort(ContentSortOrder sorted) { if (sorted == null) { return Request.CreateResponse(HttpStatusCode.NotFound); } //if there's nothing to sort just return ok if (sorted.IdSortOrder.Length == 0) { return Request.CreateResponse(HttpStatusCode.OK); } return null; } /// <summary> /// Maps the dto property values to the persisted model /// </summary> /// <typeparam name="TPersisted"></typeparam> /// <param name="contentItem"></param> protected virtual void MapPropertyValues<TPersisted>(ContentBaseItemSave<TPersisted> contentItem) where TPersisted : IContentBase { //Map the property values foreach (var p in contentItem.ContentDto.Properties) { //get the dbo property var dboProperty = contentItem.PersistedContent.Properties[p.Alias]; //create the property data to send to the property editor var d = new Dictionary<string, object>(); //add the files if any var files = contentItem.UploadedFiles.Where(x => x.PropertyAlias == p.Alias).ToArray(); if (files.Length > 0) { d.Add("files", files); } var data = new ContentPropertyData(p.Value, p.PreValues, d); //get the deserialized value from the property editor if (p.PropertyEditor == null) { LogHelper.Warn<ContentController>("No property editor found for property " + p.Alias); } else { var valueEditor = p.PropertyEditor.ValueEditor; //don't persist any bound value if the editor is readonly if (valueEditor.IsReadOnly == false) { var propVal = p.PropertyEditor.ValueEditor.ConvertEditorToDb(data, dboProperty.Value); var supportTagsAttribute = TagExtractor.GetAttribute(p.PropertyEditor); if (supportTagsAttribute != null) { TagExtractor.SetPropertyTags(dboProperty, data, propVal, supportTagsAttribute); } else { dboProperty.Value = propVal; } } } } } protected void HandleInvalidModelState<T, TPersisted>(ContentItemDisplayBase<T, TPersisted> display) where TPersisted : IContentBase where T : ContentPropertyBasic { //lasty, if it is not valid, add the modelstate to the outgoing object and throw a 403 if (!ModelState.IsValid) { display.Errors = ModelState.ToErrorDictionary(); throw new HttpResponseException(Request.CreateValidationErrorResponse(display)); } } /// <summary> /// A helper method to attempt to get the instance from the request storage if it can be found there, /// otherwise gets it from the callback specified /// </summary> /// <typeparam name="TPersisted"></typeparam> /// <param name="getFromService"></param> /// <returns></returns> /// <remarks> /// This is useful for when filters have alraedy looked up a persisted entity and we don't want to have /// to look it up again. /// </remarks> protected TPersisted GetObjectFromRequest<TPersisted>(Func<TPersisted> getFromService) { //checks if the request contains the key and the item is not null, if that is the case, return it from the request, otherwise return // it from the callback return Request.Properties.ContainsKey(typeof(TPersisted).ToString()) && Request.Properties[typeof(TPersisted).ToString()] != null ? (TPersisted) Request.Properties[typeof (TPersisted).ToString()] : getFromService(); } /// <summary> /// Returns true if the action passed in means we need to create something new /// </summary> /// <param name="action"></param> /// <returns></returns> internal static bool IsCreatingAction(ContentSaveAction action) { return (action.ToString().EndsWith("New")); } protected void AddCancelMessage(INotificationModel display, string header = "speechBubbles/operationCancelledHeader", string message = "speechBubbles/operationCancelledText", bool localizeHeader = true, bool localizeMessage = true) { //if there's already a default event message, don't add our default one var msgs = UmbracoContext.GetCurrentEventMessages(); if (msgs != null && msgs.GetAll().Any(x => x.IsDefaultEventMessage)) return; display.AddWarningNotification( localizeHeader ? Services.TextService.Localize(header) : header, localizeMessage ? Services.TextService.Localize(message): message); } } }
40.239583
145
0.555397
[ "MIT" ]
melispalaz/Umbraco-CMS
src/Umbraco.Web/Editors/ContentControllerBase.cs
7,726
C#
namespace FootballTeamGenerator.Commands { using System.Linq; public class CommandParser { public Command Parse(string input) { var inputParts = input.Split(";"); var name = inputParts[0]; var arguments = inputParts.Skip(1).ToArray(); return new Command(name, arguments); } } }
21.705882
57
0.569106
[ "MIT" ]
kalintsenkov/SoftUni-Software-Engineering
CSharp-OOP/Homeworks-And-Labs/03EncapsulationExercise/05FootballTeamGenerator/Commands/CommandParser.cs
371
C#
// SPDX-FileCopyrightText: © 2021-2022 MONAI Consortium // SPDX-License-Identifier: Apache License 2.0 using Monai.Deploy.Messaging.Common; namespace Monai.Deploy.WorkflowManager.PayloadListener.Services { public interface IEventPayloadReceiverService { /// <summary> /// Receives a workflow message payload and validates it, /// either passing it on to the workflow executor or handling the message accordingly. /// </summary> /// <param name="message">The workflow message event.</param> Task ReceiveWorkflowPayload(MessageReceivedEventArgs message); /// <summary> /// Receives an update task message payload and validates it, /// then goes on to update the workflow instance database record /// </summary> /// <param name="message">The workflow message event.</param> Task TaskUpdatePayload(MessageReceivedEventArgs message); } }
37.8
94
0.687831
[ "Apache-2.0" ]
Project-MONAI/monai-deploy-workflow-manager
src/PayloadListener/Services/IEventPayloadRecieverService.cs
948
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Model\EntityType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type Vendor. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class Vendor : Entity { ///<summary> /// The Vendor constructor ///</summary> public Vendor() { this.ODataType = "microsoft.graph.vendor"; } /// <summary> /// Gets or sets number. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "number", Required = Newtonsoft.Json.Required.Default)] public string Number { get; set; } /// <summary> /// Gets or sets display name. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "displayName", Required = Newtonsoft.Json.Required.Default)] public string DisplayName { get; set; } /// <summary> /// Gets or sets address. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "address", Required = Newtonsoft.Json.Required.Default)] public PostalAddressType Address { get; set; } /// <summary> /// Gets or sets phone number. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "phoneNumber", Required = Newtonsoft.Json.Required.Default)] public string PhoneNumber { get; set; } /// <summary> /// Gets or sets email. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "email", Required = Newtonsoft.Json.Required.Default)] public string Email { get; set; } /// <summary> /// Gets or sets website. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "website", Required = Newtonsoft.Json.Required.Default)] public string Website { get; set; } /// <summary> /// Gets or sets tax registration number. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "taxRegistrationNumber", Required = Newtonsoft.Json.Required.Default)] public string TaxRegistrationNumber { get; set; } /// <summary> /// Gets or sets currency id. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "currencyId", Required = Newtonsoft.Json.Required.Default)] public Guid? CurrencyId { get; set; } /// <summary> /// Gets or sets currency code. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "currencyCode", Required = Newtonsoft.Json.Required.Default)] public string CurrencyCode { get; set; } /// <summary> /// Gets or sets payment terms id. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "paymentTermsId", Required = Newtonsoft.Json.Required.Default)] public Guid? PaymentTermsId { get; set; } /// <summary> /// Gets or sets payment method id. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "paymentMethodId", Required = Newtonsoft.Json.Required.Default)] public Guid? PaymentMethodId { get; set; } /// <summary> /// Gets or sets tax liable. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "taxLiable", Required = Newtonsoft.Json.Required.Default)] public bool? TaxLiable { get; set; } /// <summary> /// Gets or sets blocked. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "blocked", Required = Newtonsoft.Json.Required.Default)] public string Blocked { get; set; } /// <summary> /// Gets or sets balance. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "balance", Required = Newtonsoft.Json.Required.Default)] public Decimal? Balance { get; set; } /// <summary> /// Gets or sets last modified date time. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "lastModifiedDateTime", Required = Newtonsoft.Json.Required.Default)] public DateTimeOffset? LastModifiedDateTime { get; set; } /// <summary> /// Gets or sets picture. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "picture", Required = Newtonsoft.Json.Required.Default)] public IVendorPictureCollectionPage Picture { get; set; } /// <summary> /// Gets or sets currency. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "currency", Required = Newtonsoft.Json.Required.Default)] public Currency Currency { get; set; } /// <summary> /// Gets or sets payment term. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "paymentTerm", Required = Newtonsoft.Json.Required.Default)] public PaymentTerm PaymentTerm { get; set; } /// <summary> /// Gets or sets payment method. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "paymentMethod", Required = Newtonsoft.Json.Required.Default)] public PaymentMethod PaymentMethod { get; set; } } }
42.493333
153
0.615783
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Models/Generated/Vendor.cs
6,374
C#
namespace Epi.Windows.ImportExport.Dialogs { partial class ProjectUpgradeDialog { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProjectUpgradeDialog)); this.grpSourceProject = new System.Windows.Forms.GroupBox(); this.txtSourceProject = new System.Windows.Forms.TextBox(); this.lblSourceProject = new System.Windows.Forms.Label(); this.grpProject.SuspendLayout(); this.grpData.SuspendLayout(); this.grpView.SuspendLayout(); this.grpMetadata.SuspendLayout(); this.grpSourceProject.SuspendLayout(); this.SuspendLayout(); // // grpProject // this.grpProject.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left))); this.grpProject.Location = new System.Drawing.Point(7, 92); this.grpProject.Size = new System.Drawing.Size(475, 184); // // btnBrowseProjectLocation // this.btnBrowseProjectLocation.Location = new System.Drawing.Point(372, 73); // // grpData // this.grpData.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left))); this.grpData.Location = new System.Drawing.Point(7, 290); this.grpData.Size = new System.Drawing.Size(475, 95); // // grpView // this.grpView.Location = new System.Drawing.Point(9, 435); this.grpView.Size = new System.Drawing.Size(581, 77); // // txtViewName // this.txtViewName.Size = new System.Drawing.Size(554, 20); // // btnOk // this.btnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left))); this.btnOk.Location = new System.Drawing.Point(191, 391); this.btnOk.Size = new System.Drawing.Size(93, 23); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left))); this.btnCancel.Location = new System.Drawing.Point(290, 391); this.btnCancel.Size = new System.Drawing.Size(93, 23); // // btnHelp // this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left))); this.btnHelp.Location = new System.Drawing.Point(389, 391); this.btnHelp.Size = new System.Drawing.Size(93, 23); // // btnBuildCollectedDataConnectionString // this.btnBuildCollectedDataConnectionString.Location = new System.Drawing.Point(372, 32); // // cbxMetadataDriver // this.cbxMetadataDriver.Size = new System.Drawing.Size(242, 21); // // txtMetadata // this.txtMetadata.Size = new System.Drawing.Size(167, 20); // // btnBuildMetadataConnectionString // this.btnBuildMetadataConnectionString.Location = new System.Drawing.Point(417, 597); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); this.baseImageList.Images.SetKeyName(76, ""); this.baseImageList.Images.SetKeyName(77, ""); this.baseImageList.Images.SetKeyName(78, ""); this.baseImageList.Images.SetKeyName(79, ""); // // grpSourceProject // this.grpSourceProject.Controls.Add(this.txtSourceProject); this.grpSourceProject.Controls.Add(this.lblSourceProject); this.grpSourceProject.Location = new System.Drawing.Point(7, 12); this.grpSourceProject.Name = "grpSourceProject"; this.grpSourceProject.Size = new System.Drawing.Size(476, 74); this.grpSourceProject.TabIndex = 8; this.grpSourceProject.TabStop = false; this.grpSourceProject.Text = "Source Project"; // // txtSourceProject // this.txtSourceProject.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtSourceProject.Enabled = false; this.txtSourceProject.Location = new System.Drawing.Point(15, 37); this.txtSourceProject.Name = "txtSourceProject"; this.txtSourceProject.Size = new System.Drawing.Size(447, 20); this.txtSourceProject.TabIndex = 5; // // lblSourceProject // this.lblSourceProject.AutoSize = true; this.lblSourceProject.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.lblSourceProject.Location = new System.Drawing.Point(12, 21); this.lblSourceProject.Name = "lblSourceProject"; this.lblSourceProject.Size = new System.Drawing.Size(72, 13); this.lblSourceProject.TabIndex = 4; this.lblSourceProject.Text = "Source Name"; // // ProjectUpgradeDialog // this.ClientSize = new System.Drawing.Size(493, 427); this.Controls.Add(this.grpSourceProject); this.Name = "ProjectUpgradeDialog"; this.Text = "Import Project"; this.Load += new System.EventHandler(this.ProjectImportDialog_Load); this.Controls.SetChildIndex(this.btnOk, 0); this.Controls.SetChildIndex(this.btnCancel, 0); this.Controls.SetChildIndex(this.btnHelp, 0); this.Controls.SetChildIndex(this.grpSourceProject, 0); this.Controls.SetChildIndex(this.grpData, 0); this.Controls.SetChildIndex(this.grpProject, 0); this.Controls.SetChildIndex(this.lblMetadata, 0); this.Controls.SetChildIndex(this.btnBuildMetadataConnectionString, 0); this.Controls.SetChildIndex(this.txtMetadata, 0); this.Controls.SetChildIndex(this.grpMetadata, 0); this.Controls.SetChildIndex(this.grpView, 0); this.Controls.SetChildIndex(this.cbxMetadataDriver, 0); this.grpProject.ResumeLayout(false); this.grpProject.PerformLayout(); this.grpData.ResumeLayout(false); this.grpData.PerformLayout(); this.grpView.ResumeLayout(false); this.grpView.PerformLayout(); this.grpMetadata.ResumeLayout(false); this.grpMetadata.PerformLayout(); this.grpSourceProject.ResumeLayout(false); this.grpSourceProject.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox grpSourceProject; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.TextBox txtSourceProject; /// <summary> /// Control exposed to derived class for UI inheritance /// </summary> protected System.Windows.Forms.Label lblSourceProject; } }
50.146617
163
0.58745
[ "Apache-2.0" ]
Epi-Info/Epi-Info-Community-Edition
Epi.Windows.ImportExport/Dialogs/ProjectUpgradeDialog.Designer.cs
13,339
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201 { using Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell; /// <summary> /// Current TCP connectivity information from the Kusto cluster to a single endpoint. /// </summary> [System.ComponentModel.TypeConverter(typeof(EndpointDetailTypeConverter))] public partial class EndpointDetail { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.EndpointDetail" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IEndpointDetail" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IEndpointDetail DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new EndpointDetail(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.EndpointDetail" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IEndpointDetail" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IEndpointDetail DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new EndpointDetail(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.EndpointDetail" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal EndpointDetail(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Port")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IEndpointDetailInternal)this).Port = (int?) content.GetValueForProperty("Port",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IEndpointDetailInternal)this).Port, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.EndpointDetail" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal EndpointDetail(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Port")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IEndpointDetailInternal)this).Port = (int?) content.GetValueForProperty("Port",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IEndpointDetailInternal)this).Port, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } AfterDeserializePSObject(content); } /// <summary> /// Creates a new instance of <see cref="EndpointDetail" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IEndpointDetail FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Current TCP connectivity information from the Kusto cluster to a single endpoint. [System.ComponentModel.TypeConverter(typeof(EndpointDetailTypeConverter))] public partial interface IEndpointDetail { } }
59.097222
323
0.672033
[ "MIT" ]
AlanFlorance/azure-powershell
src/Kusto/generated/api/Models/Api20220201/EndpointDetail.PowerShell.cs
8,367
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.V20160810.Outputs { [OutputType] public sealed class VMNicDetailsResponse { /// <summary> /// Ip address type. /// </summary> public readonly string? IpAddressType; /// <summary> /// The nic Id. /// </summary> public readonly string? NicId; /// <summary> /// Primary nic static IP address. /// </summary> public readonly string? PrimaryNicStaticIPAddress; /// <summary> /// IP allocation type for recovery VM. /// </summary> public readonly string? RecoveryNicIpAddressType; /// <summary> /// Recovery VM network Id. /// </summary> public readonly string? RecoveryVMNetworkId; /// <summary> /// Recovery VM subnet name. /// </summary> public readonly string? RecoveryVMSubnetName; /// <summary> /// The replica nic Id. /// </summary> public readonly string? ReplicaNicId; /// <summary> /// Replica nic static IP address. /// </summary> public readonly string? ReplicaNicStaticIPAddress; /// <summary> /// Selection type for failover. /// </summary> public readonly string? SelectionType; /// <summary> /// The source nic ARM Id. /// </summary> public readonly string? SourceNicArmId; /// <summary> /// VM network name. /// </summary> public readonly string? VMNetworkName; /// <summary> /// VM subnet name. /// </summary> public readonly string? VMSubnetName; [OutputConstructor] private VMNicDetailsResponse( string? ipAddressType, string? nicId, string? primaryNicStaticIPAddress, string? recoveryNicIpAddressType, string? recoveryVMNetworkId, string? recoveryVMSubnetName, string? replicaNicId, string? replicaNicStaticIPAddress, string? selectionType, string? sourceNicArmId, string? vMNetworkName, string? vMSubnetName) { IpAddressType = ipAddressType; NicId = nicId; PrimaryNicStaticIPAddress = primaryNicStaticIPAddress; RecoveryNicIpAddressType = recoveryNicIpAddressType; RecoveryVMNetworkId = recoveryVMNetworkId; RecoveryVMSubnetName = recoveryVMSubnetName; ReplicaNicId = replicaNicId; ReplicaNicStaticIPAddress = replicaNicStaticIPAddress; SelectionType = selectionType; SourceNicArmId = sourceNicArmId; VMNetworkName = vMNetworkName; VMSubnetName = vMSubnetName; } } }
29.820755
81
0.586523
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/RecoveryServices/V20160810/Outputs/VMNicDetailsResponse.cs
3,161
C#
using System.Linq; namespace TorrentExtractor.Qbittorrent.ConsoleApp.Helpers { public static class ArgsHelper { public static string[] RemoveEmptyArgs(string[] args) { for (var index = 0; index < args.Length; index++) { if (!args[index].StartsWith("-")) continue; if ((index + 1) < args.Length && args[index + 1].StartsWith("-")) { // remove empty arg args = args.Where(c => c != args[index]).ToArray(); index--; } else if ((index + 1) == args.Length && args[index].StartsWith("-")) { // remove last empty arg args = args.Where(c => c != args[index]).ToArray(); } } return args; } } }
29.5
83
0.437288
[ "MIT" ]
plneto/TorrentExtractor
src/TorrentExtractor.Qbittorrent.ConsoleApp/Helpers/ArgsHelper.cs
887
C#
using System; using Android.Content; using Android.Widget; namespace MonoDroid.Dialog { public class DialogHelper { private Context context; private RootElement formLayer; //public event Action<Section, Element> ElementClick; //public event Action<Section, Element> ElementLongClick; public RootElement Root { get; set; } private DialogAdapter DialogAdapter { get; set; } public DialogHelper(Context context, ListView dialogView, RootElement root) { this.Root = root; this.Root.Context = context; dialogView.Adapter = this.DialogAdapter = new DialogAdapter(context, this.Root); dialogView.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs>(ListView_ItemClick); dialogView.ItemLongClick += ListView_ItemLongClick; dialogView.Scroll += delegate(object sender, AbsListView.ScrollEventArgs e) { Console.WriteLine( "Item Count " + e.View.Count ); }; dialogView.Tag = root; } void ListView_ItemLongClick (object sender, AdapterView.ItemLongClickEventArgs e) { var elem = this.DialogAdapter.ElementAtIndex(e.Position); if (elem != null && elem.LongClick != null) { elem.LongClick(); } } void ListView_ItemClick (object sender, AdapterView.ItemClickEventArgs e) { var elem = this.DialogAdapter.ElementAtIndex(e.Position); if(elem != null) elem.Selected(); } public void ReloadData() { if(Root == null) { return; } this.DialogAdapter.ReloadData(); } } }
30.661017
105
0.585406
[ "MIT" ]
drubin/c-sharp
mono-for-android/3.4/Pubnub-Messaging/MonoDroid.Dialog/DialogHelper.cs
1,811
C#
// <copyright> // Copyright by the Spark Development Network // // Licensed under the Rock Community License (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.rockrms.com/license // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // // <notice> // This file contains modifications by Kingdom First Solutions // and is a derivative work. // // Modification (including but not limited to): // * Allows person impersonation via url for checkin manager purposes. // </notice> // using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Rock; using Rock.Attribute; using Rock.Data; using Rock.Lava; using Rock.Model; using Rock.Web.Cache; using Rock.Web.UI; using Rock.Web.UI.Controls; namespace RockWeb.Plugins.rocks_kfs.Cms { /// <summary> /// </summary> [DisplayName( "Public Profile Edit" )] [Category( "KFS > CMS" )] [Description( "Public block for users to manage their accounts. The KFS Version allows for Person Impersonation." )] #region "Block Attributes" [DefinedValueField( "Default Connection Status", Key = AttributeKey.DefaultConnectionStatus, Description = "The connection status that should be set by default", DefinedTypeGuid = Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS, IsRequired = false, AllowMultiple = false, Order = 0 )] [BooleanField( "Disable Name Edit", Key = AttributeKey.DisableNameEdit, Description = "Whether the First and Last Names can be edited.", DefaultBooleanValue = false, Order = 1 )] [BooleanField( "Show Title", Key = AttributeKey.ShowTitle, Description = "Whether to show the person's title (e.g. Mr., Mrs. etc...)", DefaultBooleanValue = true, Order = 2 )] [BooleanField( "Show Suffix", Key = AttributeKey.ShowSuffix, Description = "Whether to show the person's suffix (e.g. Roman Numerals, Jr., Ph.D., etc...)", DefaultBooleanValue = true, Order = 3 )] [BooleanField( "Show Nick Name", Key = AttributeKey.ShowNickName, Description = "Whether to show the person's Nickname in addition to the First Name.", DefaultBooleanValue = true, Order = 4 )] [BooleanField( "View Only", Key = AttributeKey.ViewOnly, Description = "Should people be prevented from editing their profile or family records?", DefaultBooleanValue = false, Order = 5 )] [BooleanField( "Show Family Members", Key = AttributeKey.ShowFamilyMembers, Description = "Whether family members are shown or not.", DefaultBooleanValue = true, Order = 6 )] [GroupLocationTypeField( "Address Type", Key = AttributeKey.AddressTypeValueGuid, Description = "The type of address to be displayed / edited.", GroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY, IsRequired = false, DefaultValue = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME, Order = 7 )] [BooleanField( "Show Phone Numbers", Key = AttributeKey.ShowPhoneNumbers, Description = "Allows hiding the phone numbers.", DefaultBooleanValue = false, Order = 8 )] [DefinedValueField( "Phone Types", Key = AttributeKey.PhoneTypeValueGuids, Description = "The types of phone numbers to display / edit.", DefinedTypeGuid = Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE, IsRequired = false, AllowMultiple = true, DefaultValue = Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME, Order = 9 )] [BooleanField( "Highlight Mobile Phone", Key = AttributeKey.HighlightMobilePhone, Description = "Determines if the emphasis box should be placed around the mobile number.", DefaultBooleanValue = true, Order = 10 )] [TextField( "Mobile Highlight Title", Key = AttributeKey.MobileHighlightTitle, Description = "The text to use for the mobile highlight title (only displayed if Highlight Mobile Phone is selected).", IsRequired = false, DefaultValue = "Help Us Keep You Informed", Order = 11 )] [TextField( "Mobile Highlight Text", Description = "The text to use for the mobile highlight text (only displayed if Highlight Mobile Phone is selected).", IsRequired = false, DefaultValue = "Help us keep you in the loop by providing your mobile phone number and opting in for text messages. We'll only send you the most important information at this number.", Order = 12, Key = AttributeKey.MobileHighlightText )] [DefinedValueField( "Required Adult Phone Types", Key = AttributeKey.RequiredAdultPhoneTypes, Description = "The phone numbers that are required when editing an adult record.", DefinedTypeGuid = Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE, IsRequired = false, AllowMultiple = true, Order = 13 )] [BooleanField( "Require Adult Email Address", Key = AttributeKey.RequireAdultEmailAddress, Description = "Require an email address on adult records", DefaultBooleanValue = true, Order = 14 )] [BooleanField( "Show Communication Preference", Key = AttributeKey.ShowCommunicationPreference, Description = "Show the communication preference and allow it to be edited", DefaultBooleanValue = true, Order = 15 )] [LinkedPage( "Workflow Launch Page", Key = AttributeKey.RequestChangesPage, Description = "Page used to launch the workflow to make a profile change request", IsRequired = false, Order = 16 )] [TextField( "Request Changes Text", Key = AttributeKey.RequestChangesText, Description = "The text to use for the request changes button (only displayed if there is a 'Workflow Launch Page' configured).", IsRequired = false, DefaultValue = "Request Additional Changes", Order = 17 )] [AttributeField( "Family Attributes", Key = AttributeKey.FamilyAttributes, EntityTypeGuid = Rock.SystemGuid.EntityType.GROUP, EntityTypeQualifierColumn = "GroupTypeId", EntityTypeQualifierValue = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY, Description = "The family attributes that should be displayed / edited.", IsRequired = false, AllowMultiple = true, Order = 18 )] [AttributeField( "Person Attributes (adults)", Key = AttributeKey.PersonAttributesAdults, EntityTypeGuid = Rock.SystemGuid.EntityType.PERSON, Description = "The person attributes that should be displayed / edited for adults.", IsRequired = false, AllowMultiple = true, Order = 19 )] [AttributeField( "Person Attributes (children)", Key = AttributeKey.PersonAttributesChildren, EntityTypeGuid = Rock.SystemGuid.EntityType.PERSON, Description = "The person attributes that should be displayed / edited for children.", IsRequired = false, AllowMultiple = true, Order = 20 )] [BooleanField( "Show Campus Selector", Key = AttributeKey.ShowCampusSelector, Description = "Allows selection of primary campus.", DefaultBooleanValue = false, Order = 21 )] [TextField( "Campus Selector Label", Key = AttributeKey.CampusSelectorLabel, Description = "The label for the campus selector (only effective when \"Show Campus Selector\" is enabled).", IsRequired = false, DefaultValue = "Campus", Order = 22 )] [BooleanField( "Require Gender", Key = AttributeKey.RequireGender, Description = "Controls whether or not the gender field is required.", IsRequired = true, DefaultBooleanValue = true, Order = 23 )] [CodeEditorField( "View Template", Key = AttributeKey.ViewTemplate, Description = "The lava template to use to format the view details.", EditorMode = CodeEditorMode.Lava, EditorTheme = CodeEditorTheme.Rock, EditorHeight = 400, IsRequired = true, DefaultValue = "{% include '~/Assets/Lava/PublicProfile.lava' %}", Order = 24 )] [BooleanField( "Impersonation", TrueText = "Allow (only use on an internal page used by staff)", FalseText = "Don't Allow", Description = "Should the current user be able to view and edit other people's transactions? IMPORTANT: This should only be enabled on an internal page that is secured to trusted users", DefaultValue = "false", Order = 25 )] #endregion public partial class PublicProfileEdit : RockBlock { private static class AttributeKey { public const string DefaultConnectionStatus = "DefaultConnectionStatus"; public const string DisableNameEdit = "DisableNameEdit"; public const string ShowTitle = "ShowTitle"; public const string ShowSuffix = "ShowSuffix"; public const string ShowNickName = "ShowNickName"; public const string ViewOnly = "ViewOnly"; public const string ShowFamilyMembers = "ShowFamilyMembers"; public const string AddressTypeValueGuid = "AddressType"; public const string ShowPhoneNumbers = "ShowPhoneNumbers"; public const string PhoneTypeValueGuids = "PhoneNumbers"; public const string HighlightMobilePhone = "HighlightMobilePhone"; public const string MobileHighlightTitle = "MobileHighlightTitle"; public const string MobileHighlightText = "MobileHighlightText"; public const string RequiredAdultPhoneTypes = "RequiredAdultPhoneTypes"; public const string RequireAdultEmailAddress = "RequireAdultEmailAddress"; public const string ShowCommunicationPreference = "ShowCommunicationPreference"; public const string RequestChangesPage = "WorkflowLaunchPage"; public const string RequestChangesText = "RequestChangesText"; public const string FamilyAttributes = "FamilyAttributes"; public const string PersonAttributesAdults = "PersonAttributes(adults)"; public const string PersonAttributesChildren = "PersonAttributes(children)"; public const string ShowCampusSelector = "ShowCampusSelector"; public const string CampusSelectorLabel = "CampusSelectorLabel"; public const string RequireGender = "RequireGender"; public const string ViewTemplate = "ViewTemplate"; public const string Impersonation = "Impersonation"; } private static class MergeFieldKey { /// <summary> /// If only View mode should be enabled. /// If this is true, the Edit button should not be visible /// </summary> public const string ViewOnly = "ViewOnly"; /// <summary> /// The family that is currently selected (the person could be in multiple families). /// <see cref="Rock.Model.Group" /> /// </summary> public const string Family = "Family"; /// <summary> /// True if Family Members should be listed /// </summary> public const string ShowFamilyMembers = "ShowFamilyMembers"; /// <summary> /// The members of the selected family. /// List of <see cref="Rock.Model.GroupMember"/> /// </summary> public const string FamilyMembers = "FamilyMembers"; /// <summary> /// The families that this person is in. /// List <see cref="Rock.Model.Group" /> /// </summary> public const string Families = "Families"; /// <summary> /// The address type defined value id that is displayed. /// <see cref="DefinedValueCache">DefinedValue Id</see> /// </summary> public const string AddressTypeValueId = "AddressTypeValueId"; /// <summary> /// The address to be displayed. /// <see cref="Rock.Model.GroupLocation"/> /// </summary> public const string Address = "Address"; /// <summary> /// True if phone numbers should be shown /// </summary> public const string ShowPhoneNumbers = "ShowPhoneNumbers"; /// <summary> /// The Phone Types defined value ids that should be shown. /// List of <see cref="DefinedValueCache">DefinedValue Id</see> /// </summary> public const string DisplayedPhoneTypeValueIds = "DisplayedPhoneTypeValueIds"; /// <summary> /// The URL to use when they press the Request Changes button /// </summary> public const string RequestChangesPageUrl = "RequestChangesPageUrl"; /// <summary> /// The text to shown on the Request Changes button /// Only show the button if <see cref="RequestChangesPageUrl"/> has a value /// </summary> public const string RequestChangesText = "RequestChangesText"; /// <summary> /// The family attributes that should be displayed. /// List of <see cref="AttributeCache" /> /// </summary> public const string FamilyAttributes = "FamilyAttributes"; /// <summary> /// The person attributes that should be displayed for Adults /// List of <see cref="AttributeCache" /> /// </summary> public const string PersonAttributesAdults = "PersonAttributesAdults"; /// The person attributes that should be displayed for Children /// List of <see cref="AttributeCache" /> /// </summary> public const string PersonAttributesChildren = "PersonAttributesChildren"; } private static class EventArgumentKey { public const string SelectFamily = "SelectFamily"; public const string EditPerson = "EditPerson"; public const string AddGroupMember = "AddGroupMember"; } #region Fields private List<Guid> _requiredPhoneNumberGuids = new List<Guid>(); private bool _isEditRecordAdult = false; #endregion #region Properties private Person _person = null; #endregion #region Base Control Methods /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit( EventArgs e ) { base.OnInit( e ); ScriptManager.RegisterStartupScript( ddlGradePicker, ddlGradePicker.GetType(), "grade-selection-" + BlockId.ToString(), ddlGradePicker.GetJavascriptForYearPicker( ypGraduation ), true ); dvpTitle.DefinedTypeId = DefinedTypeCache.Get( new Guid( Rock.SystemGuid.DefinedType.PERSON_TITLE ) ).Id; dvpTitle.Visible = GetAttributeValue( AttributeKey.ShowTitle ).AsBoolean(); dvpSuffix.DefinedTypeId = DefinedTypeCache.Get( new Guid( Rock.SystemGuid.DefinedType.PERSON_SUFFIX ) ).Id; dvpSuffix.Visible = GetAttributeValue( AttributeKey.ShowSuffix ).AsBoolean(); tbNickName.Visible = GetAttributeValue( AttributeKey.ShowNickName ).AsBoolean(); RockPage.AddCSSLink( "~/Styles/fluidbox.css" ); RockPage.AddScriptLink( "~/Scripts/imagesloaded.min.js" ); RockPage.AddScriptLink( "~/Scripts/jquery.fluidbox.min.js" ); // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it this.BlockUpdated += PublicProfileEdit_BlockUpdated; this.AddConfigurationUpdateTrigger( upContent ); cpCampus.Label = GetAttributeValue( AttributeKey.CampusSelectorLabel ); if ( !string.IsNullOrWhiteSpace( GetAttributeValue( AttributeKey.RequiredAdultPhoneTypes ) ) ) { _requiredPhoneNumberGuids = GetAttributeValue( AttributeKey.RequiredAdultPhoneTypes ).Split( ',' ).Select( Guid.Parse ).ToList(); } rContactInfo.ItemDataBound += rContactInfo_ItemDataBound; string smsScript = @" $('.js-sms-number').click(function () { if ($(this).is(':checked')) { $('.js-sms-number').not($(this)).prop('checked', false); } }); "; ScriptManager.RegisterStartupScript( rContactInfo, rContactInfo.GetType(), "sms-number-" + BlockId.ToString(), smsScript, true ); // If impersonation is allowed, and a valid person key was used, set the target to that person if ( GetAttributeValue( "Impersonation" ).AsBooleanOrNull() ?? false ) { string personKey = PageParameter( "Person" ); if ( !string.IsNullOrWhiteSpace( personKey ) ) { var rockContext = new RockContext(); _person = new PersonService( rockContext ).GetByUrlEncodedKey( personKey ); } } if ( _person == null ) { _person = CurrentPerson; } } /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); if ( _person == null ) { pnlView.Visible = false; pnlEdit.Visible = false; pnlEdit.Visible = false; nbNotAuthorized.Visible = true; return; } if ( !Page.IsPostBack ) { ShowViewDetail(); } else { var handled = HandleLavaPostback( this.Request.Params["__EVENTTARGET"], this.Request.Params["__EVENTARGUMENT"] ); } } /// <summary> /// Handles the BlockUpdated event of the PublicProfileEdit control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void PublicProfileEdit_BlockUpdated( object sender, EventArgs e ) { ShowViewDetail(); } /// <summary> /// Handles any custom postbacks from the Lava. /// Returns true if one of the custom Lava postbacks was handled /// </summary> /// <param name="eventTarget">The event target.</param> /// <param name="eventArgument">The event argument.</param> /// <returns></returns> private bool HandleLavaPostback( string eventTarget, string eventArgument ) { if ( !eventTarget.Equals( upContent.UniqueID, StringComparison.OrdinalIgnoreCase ) ) { // post back from some other block return false; } var eventArgumentParts = eventArgument.Split( '^' ); if ( !eventArgumentParts.Any() ) { return false; } var eventArgumentKey = eventArgumentParts[0]; var eventArgumentValue = eventArgumentParts.Length > 1 ? eventArgumentParts[1] : string.Empty; if ( eventArgumentKey == EventArgumentKey.SelectFamily ) { hfGroupId.Value = this.Request.Form["selectFamily"]; ShowViewDetail(); return true; } else if ( eventArgumentKey == EventArgumentKey.EditPerson ) { ShowEditPersonDetails( eventArgumentValue.AsGuid() ); return true; } else if ( eventArgumentKey == EventArgumentKey.AddGroupMember ) { AddGroupMember( eventArgumentValue.AsInteger() ); return true; } return false; } /// <summary> /// Shows the detail. /// </summary> private void ShowViewDetail() { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService( rockContext ); var attributeValueService = new AttributeValueService( rockContext ); // invalid situation; return and report nothing. if ( _person == null ) { return; } var mergeFields = LavaHelper.GetCommonMergeFields( this.RockPage, _person ); var personFamilies = _person.GetFamilies(); Group selectedFamily; var selectedGroupId = hfGroupId.Value.AsIntegerOrNull(); if ( selectedGroupId.HasValue ) { selectedFamily = personFamilies.FirstOrDefault( a => a.Id == selectedGroupId ); } else { selectedFamily = _person.GetFamily(); } if ( selectedFamily == null ) { selectedFamily = _person.GetFamily(); } hfGroupId.Value = selectedFamily.Id.ToString(); mergeFields.Add( MergeFieldKey.Family, selectedFamily ); var familyMembers = groupMemberService.Queryable() .Where( gm => gm.GroupId == selectedFamily.Id && gm.PersonId != _person.Id && gm.Person.IsDeceased == false ) .OrderBy( m => m.GroupRole.Order ) .ToList(); var orderedMembers = new List<GroupMember>(); // Add adult males orderedMembers.AddRange( familyMembers .Where( m => m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) && m.Person.Gender == Gender.Male ) .OrderByDescending( m => m.Person.Age ) ); // Add adult females orderedMembers.AddRange( familyMembers .Where( m => m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) && m.Person.Gender != Gender.Male ) .OrderByDescending( m => m.Person.Age ) ); // Add non-adults orderedMembers.AddRange( familyMembers .Where( m => !m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) ) .OrderByDescending( m => m.Person.Age ) ); mergeFields.Add( MergeFieldKey.FamilyMembers, orderedMembers ); mergeFields.Add( MergeFieldKey.ShowFamilyMembers, GetAttributeValue( AttributeKey.ShowFamilyMembers ).AsBoolean() ); mergeFields.Add( MergeFieldKey.Families, personFamilies ); mergeFields.Add( MergeFieldKey.ViewOnly, GetAttributeValue( AttributeKey.ViewOnly ).AsBoolean() ); mergeFields.Add( MergeFieldKey.AddressTypeValueId, DefinedValueCache.GetId( GetAttributeValue( AttributeKey.AddressTypeValueGuid ).AsGuid() ) ); var groupLocationTypeValueGuid = this.GetAttributeValue( AttributeKey.AddressTypeValueGuid ).AsGuidOrNull() ?? Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid(); var groupLocationTypeValueId = DefinedValueCache.GetId( groupLocationTypeValueGuid ); if ( groupLocationTypeValueId.HasValue ) { var familyGroupLocation = selectedFamily.GroupLocations.Where( a => a.GroupLocationTypeValueId == groupLocationTypeValueId.Value ).FirstOrDefault(); mergeFields.Add( MergeFieldKey.Address, familyGroupLocation ); } mergeFields.Add( MergeFieldKey.ShowPhoneNumbers, GetAttributeValue( AttributeKey.ShowPhoneNumbers ).AsBoolean() ); var phoneTypeValueIds = GetAttributeValues( AttributeKey.PhoneTypeValueGuids ).AsGuidList().Select( a => DefinedValueCache.GetId( a ) ).ToList(); mergeFields.Add( MergeFieldKey.DisplayedPhoneTypeValueIds, phoneTypeValueIds ); var requestChangesPageUrl = LinkedPageUrl( AttributeKey.RequestChangesPage, new Dictionary<string, string>() ); mergeFields.Add( MergeFieldKey.RequestChangesPageUrl, requestChangesPageUrl ); mergeFields.Add( MergeFieldKey.RequestChangesText, GetAttributeValue( AttributeKey.RequestChangesText ) ); var familyAttributes = GetAttributeValues( AttributeKey.FamilyAttributes ).AsGuidList().Select( a => AttributeCache.Get( a ) ); mergeFields.Add( MergeFieldKey.FamilyAttributes, familyAttributes ); mergeFields.Add( MergeFieldKey.PersonAttributesChildren, GetAttributeValues( AttributeKey.PersonAttributesChildren ).AsGuidList().Select( a => AttributeCache.Get( a ) ) ); mergeFields.Add( MergeFieldKey.PersonAttributesAdults, GetAttributeValues( AttributeKey.PersonAttributesAdults ).AsGuidList().Select( a => AttributeCache.Get( a ) ) ); var viewPersonLavaTemplate = GetAttributeValue( AttributeKey.ViewTemplate ); var viewPersonHtml = viewPersonLavaTemplate.ResolveMergeFields( mergeFields, _person ).ResolveClientIds( upContent.UniqueID ); lViewPersonContent.Visible = true; lViewPersonContent.Text = viewPersonHtml; hfEditPersonGuid.Value = Guid.Empty.ToString(); pnlEdit.Visible = false; pnlView.Visible = true; rblRole.Items.Clear(); var familyRoles = selectedFamily.GroupType.Roles.OrderBy( r => r.Order ).ToList(); foreach ( var role in familyRoles ) { rblRole.Items.Add( new ListItem( role.Name, role.Id.ToString() ) ); } rblRole.SetValue( _person.GetFamilyRole() ); } /// <summary> /// Verifies whether the current person is in the given group (Family). /// </summary> /// <param name="group">The group.</param> /// <returns> /// <c>true</c> if the current person is in the group; otherwise, <c>false</c>. /// </returns> private bool IsCurrentPersonInGroup( Group group ) { if ( group == null ) { return false; } return group.Members.Where( gm => gm.PersonId == _person.Id ).Any(); } /// <summary> /// Verifies that the personGuid (if not empty) or the given person is a member of the given group. /// </summary> /// <param name="person">The person.</param> /// <param name="group">The group.</param> private bool IsValidPersonForGroup( Guid personGuid, Person person, Group group ) { if ( personGuid == Guid.Empty ) { // When the personGuid is empty, then we check based on the given person's Id is in the group. return IsValidPersonForGroup( person, group ); } else { // Is the given person (their guid) in the group? return group.Members.Where( gm => gm.Person.Guid == personGuid ).Any(); } } /// <summary> /// Verifies the given person's Id is a member of the given group. /// </summary> /// <param name="person">The person.</param> /// <param name="group">The group.</param> private bool IsValidPersonForGroup( Person person, Group group ) { // Is the given person' (their Id) in the group? return group.Members.Where( gm => gm.PersonId == person.Id ).Any(); } #endregion #region Events #region View Events /// <summary> /// Handles the Click event of the lbEditPerson control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbEditPerson_Click( object sender, EventArgs e ) { ShowEditPersonDetails( _person.Guid ); } /// <summary> /// Handles the Click event of the lbMoved control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbMoved_Click( object sender, EventArgs e ) { if ( !string.IsNullOrWhiteSpace( acAddress.Street1 ) ) { hfStreet1.Value = acAddress.Street1; hfStreet2.Value = acAddress.Street2; hfCity.Value = acAddress.City; hfState.Value = acAddress.State; hfPostalCode.Value = acAddress.PostalCode; hfCountry.Value = acAddress.Country; Location currentAddress = new Location(); acAddress.Required = true; acAddress.GetValues( currentAddress ); lPreviousAddress.Text = string.Format( "<strong>Previous Address</strong><br />{0}", currentAddress.FormattedHtmlAddress ); acAddress.Street1 = string.Empty; acAddress.Street2 = string.Empty; acAddress.PostalCode = string.Empty; acAddress.City = string.Empty; cbIsMailingAddress.Checked = true; cbIsPhysicalAddress.Checked = true; } } /// <summary> /// Handles the Click event of the lbAddGroupMember control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void AddGroupMember( int groupId ) { ShowEditPersonDetails( Guid.Empty ); } #endregion /// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); var personGuid = hfEditPersonGuid.Value.AsGuid(); if ( !hfGroupId.Value.AsIntegerOrNull().HasValue ) { return; } var groupId = hfGroupId.Value.AsIntegerOrNull(); if ( !groupId.HasValue ) { // invalid situation/tampering; return and report nothing. } var group = new GroupService( rockContext ).Get( groupId.Value ); if ( group == null ) { // invalid situation/tampering; return and report nothing. } // invalid situation; return and report nothing. if ( !IsCurrentPersonInGroup( group ) ) { return; } // Validate before continuing; either the personGuid or the CurrentPerson must be in the group. if ( !IsValidPersonForGroup( personGuid, _person, group ) ) { return; } bool showPhoneNumbers = GetAttributeValue( AttributeKey.ShowPhoneNumbers ).AsBoolean(); bool showCommunicationPreference = GetAttributeValue( AttributeKey.ShowCommunicationPreference ).AsBoolean(); var communicationPreference = rblCommunicationPreference.SelectedValueAsEnum<CommunicationType>(); var wrapTransactionResult = rockContext.WrapTransactionIf( () => { var personService = new PersonService( rockContext ); if ( personGuid == Guid.Empty ) { var groupMemberService = new GroupMemberService( rockContext ); var groupMember = new GroupMember() { Person = new Person(), Group = group, GroupId = group.Id }; groupMember.Person.TitleValueId = dvpTitle.SelectedValueAsId(); groupMember.Person.FirstName = tbFirstName.Text; groupMember.Person.NickName = tbNickName.Text; groupMember.Person.LastName = tbLastName.Text; groupMember.Person.SuffixValueId = dvpSuffix.SelectedValueAsId(); groupMember.Person.Gender = rblGender.SelectedValueAsEnum<Gender>(); DateTime? birthdate = bpBirthDay.SelectedDate; if ( birthdate.HasValue ) { // If setting a future birthdate, subtract a century until birthdate is not greater than today. var today = RockDateTime.Today; while ( birthdate.Value.CompareTo( today ) > 0 ) { birthdate = birthdate.Value.AddYears( -100 ); } } groupMember.Person.SetBirthDate( birthdate ); if ( ddlGradePicker.Visible ) { groupMember.Person.GradeOffset = ddlGradePicker.SelectedValueAsInt(); } var role = group.GroupType.Roles.Where( r => r.Id == ( rblRole.SelectedValueAsInt() ?? 0 ) ).FirstOrDefault(); if ( role != null ) { groupMember.GroupRole = role; groupMember.GroupRoleId = role.Id; } var connectionStatusGuid = GetAttributeValue( AttributeKey.DefaultConnectionStatus ).AsGuidOrNull(); if ( connectionStatusGuid.HasValue ) { groupMember.Person.ConnectionStatusValueId = DefinedValueCache.Get( connectionStatusGuid.Value ).Id; } else { groupMember.Person.ConnectionStatusValueId = _person.ConnectionStatusValueId; } var headOfHousehold = GroupServiceExtensions.HeadOfHousehold( group.Members.AsQueryable() ); if ( headOfHousehold != null ) { DefinedValueCache dvcRecordStatus = DefinedValueCache.Get( headOfHousehold.RecordStatusValueId ?? 0 ); if ( dvcRecordStatus != null ) { groupMember.Person.RecordStatusValueId = dvcRecordStatus.Id; } } if ( groupMember.GroupRole.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) { groupMember.Person.GivingGroupId = group.Id; } groupMember.Person.IsEmailActive = true; groupMember.Person.EmailPreference = EmailPreference.EmailAllowed; groupMember.Person.RecordTypeValueId = DefinedValueCache.Get( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; groupMemberService.Add( groupMember ); rockContext.SaveChanges(); personGuid = groupMember.Person.Guid; } var person = personService.Get( personGuid ); if ( person != null ) { int? orphanedPhotoId = null; if ( person.PhotoId != imgPhoto.BinaryFileId ) { orphanedPhotoId = person.PhotoId; person.PhotoId = imgPhoto.BinaryFileId; } person.TitleValueId = dvpTitle.SelectedValueAsInt(); person.FirstName = tbFirstName.Text; person.NickName = tbNickName.Text; person.LastName = tbLastName.Text; person.SuffixValueId = dvpSuffix.SelectedValueAsInt(); var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; var birthday = bpBirthDay.SelectedDate; if ( birthday.HasValue ) { // If setting a future birthdate, subtract a century until birthdate is not greater than today. var today = RockDateTime.Today; while ( birthday.Value.CompareTo( today ) > 0 ) { birthday = birthday.Value.AddYears( -100 ); } person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if ( birthday.Value.Year != DateTime.MinValue.Year ) { person.BirthYear = birthday.Value.Year; } else { person.BirthYear = null; } } else { person.SetBirthDate( null ); } if ( ddlGradePicker.Visible ) { int? graduationYear = null; if ( ypGraduation.SelectedYear.HasValue ) { graduationYear = ypGraduation.SelectedYear.Value; } person.GraduationYear = graduationYear; } person.Gender = rblGender.SelectedValue.ConvertToEnum<Gender>(); // update campus // bool showCampus = GetAttributeValue( AttributeKey.ShowCampusSelector ).AsBoolean(); // Even if the block is set to show the picker it will not be visible if there is only one campus so use the Visible prop instead of the attribute value here. if ( cpCampus.Visible ) { var primaryFamily = person.GetFamily( rockContext ); if ( primaryFamily.CampusId != cpCampus.SelectedCampusId ) { primaryFamily.CampusId = cpCampus.SelectedCampusId; } } if ( showPhoneNumbers ) { var phoneNumberTypeIds = new List<int>(); bool smsSelected = false; foreach ( RepeaterItem item in rContactInfo.Items ) { HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField; PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox; CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox; if ( hfPhoneType != null && pnbPhone != null && cbSms != null ) { if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) ) { int phoneNumberTypeId; if ( int.TryParse( hfPhoneType.Value, out phoneNumberTypeId ) ) { var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberTypeId ); string oldPhoneNumber = string.Empty; if ( phoneNumber == null ) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add( phoneNumber ); } else { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); // Only allow one number to have SMS selected if ( smsSelected ) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumberTypeIds.Add( phoneNumberTypeId ); } } } } var selectedPhoneTypeGuids = GetAttributeValue( AttributeKey.PhoneTypeValueGuids ).Split( ',' ).AsGuidList(); // Remove any blank numbers var phoneNumberService = new PhoneNumberService( rockContext ); foreach ( var phoneNumber in person.PhoneNumbers .Where( n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains( n.NumberTypeValueId.Value ) && selectedPhoneTypeGuids.Contains( n.NumberTypeValue.Guid ) ) .ToList() ) { person.PhoneNumbers.Remove( phoneNumber ); phoneNumberService.Delete( phoneNumber ); } } person.Email = tbEmail.Text.Trim(); person.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>(); /* 2020-10-06 MDP To help prevent a person from setting their communication preference to SMS, even if they don't have an SMS number, we'll require an SMS number in these situations. The goal is to only enforce if they are able to do something about it. 1) The block is configured to show both 'Communication Preference' and 'Phone Numbers'. 2) Communication Preference is set to SMS Edge cases - Both #1 and #2 are true, but no Phone Types are selected in block settings. In this case, still enforce. Think of this as a block configuration issue (they shouldn't have configured it that way) - Person has an SMS phone number, but the block settings don't show it. We'll see if any of the Person's phone numbers have SMS, including ones that are not shown. So, they can set communication preference to SMS without getting a warning. NOTE: We might have already done a save changes at this point, but we are in a DB Transaction, so it'll get rolled back if we return false, with a warning message. */ if ( showCommunicationPreference && showPhoneNumbers && communicationPreference == CommunicationType.SMS ) { if ( !person.PhoneNumbers.Any( a => a.IsMessagingEnabled ) ) { nbCommunicationPreferenceWarning.Text = "A phone number with SMS enabled is required when Communication Preference is set to SMS."; nbCommunicationPreferenceWarning.NotificationBoxType = NotificationBoxType.Warning; nbCommunicationPreferenceWarning.Visible = true; return false; } } person.CommunicationPreference = communicationPreference; person.LoadAttributes(); if ( avcPersonAttributesAdult.Visible ) { avcPersonAttributesAdult.GetEditValues( person ); } else { avcPersonAttributesChild.GetEditValues( person ); } if ( person.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( orphanedPhotoId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( orphanedPhotoId.Value ); if ( binaryFile != null ) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; rockContext.SaveChanges(); } } // if they used the ImageEditor, and cropped it, the un-cropped file is still in BinaryFile. So clean it up if ( imgPhoto.CropBinaryFileId.HasValue ) { if ( imgPhoto.CropBinaryFileId != person.PhotoId ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( imgPhoto.CropBinaryFileId.Value ); if ( binaryFile != null && binaryFile.IsTemporary ) { string errorMessage; if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) ) { binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); } } } } } person.SaveAttributeValues( rockContext ); // save family information if ( pnlAddress.Visible ) { Guid? familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull(); if ( familyGroupTypeGuid.HasValue ) { var familyGroup = new GroupService( rockContext ) .Queryable() .Where( f => f.Id == groupId.Value && f.Members.Any( m => m.PersonId == person.Id ) ) .FirstOrDefault(); if ( familyGroup != null ) { Guid? addressTypeGuid = GetAttributeValue( AttributeKey.AddressTypeValueGuid ).AsGuidOrNull(); if ( addressTypeGuid.HasValue ) { var groupLocationService = new GroupLocationService( rockContext ); var dvHomeAddressType = DefinedValueCache.Get( addressTypeGuid.Value ); var familyAddress = groupLocationService.Queryable().Where( l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id ).FirstOrDefault(); if ( familyAddress != null && string.IsNullOrWhiteSpace( acAddress.Street1 ) ) { // delete the current address groupLocationService.Delete( familyAddress ); rockContext.SaveChanges(); } else { if ( !string.IsNullOrWhiteSpace( acAddress.Street1 ) ) { if ( familyAddress == null ) { familyAddress = new GroupLocation(); groupLocationService.Add( familyAddress ); familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id; familyAddress.GroupId = familyGroup.Id; familyAddress.IsMailingLocation = true; familyAddress.IsMappedLocation = true; } else if ( hfStreet1.Value != string.Empty ) { // user clicked move so create a previous address var previousAddress = new GroupLocation(); groupLocationService.Add( previousAddress ); var previousAddressValue = DefinedValueCache.Get( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid() ); if ( previousAddressValue != null ) { previousAddress.GroupLocationTypeValueId = previousAddressValue.Id; previousAddress.GroupId = familyGroup.Id; Location previousAddressLocation = new Location(); previousAddressLocation.Street1 = hfStreet1.Value; previousAddressLocation.Street2 = hfStreet2.Value; previousAddressLocation.City = hfCity.Value; previousAddressLocation.State = hfState.Value; previousAddressLocation.PostalCode = hfPostalCode.Value; previousAddressLocation.Country = hfCountry.Value; previousAddress.Location = previousAddressLocation; } } familyAddress.IsMailingLocation = cbIsMailingAddress.Checked; familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked; var loc = new Location(); acAddress.GetValues( loc ); familyAddress.Location = new LocationService( rockContext ).Get( loc.Street1, loc.Street2, loc.City, loc.State, loc.PostalCode, loc.Country, familyGroup, true ); // since there can only be one mapped location, set the other locations to not mapped if ( familyAddress.IsMappedLocation ) { var groupLocations = groupLocationService.Queryable() .Where( l => l.GroupId == familyGroup.Id && l.Id != familyAddress.Id ).ToList(); foreach ( var groupLocation in groupLocations ) { groupLocation.IsMappedLocation = false; } } rockContext.SaveChanges(); } } } familyGroup.LoadAttributes(); avcFamilyAttributes.GetEditValues( familyGroup ); familyGroup.SaveAttributeValues(); } } } } } return true; } ); if ( wrapTransactionResult ) { var queryString = new Dictionary<string, string>(); var personParam = PageParameter( "Person" ); if ( !string.IsNullOrWhiteSpace( personParam ) ) { queryString.Add( "Person", personParam ); } NavigateToPage( RockPage.Guid, queryString ); } } /// <summary> /// Handles the Click event of the btnCancel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnCancel_Click( object sender, EventArgs e ) { ShowViewDetail(); } /// <summary> /// Handles the SelectedIndexChanged event of the rblRole control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void rblRole_SelectedIndexChanged( object sender, EventArgs e ) { var selectedId = rblRole.SelectedValueAsId(); if ( selectedId.HasValue ) { SetControlsForRoleType( selectedId.Value ); } } /// <summary> /// Handles the ItemDataBound event of the rContactInfo control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param> protected void rContactInfo_ItemDataBound( object sender, RepeaterItemEventArgs e ) { var pnbPhone = e.Item.FindControl( "pnbPhone" ) as PhoneNumberBox; if ( pnbPhone != null ) { pnbPhone.ValidationGroup = BlockValidationGroup; var phoneNumber = e.Item.DataItem as PhoneNumber; HtmlGenericControl phoneNumberContainer = ( HtmlGenericControl ) e.Item.FindControl( "divPhoneNumberContainer" ); if ( _isEditRecordAdult && ( phoneNumber != null ) ) { pnbPhone.Required = _requiredPhoneNumberGuids.Contains( phoneNumber.NumberTypeValue.Guid ); if ( pnbPhone.Required ) { pnbPhone.RequiredErrorMessage = string.Format( "{0} phone is required", phoneNumber.NumberTypeValue.Value ); phoneNumberContainer.AddCssClass( "required" ); } } if ( phoneNumber.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid() ) { if ( GetAttributeValue( AttributeKey.HighlightMobilePhone ).AsBoolean() ) { var hightlightTitle = ( Literal ) e.Item.FindControl( "litHighlightTitle" ); hightlightTitle.Text = string.Format( "<h4>{0}</h4>", GetAttributeValue( AttributeKey.MobileHighlightTitle ) ); hightlightTitle.Visible = true; var hightlightText = ( Literal ) e.Item.FindControl( "litHighlightText" ); hightlightText.Text = string.Format( "<p>{0}</p>", GetAttributeValue( AttributeKey.MobileHighlightText ) ); hightlightText.Visible = true; phoneNumberContainer.AddCssClass( "well" ); } } } } #endregion #region Methods /// <summary> /// Shows the edit person details. /// </summary> /// <param name="personGuid">The person's global unique identifier.</param> private void ShowEditPersonDetails( Guid personGuid ) { lViewPersonContent.Visible = false; var childGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid(); RockContext rockContext = new RockContext(); var groupId = hfGroupId.Value.AsIntegerOrNull(); if ( !groupId.HasValue ) { // invalid situation; return and report nothing. return; } var group = new GroupService( rockContext ).Get( groupId.Value ); if ( group == null ) { // invalid situation; return and report nothing. return; } hfEditPersonGuid.Value = personGuid.ToString(); var person = new Person(); if ( personGuid == Guid.Empty ) { rblRole.Visible = true; rblRole.Required = true; tbFirstName.Enabled = true; tbLastName.Enabled = true; } else { person = new PersonService( rockContext ).Get( personGuid ); if ( GetAttributeValue( AttributeKey.DisableNameEdit ).AsBoolean() ) { tbFirstName.Enabled = false; tbLastName.Enabled = false; } } if ( person == null ) { return; } if ( personGuid == Guid.Empty ) { // make them pick the family role on a new person rblRole.SelectedValue = null; } else { rblRole.SetValue( person.GetFamilyRole() ); } imgPhoto.BinaryFileId = person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPersonNoPictureUrl( person, 200, 200 ); dvpTitle.SetValue( person.TitleValueId ); tbFirstName.Text = person.FirstName; tbNickName.Text = person.NickName; tbLastName.Text = person.LastName; dvpSuffix.SetValue( person.SuffixValueId ); bpBirthDay.SelectedDate = person.BirthDate; // Setup the gender radio button list according to the required field var genderRequired = GetAttributeValue( AttributeKey.RequireGender ).AsBooleanOrNull() ?? true; if ( !genderRequired ) { rblGender.Items.Add( new ListItem( "Unknown", "Unknown" ) ); } // Add this check to handle if the gender requirement became required after an "Unknown" value was already set if ( rblGender.Items.FindByValue( person.Gender.ConvertToString() ) != null ) { rblGender.SelectedValue = person.Gender.ConvertToString(); } if ( group.Members.Where( gm => gm.PersonId == person.Id && gm.GroupRole.Guid == childGuid ).Any() ) { _isEditRecordAdult = false; tbEmail.Required = false; // don't display campus selector to children. Rated PG. cpCampus.Visible = false; if ( person.GraduationYear.HasValue ) { ypGraduation.SelectedYear = person.GraduationYear.Value; } else { ypGraduation.SelectedYear = null; } ddlGradePicker.Visible = true; if ( !person.HasGraduated ?? false ) { int gradeOffset = person.GradeOffset.Value; var maxGradeOffset = ddlGradePicker.MaxGradeOffset; // keep trying until we find a Grade that has a gradeOffset that includes the Person's gradeOffset (for example, there might be combined grades) while ( !ddlGradePicker.Items.OfType<ListItem>().Any( a => a.Value.AsInteger() == gradeOffset ) && gradeOffset <= maxGradeOffset ) { gradeOffset++; } ddlGradePicker.SetValue( gradeOffset ); } else { ddlGradePicker.SelectedIndex = 0; } } else { _isEditRecordAdult = true; bool requireEmail = GetAttributeValue( AttributeKey.RequireAdultEmailAddress ).AsBoolean(); tbEmail.Required = requireEmail; ddlGradePicker.Visible = false; // show/hide campus selector bool showCampus = GetAttributeValue( AttributeKey.ShowCampusSelector ).AsBoolean(); cpCampus.Visible = showCampus; if ( showCampus ) { cpCampus.Campuses = CampusCache.All( false ); // Use the current person's campus if this a new person if ( personGuid == Guid.Empty ) { cpCampus.SetValue( _person.PrimaryCampus ); } else { cpCampus.SetValue( person.GetCampus() ); } } } tbEmail.Text = person.Email; rblEmailPreference.SelectedValue = person.EmailPreference.ConvertToString( false ); rblCommunicationPreference.Visible = this.GetAttributeValue( AttributeKey.ShowCommunicationPreference ).AsBoolean(); rblCommunicationPreference.SetValue( person.CommunicationPreference == CommunicationType.SMS ? "2" : "1" ); // Person Attributes var personAttributeAdultGuidList = GetAttributeValue( AttributeKey.PersonAttributesAdults ).SplitDelimitedValues().AsGuidList(); var personAttributeChildGuidList = GetAttributeValue( AttributeKey.PersonAttributesChildren ).SplitDelimitedValues().AsGuidList(); avcPersonAttributesAdult.IncludedAttributes = personAttributeAdultGuidList.Select( a => AttributeCache.Get( a ) ).ToArray(); avcPersonAttributesChild.IncludedAttributes = personAttributeChildGuidList.Select( a => AttributeCache.Get( a ) ).ToArray(); avcPersonAttributesAdult.AddEditControls( person, true ); avcPersonAttributesChild.AddEditControls( person, true ); avcPersonAttributesAdult.Visible = false; avcPersonAttributesChild.Visible = false; pnlPersonAttributes.Visible = false; if ( personGuid != Guid.Empty ) { if ( person.AgeClassification != AgeClassification.Child && personAttributeAdultGuidList.Any() ) { avcPersonAttributesAdult.Visible = true; pnlPersonAttributes.Visible = true; } else if ( person.AgeClassification == AgeClassification.Child && personAttributeChildGuidList.Any() ) { avcPersonAttributesChild.Visible = true; pnlPersonAttributes.Visible = true; } } // Family Attributes if ( person.Id == _person.Id ) { List<Guid> familyAttributeGuidList = GetAttributeValue( AttributeKey.FamilyAttributes ).SplitDelimitedValues().AsGuidList(); if ( familyAttributeGuidList.Any() ) { pnlFamilyAttributes.Visible = true; avcFamilyAttributes.IncludedAttributes = familyAttributeGuidList.Select( a => AttributeCache.Get( a ) ).ToArray(); avcFamilyAttributes.AddEditControls( group, true ); } else { pnlFamilyAttributes.Visible = false; } lPreviousAddress.Text = string.Empty; acAddress.Required = false; Guid? locationTypeGuid = GetAttributeValue( AttributeKey.AddressTypeValueGuid ).AsGuidOrNull(); if ( locationTypeGuid.HasValue ) { pnlAddress.Visible = true; var addressTypeDv = DefinedValueCache.Get( locationTypeGuid.Value ); // if address type is home enable the move and is mailing/physical if ( addressTypeDv.Guid == Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() ) { lbMoved.Visible = true; cbIsMailingAddress.Visible = true; cbIsPhysicalAddress.Visible = true; } else { lbMoved.Visible = false; cbIsMailingAddress.Visible = false; cbIsPhysicalAddress.Visible = false; } lAddressTitle.Text = addressTypeDv.Value + " Address"; var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull(); if ( familyGroupTypeGuid.HasValue ) { var familyGroupType = GroupTypeCache.Get( familyGroupTypeGuid.Value ); var familyAddress = new GroupLocationService( rockContext ).Queryable() .Where( l => l.GroupId == groupId.Value && l.GroupLocationTypeValueId == addressTypeDv.Id && l.Group.Members.Any( m => m.PersonId == person.Id ) ) .FirstOrDefault(); if ( familyAddress != null ) { acAddress.SetValues( familyAddress.Location ); cbIsMailingAddress.Checked = familyAddress.IsMailingLocation; cbIsPhysicalAddress.Checked = familyAddress.IsMappedLocation; } } } } else { pnlFamilyAttributes.Visible = false; pnlAddress.Visible = false; } BindPhoneNumbers( person ); pnlView.Visible = false; pnlEdit.Visible = true; } /// <summary> /// Binds the phone numbers. /// </summary> /// <param name="person">The person.</param> private void BindPhoneNumbers( Person person ) { if ( person == null ) { person = new Person(); } bool showPhoneNumbers = GetAttributeValue( AttributeKey.ShowPhoneNumbers ).AsBoolean(); pnlPhoneNumbers.Visible = showPhoneNumbers; if ( !showPhoneNumbers ) { return; } var phoneNumbers = new List<PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Get( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ) ); var mobilePhoneType = DefinedValueCache.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE ) ); var selectedPhoneTypeGuids = GetAttributeValue( AttributeKey.PhoneTypeValueGuids ).Split( ',' ).AsGuidList(); if ( phoneNumberTypes.DefinedValues.Where( pnt => selectedPhoneTypeGuids.Contains( pnt.Guid ) ).Any() ) { foreach ( var phoneNumberType in phoneNumberTypes.DefinedValues.Where( pnt => selectedPhoneTypeGuids.Contains( pnt.Guid ) ) ) { var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberType.Id ); if ( phoneNumber == null ) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; numberType.Guid = phoneNumberType.Guid; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber( phoneNumber.CountryCode, phoneNumber.Number ); } phoneNumbers.Add( phoneNumber ); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } } /// <summary> /// Gets the person attribute Guids. /// </summary> /// <param name="personId">The person identifier.</param> /// <returns></returns> private List<Guid> GetPersonAttributeGuids( int personId ) { GroupMemberService groupMemberService = new GroupMemberService( new RockContext() ); List<Guid> attributeGuidList = new List<Guid>(); var adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid(); var childGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid(); var groupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid(); if ( groupMemberService.Queryable().Where( gm => gm.PersonId == personId && gm.Group.GroupType.Guid == groupTypeGuid && gm.GroupRole.Guid == adultGuid ).Any() ) { attributeGuidList = GetAttributeValue( AttributeKey.PersonAttributesAdults ).SplitDelimitedValues().AsGuidList(); } else { attributeGuidList = GetAttributeValue( AttributeKey.PersonAttributesChildren ).SplitDelimitedValues().AsGuidList(); } return attributeGuidList; } /// <summary> /// Sets the visiblity of the controls for role. /// </summary> /// <param name="roleTypeId">The role type identifier.</param> public void SetControlsForRoleType( int roleTypeId ) { var adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid(); var groupTypeFamily = GroupTypeCache.GetFamilyGroupType(); if ( groupTypeFamily.Roles.Where( gr => gr.Guid == adultGuid && gr.Id == roleTypeId ).Any() ) { ddlGradePicker.Visible = false; tbEmail.Required = GetAttributeValue( AttributeKey.RequireAdultEmailAddress ).AsBoolean(); _isEditRecordAdult = true; } else { ddlGradePicker.Visible = true; tbEmail.Required = false; _isEditRecordAdult = false; } avcPersonAttributesAdult.Visible = _isEditRecordAdult; avcPersonAttributesChild.Visible = !_isEditRecordAdult; if ( _isEditRecordAdult ) { var attributeGuidListAdult = GetAttributeValue( AttributeKey.PersonAttributesAdults ).SplitDelimitedValues().AsGuidList(); pnlPersonAttributes.Visible = attributeGuidListAdult.Any(); } else { var attributeGuidListChild = GetAttributeValue( AttributeKey.PersonAttributesChildren ).SplitDelimitedValues().AsGuidList(); pnlPersonAttributes.Visible = attributeGuidListChild.Any(); } } #endregion } }
45.540557
206
0.534141
[ "Apache-2.0" ]
KingdomFirst/RockBlocks
Cms/PublicProfileEdit.ascx.cs
75,235
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the organizations-2016-11-28.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.Organizations.Model { /// <summary> /// We can't find a handshake with the <code>HandshakeId</code> that you specified. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class HandshakeNotFoundException : AmazonOrganizationsException { /// <summary> /// Constructs a new HandshakeNotFoundException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public HandshakeNotFoundException(string message) : base(message) {} /// <summary> /// Construct instance of HandshakeNotFoundException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public HandshakeNotFoundException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of HandshakeNotFoundException /// </summary> /// <param name="innerException"></param> public HandshakeNotFoundException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of HandshakeNotFoundException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public HandshakeNotFoundException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of HandshakeNotFoundException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public HandshakeNotFoundException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the HandshakeNotFoundException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected HandshakeNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
47.637097
178
0.682241
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Organizations/Generated/Model/HandshakeNotFoundException.cs
5,907
C#
namespace EDiary.Services.Mapping { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using AutoMapper; using AutoMapper.Configuration; public static class AutoMapperConfig { private static bool initialized; public static IMapper MapperInstance { get; set; } public static void RegisterMappings(params Assembly[] assemblies) { if (initialized) { return; } initialized = true; var types = assemblies.SelectMany(a => a.GetExportedTypes()).ToList(); var config = new MapperConfigurationExpression(); config.CreateProfile( "ReflectionProfile", configuration => { // IMapFrom<> foreach (var map in GetFromMaps(types)) { configuration.CreateMap(map.Source, map.Destination); } // IMapTo<> foreach (var map in GetToMaps(types)) { configuration.CreateMap(map.Source, map.Destination); } // IHaveCustomMappings foreach (var map in GetCustomMappings(types)) { map.CreateMappings(configuration); } }); MapperInstance = new Mapper(new MapperConfiguration(config)); } private static IEnumerable<TypesMap> GetFromMaps(IEnumerable<Type> types) { var fromMaps = from t in types from i in t.GetTypeInfo().GetInterfaces() where i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>) && !t.GetTypeInfo().IsAbstract && !t.GetTypeInfo().IsInterface select new TypesMap { Source = i.GetTypeInfo().GetGenericArguments()[0], Destination = t, }; return fromMaps; } private static IEnumerable<TypesMap> GetToMaps(IEnumerable<Type> types) { var toMaps = from t in types from i in t.GetTypeInfo().GetInterfaces() where i.GetTypeInfo().IsGenericType && i.GetTypeInfo().GetGenericTypeDefinition() == typeof(IMapTo<>) && !t.GetTypeInfo().IsAbstract && !t.GetTypeInfo().IsInterface select new TypesMap { Source = t, Destination = i.GetTypeInfo().GetGenericArguments()[0], }; return toMaps; } private static IEnumerable<IHaveCustomMappings> GetCustomMappings(IEnumerable<Type> types) { var customMaps = from t in types from i in t.GetTypeInfo().GetInterfaces() where typeof(IHaveCustomMappings).GetTypeInfo().IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract && !t.GetTypeInfo().IsInterface select (IHaveCustomMappings)Activator.CreateInstance(t); return customMaps; } private class TypesMap { public Type Source { get; set; } public Type Destination { get; set; } } } }
35.305556
99
0.468135
[ "MIT" ]
markodjunev/E-Diary
EDiary/Services/EDiary.Services.Mapping/AutoMapperConfig.cs
3,815
C#
namespace GameDesingerTools { partial class TabExport { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.Export_button = new DevComponents.DotNetBar.ButtonX(); this.SelectAll_button = new DevComponents.DotNetBar.ButtonX(); this.checkedListBox1 = new System.Windows.Forms.CheckedListBox(); this.panelEx1 = new DevComponents.DotNetBar.PanelEx(); this.btOpenDictionary = new DevComponents.DotNetBar.ButtonX(); this.btOpenExportedFile = new DevComponents.DotNetBar.ButtonX(); this.panelEx1.SuspendLayout(); this.SuspendLayout(); // // Export_button // this.Export_button.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.Export_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.Export_button.Location = new System.Drawing.Point(147, 252); this.Export_button.Name = "Export_button"; this.Export_button.Size = new System.Drawing.Size(114, 26); this.Export_button.TabIndex = 2; this.Export_button.Text = "导出所选表"; this.Export_button.Click += new System.EventHandler(this.Export_button_Click); // // SelectAll_button // this.SelectAll_button.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.SelectAll_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.SelectAll_button.Location = new System.Drawing.Point(12, 252); this.SelectAll_button.Name = "SelectAll_button"; this.SelectAll_button.Size = new System.Drawing.Size(114, 26); this.SelectAll_button.TabIndex = 1; this.SelectAll_button.Text = "全选"; this.SelectAll_button.Click += new System.EventHandler(this.SelectAll_button_Click); // // checkedListBox1 // this.checkedListBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.checkedListBox1.FormattingEnabled = true; this.checkedListBox1.Location = new System.Drawing.Point(0, 0); this.checkedListBox1.Name = "checkedListBox1"; this.checkedListBox1.Size = new System.Drawing.Size(615, 212); this.checkedListBox1.TabIndex = 0; // // panelEx1 // this.panelEx1.CanvasColor = System.Drawing.SystemColors.Control; this.panelEx1.Controls.Add(this.checkedListBox1); this.panelEx1.Controls.Add(this.btOpenExportedFile); this.panelEx1.Controls.Add(this.btOpenDictionary); this.panelEx1.Controls.Add(this.SelectAll_button); this.panelEx1.Controls.Add(this.Export_button); this.panelEx1.Dock = System.Windows.Forms.DockStyle.Fill; this.panelEx1.Location = new System.Drawing.Point(0, 0); this.panelEx1.Name = "panelEx1"; this.panelEx1.Size = new System.Drawing.Size(615, 316); this.panelEx1.Style.Alignment = System.Drawing.StringAlignment.Center; this.panelEx1.Style.BackColor1.ColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelBackground; this.panelEx1.Style.BackColor2.ColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelBackground2; this.panelEx1.Style.Border = DevComponents.DotNetBar.eBorderType.SingleLine; this.panelEx1.Style.BorderColor.ColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelBorder; this.panelEx1.Style.ForeColor.ColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelText; this.panelEx1.Style.GradientAngle = 90; this.panelEx1.TabIndex = 3; // // btOpenDictionary // this.btOpenDictionary.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.btOpenDictionary.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btOpenDictionary.Location = new System.Drawing.Point(298, 252); this.btOpenDictionary.Name = "btOpenDictionary"; this.btOpenDictionary.Size = new System.Drawing.Size(131, 26); this.btOpenDictionary.TabIndex = 1; this.btOpenDictionary.Text = "打开导出文件的目录"; this.btOpenDictionary.Click += new System.EventHandler(this.btOpenDictionary_Click); // // btOpenExportedFile // this.btOpenExportedFile.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.btOpenExportedFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btOpenExportedFile.Location = new System.Drawing.Point(466, 252); this.btOpenExportedFile.Name = "btOpenExportedFile"; this.btOpenExportedFile.Size = new System.Drawing.Size(124, 26); this.btOpenExportedFile.TabIndex = 1; this.btOpenExportedFile.Text = "打开所导出的文件"; this.btOpenExportedFile.Click += new System.EventHandler(this.btOpenExportedFile_Click); // // TabExport // this.AcceptButton = this.Export_button; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(615, 316); this.Controls.Add(this.panelEx1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Name = "TabExport"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "导出数据"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.TabExport_FormClosed); this.panelEx1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private DevComponents.DotNetBar.ButtonX Export_button; private DevComponents.DotNetBar.ButtonX SelectAll_button; private System.Windows.Forms.CheckedListBox checkedListBox1; private DevComponents.DotNetBar.PanelEx panelEx1; private DevComponents.DotNetBar.ButtonX btOpenDictionary; private DevComponents.DotNetBar.ButtonX btOpenExportedFile; } }
54.401408
169
0.634434
[ "MIT" ]
RivenZoo/FullSource
Jx3Full/Source/Source/Tools/GameDesignerEditor/GameDesignerTools/MainFrame/TabExport.Designer.cs
7,792
C#
namespace SharpHook; using SharpHook.Native; /// <summary> /// Represents an object which can simulate keyboard and mouse events. /// </summary> /// <remarks> /// The methods of this interface correspond to constants defined in the <see cref="EventType" /> enum. /// </remarks> public interface IEventSimulator { /// <summary> /// Simulates pressing a key. /// </summary> /// <param name="keyCode">The code of the key to press.</param> /// <param name="mask">The modifier mask of the event.</param> public void SimulateKeyPress(KeyCode keyCode, ModifierMask mask = ModifierMask.None); /// <summary> /// Simulates releasing a key. /// </summary> /// <param name="keyCode">The code of the key to release.</param> /// <param name="mask">The modifier mask of the event.</param> public void SimulateKeyRelease(KeyCode keyCode, ModifierMask mask = ModifierMask.None); /// <summary> /// Simulates pressing a mouse button. /// </summary> /// <param name="button">The mouse button to press.</param> /// <param name="mask">The modifier mask of the event.</param> public void SimulateMousePress(MouseButton button, ModifierMask mask = ModifierMask.None); /// <summary> /// Simulates releasing a mouse button. /// </summary> /// <param name="button">The mouse button to release.</param> /// <param name="mask">The modifier mask of the event.</param> public void SimulateMouseRelease(MouseButton button, ModifierMask mask = ModifierMask.None); /// <summary> /// Simulates moving a mouse pointer. /// </summary> /// <param name="x">The target X-coordinate of the mouse pointer.</param> /// <param name="y">The target Y-coordinate of the mouse pointer.</param> /// <param name="mask">The modifier mask of the event.</param> public void SimulateMouseMovement(short x, short y, ModifierMask mask = ModifierMask.None); /// <summary> /// Simulates scrolling a mouse wheel. /// </summary> /// <param name="x">The target X-coordinate of the mouse pointer.</param> /// <param name="y">The target Y-coordinate of the mouse pointer.</param> /// <param name="amount">The scrolling amount.</param> /// <param name="rotation">The wheel rotation.</param> /// <param name="mask">The modifier mask of the event.</param> /// <remarks> /// A positive <paramref name="rotation" /> value indicates that the wheel was rotated forward, away from the user; /// a negative value indicates that the wheel was rotated backward, toward the user. /// </remarks> public void SimulateMouseWheel( short x, short y, ushort amount, short rotation, ModifierMask mask = ModifierMask.None); }
40.676471
119
0.660882
[ "MIT" ]
Luxusio/SharpHook
SharpHook/IEventSimulator.cs
2,766
C#
using Microsoft.Extensions.Options; using Microsoft.VisualStudio.TestTools.UnitTesting; using MigrationTools.DataContracts; namespace MigrationTools.Endpoints.Tests { [TestClass()] public class FileSystemWorkItemEndpointTests { [TestMethod] public void ConfiguredTest() { SetupStore(@".\Store\Source\", 10); FileSystemWorkItemEndpoint e = CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection.Source, @".\Store\Source\"); Assert.AreEqual(10, e.Count); } [TestMethod] public void EmptyTest() { FileSystemWorkItemEndpoint e = CreateInMemoryWorkItemEndpoint(EndpointDirection.Source); Assert.AreEqual(0, e.Count); } [TestMethod] public void FilterAllTest() { SetupStore(@".\Store\Source\", 10); SetupStore(@".\Store\target\", 10); FileSystemWorkItemEndpoint e1 = CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection.Source, @".\Store\Source\"); FileSystemWorkItemEndpoint e2 = CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection.Source, @".\Store\target\"); e1.Filter(e2.WorkItems); Assert.AreEqual(0, e1.Count); } [TestMethod] public void FilterHalfTest() { SetupStore(@".\Store\Source\", 20); SetupStore(@".\Store\target\", 10); FileSystemWorkItemEndpoint e1 = CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection.Source, @".\Store\Source\"); FileSystemWorkItemEndpoint e2 = CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection.Source, @".\Store\target\"); e1.Filter(e2.WorkItems); Assert.AreEqual(10, e1.Count); } [TestMethod] public void PersistWorkItemExistsTest() { SetupStore(@".\Store\Source\", 20); SetupStore(@".\Store\target\", 10); FileSystemWorkItemEndpoint e1 = CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection.Source, @".\Store\Source\"); FileSystemWorkItemEndpoint e2 = CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection.Source, @".\Store\target\"); foreach (WorkItemData item in e1.WorkItems) { e2.PersistWorkItem(item); } Assert.AreEqual(20, e2.Count); } [TestMethod] public void PersistWorkItemWithFilterTest() { SetupStore(@".\Store\Source\", 20); SetupStore(@".\Store\target\", 10); FileSystemWorkItemEndpoint e1 = CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection.Source, @".\Store\Source\"); FileSystemWorkItemEndpoint e2 = CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection.Source, @".\Store\target\"); e1.Filter(e2.WorkItems); Assert.AreEqual(10, e1.Count); foreach (WorkItemData item in e1.WorkItems) { e2.PersistWorkItem(item); } Assert.AreEqual(20, e2.Count); } public void SetupStore(string path, int count) { if (System.IO.Directory.Exists(path)) { System.IO.Directory.Delete(path, true); } FileSystemWorkItemEndpoint e = CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection.Source, path); for (int i = 0; i < count; i++) { e.PersistWorkItem(new WorkItemData() { Id = i.ToString(), Title = string.Format("Title {0}", i) }); } } private static FileSystemWorkItemEndpoint CreateAndConfigureInMemoryWorkItemEndpoint(EndpointDirection direction, string queryString) { FileSystemWorkItemEndpoint e = CreateInMemoryWorkItemEndpoint(EndpointDirection.Source); FileSystemWorkItemQuery query = new FileSystemWorkItemQuery(); query.Configure(null, queryString, null); e.Configure(query, null); return e; } private static FileSystemWorkItemEndpoint CreateInMemoryWorkItemEndpoint(EndpointDirection direction) { var options = Options.Create<FileSystemWorkItemEndpointOptions>(new FileSystemWorkItemEndpointOptions() { Direction = direction }); FileSystemWorkItemEndpoint e = new FileSystemWorkItemEndpoint(options); return e; } } }
42.367925
143
0.631931
[ "MIT" ]
GitMje/azure-devops-migration-tools
src/MigrationTools.Clients.FileSystem.Tests/Endpoints/FileSystemWorkItemEndpointTests.cs
4,493
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Web; using Microsoft.AspNetCore.Cryptography.KeyDerivation; namespace AD_Services { public class EncryptionDecryption : Dictionary<string, string> { // Change the following keys to ensure uniqueness // Must be 8 bytes protected byte[] _keyBytes = { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18 }; // Must be at least 8 characters protected string _keyString = "ABC12345"; // Name for checksum value (unlikely to be used as arguments by user) protected string _checksumKey = "__$$"; /// <summary> /// Creates an empty dictionary /// </summary> public EncryptionDecryption() { } /// <summary> /// Creates a dictionary from the given, encrypted string /// </summary> /// <param name="encryptedData"></param> public EncryptionDecryption(string encryptedData) { // Descrypt string string data = Decrypt(encryptedData); // Parse out key/value pairs and add to dictionary string checksum = null; string[] args = data.Split('&'); foreach (string arg in args) { int i = arg.IndexOf('='); if (i != -1) { string key = arg.Substring(0, i); string value = arg.Substring(i + 1); if (key == _checksumKey) checksum = value; else base.Add(HttpUtility.UrlDecode(key), HttpUtility.UrlDecode(value)); } } // Clear contents if valid checksum not found if (checksum == null || checksum != ComputeChecksum()) base.Clear(); } /// <summary> /// Returns an encrypted string that contains the current dictionary /// </summary> /// <returns></returns> public override string ToString() { // Build query string from current contents StringBuilder content = new StringBuilder(); foreach (string key in base.Keys) { if (content.Length > 0) content.Append('&'); content.AppendFormat("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(base[key])); } // Add checksum if (content.Length > 0) content.Append('&'); content.AppendFormat("{0}={1}", _checksumKey, ComputeChecksum()); return Encrypt(content.ToString()); } /// <summary> /// Returns a simple checksum for all keys and values in the collection /// </summary> /// <returns></returns> protected string ComputeChecksum() { int checksum = 0; foreach (KeyValuePair<string, string> pair in this) { checksum += pair.Key.Sum(c => c - '0'); checksum += pair.Value.Sum(c => c - '0'); } return checksum.ToString("X"); } /// <summary> /// Encrypts the given text /// </summary> /// <param name="text">Text to be encrypted</param> /// <returns></returns> public string Encrypt(string text) { try { byte[] keyData = Encoding.UTF8.GetBytes(_keyString.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] textData = Encoding.UTF8.GetBytes(text); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(keyData, _keyBytes), CryptoStreamMode.Write); cs.Write(textData, 0, textData.Length); cs.FlushFinalBlock(); return GetString(ms.ToArray()); } catch (Exception) { return String.Empty; } } /// <summary> /// Decrypts the given encrypted text /// </summary> /// <param name="text">Text to be decrypted</param> /// <returns></returns> public string Decrypt(string text) { try { byte[] keyData = Encoding.UTF8.GetBytes(_keyString.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] textData = GetBytes(text); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(keyData, _keyBytes), CryptoStreamMode.Write); cs.Write(textData, 0, textData.Length); cs.FlushFinalBlock(); return Encoding.UTF8.GetString(ms.ToArray()); } catch (Exception) { return String.Empty; } } /// <summary> /// Converts a byte array to a string of hex characters /// </summary> /// <param name="data"></param> /// <returns></returns> protected string GetString(byte[] data) { StringBuilder results = new StringBuilder(); foreach (byte b in data) results.Append(b.ToString("X2")); return results.ToString(); } /// <summary> /// Converts a string of hex characters to a byte array /// </summary> /// <param name="data"></param> /// <returns></returns> protected byte[] GetBytes(string data) { // GetString() encodes the hex-numbers with two digits byte[] results = new byte[data.Length / 2]; for (int i = 0; i < data.Length; i += 2) results[i / 2] = Convert.ToByte(data.Substring(i, 2), 16); return results; } public static string HashString(string stringToHash) { SHA256Managed sha256 = new SHA256Managed(); var bytes = UTF8Encoding.UTF8.GetBytes(stringToHash); var hash = sha256.ComputeHash(bytes); return Convert.ToBase64String(hash).Replace("+", string.Empty).Replace("=", string.Empty);//+ char is not well handled in urls, therefore skipping it } public string HashPassword(string password) { var prf = KeyDerivationPrf.HMACSHA256; var rng = RandomNumberGenerator.Create(); const int iterCount = 10000; const int saltSize = 128 / 8; const int numBytesRequested = 256 / 8; // Produce a version 3 (see comment above) text hash. var salt = new byte[saltSize]; rng.GetBytes(salt); var subkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, numBytesRequested); var outputBytes = new byte[13 + salt.Length + subkey.Length]; outputBytes[0] = 0x01; // format marker WriteNetworkByteOrder(outputBytes, 1, (uint)prf); WriteNetworkByteOrder(outputBytes, 5, iterCount); WriteNetworkByteOrder(outputBytes, 9, saltSize); Buffer.BlockCopy(salt, 0, outputBytes, 13, salt.Length); Buffer.BlockCopy(subkey, 0, outputBytes, 13 + saltSize, subkey.Length); return Convert.ToBase64String(outputBytes); } public bool VerifyHashedPassword(string hashedPassword, string providedPassword) { var decodedHashedPassword = Convert.FromBase64String(hashedPassword); // Wrong version if (decodedHashedPassword[0] != 0x01) return false; // Read header information var prf = (KeyDerivationPrf)ReadNetworkByteOrder(decodedHashedPassword, 1); var iterCount = (int)ReadNetworkByteOrder(decodedHashedPassword, 5); var saltLength = (int)ReadNetworkByteOrder(decodedHashedPassword, 9); // Read the salt: must be >= 128 bits if (saltLength < 128 / 8) { return false; } var salt = new byte[saltLength]; Buffer.BlockCopy(decodedHashedPassword, 13, salt, 0, salt.Length); // Read the subkey (the rest of the payload): must be >= 128 bits var subkeyLength = decodedHashedPassword.Length - 13 - salt.Length; if (subkeyLength < 128 / 8) { return false; } var expectedSubkey = new byte[subkeyLength]; Buffer.BlockCopy(decodedHashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length); // Hash the incoming password and verify it var actualSubkey = KeyDerivation.Pbkdf2(providedPassword, salt, prf, iterCount, subkeyLength); return actualSubkey.SequenceEqual(expectedSubkey); } private static void WriteNetworkByteOrder(byte[] buffer, int offset, uint value) { buffer[offset + 0] = (byte)(value >> 24); buffer[offset + 1] = (byte)(value >> 16); buffer[offset + 2] = (byte)(value >> 8); buffer[offset + 3] = (byte)(value >> 0); } private static uint ReadNetworkByteOrder(byte[] buffer, int offset) { return ((uint)(buffer[offset + 0]) << 24) | ((uint)(buffer[offset + 1]) << 16) | ((uint)(buffer[offset + 2]) << 8) | ((uint)(buffer[offset + 3])); } public static string Base64Encode(string plainText) { try { var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); return System.Convert.ToBase64String(plainTextBytes); } catch { return string.Empty; } } public static string Base64Decode(string base64EncodedData) { try { var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); } catch { return string.Empty; } } } }
35.28
161
0.535525
[ "MIT" ]
99s/Airlines_API_Demo_Base
AD_API_CORE/AD_Services/EncryptionDecryption.cs
10,586
C#
using System.Collections.Generic; using EvansDiary.Interfaces; namespace EvansDiary.Web.ViewModels { public class FamilyViewModel { public IEnumerable<IAssociatedImage> Images { get; set; } } }
21.4
65
0.733645
[ "MIT" ]
emzyme20/evansdiary
EvansDiary.Web/ViewModels/FamilyViewModel.cs
214
C#
/* * Mock Server API * * MockServer enables easy mocking of any system you integrate with via HTTP or HTTPS with clients written in Java, JavaScript and Ruby and a simple REST API (as shown below). MockServer Proxy is a proxy that introspects all proxied traffic including encrypted SSL traffic and supports Port Forwarding, Web Proxying (i.e. HTTP proxy), HTTPS Tunneling Proxying (using HTTP CONNECT) and SOCKS Proxying (i.e. dynamic port forwarding). Both MockServer and the MockServer Proxy record all received requests so that it is possible to verify exactly what requests have been sent by the system under test. * * OpenAPI spec version: 5.6.x * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using System.Text; namespace MockServer.Client.Net.Models { /// <summary> /// HttpClassCallback /// </summary> [DataContract] public partial class HttpClassCallback : IEquatable<HttpClassCallback>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="HttpClassCallback" /> class. /// </summary> /// <param name="delay">delay.</param> /// <param name="callbackClass">callbackClass.</param> public HttpClassCallback(Delay delay = default(Delay), string callbackClass = default(string)) { this.Delay = delay; this.CallbackClass = callbackClass; } /// <summary> /// Gets or Sets Delay /// </summary> [DataMember(Name = "delay", EmitDefaultValue = false)] public Delay Delay { get; set; } /// <summary> /// Gets or Sets CallbackClass /// </summary> [DataMember(Name = "callbackClass", EmitDefaultValue = false)] public string CallbackClass { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class HttpClassCallback {\n"); sb.Append(" Delay: ").Append(Delay).Append("\n"); sb.Append(" CallbackClass: ").Append(CallbackClass).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as HttpClassCallback); } /// <summary> /// Returns true if HttpClassCallback instances are equal /// </summary> /// <param name="input">Instance of HttpClassCallback to be compared</param> /// <returns>Boolean</returns> public bool Equals(HttpClassCallback input) { if (input == null) return false; return ( this.Delay == input.Delay || (this.Delay != null && this.Delay.Equals(input.Delay)) ) && ( this.CallbackClass == input.CallbackClass || (this.CallbackClass != null && this.CallbackClass.Equals(input.CallbackClass)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Delay != null) hashCode = hashCode * 59 + this.Delay.GetHashCode(); if (this.CallbackClass != null) hashCode = hashCode * 59 + this.CallbackClass.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
37.257576
599
0.579504
[ "MIT" ]
bangush/mockserverclient
mockserver.client.net/Model/HttpClassCallback.cs
4,918
C#
//------------------------------------------------------------ // Author: 烟雨迷离半世殇 // Mail: 1778139321@qq.com // Data: 2019年4月27日 11:25:25 //------------------------------------------------------------ using libx; using UnityEngine; namespace ETModel { [ObjectSystem] public class FUICheckForResUpdateComponentStartSystem: StartSystem<FUICheckForResUpdateComponent> { public override void Start(FUICheckForResUpdateComponent self) { StartAsync(self).Coroutine(); } private async ETVoid StartAsync(FUICheckForResUpdateComponent self) { TimerComponent timerComponent = Game.Scene.GetComponent<TimerComponent>(); long instanceId = self.InstanceId; while (true) { await timerComponent.WaitAsync(1); if (self.InstanceId != instanceId) { return; } BundleDownloaderComponent bundleDownloaderComponent = Game.Scene.GetComponent<BundleDownloaderComponent>(); if (bundleDownloaderComponent == null) { continue; } if (bundleDownloaderComponent.Updater.Step == Step.Versions) { self.FUICheackForResUpdate.updateInfo.text = "正在为您检查资源更新..."; } if (bundleDownloaderComponent.Updater.Step == Step.Prepared) { self.FUICheackForResUpdate.updateInfo.text = "检查更新完毕"; } if (bundleDownloaderComponent.Updater.Step == Step.Download) { self.FUICheackForResUpdate.updateInfo.text = "正在为您更新资源:" + $"{bundleDownloaderComponent.Updater.UpdateProgress}%"; if (bundleDownloaderComponent.Updater.UpdateProgress >= 100) { self.FUICheackForResUpdate.updateInfo.text = "资源更新完成,祝您游戏愉快。"; } } self.FUICheackForResUpdate.processbar.TweenValue(bundleDownloaderComponent.Updater.UpdateProgress, 0.1f); } } } }
35.836066
134
0.532937
[ "MIT" ]
mosheepdev/NKGMobaBasedOnET
Unity/Assets/Model/NKGMOBA/FairyGUI/System/FUICheckForResUpdate/FUICheckForResUpdateComponentStartSystem.cs
2,284
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SecurityHub.Model { /// <summary> /// This is the response object from the GetFindings operation. /// </summary> public partial class GetFindingsResponse : AmazonWebServiceResponse { private List<AwsSecurityFinding> _findings = new List<AwsSecurityFinding>(); private string _nextToken; /// <summary> /// Gets and sets the property Findings. /// <para> /// Findings details returned by the operation. /// </para> /// </summary> [AWSProperty(Required=true)] public List<AwsSecurityFinding> Findings { get { return this._findings; } set { this._findings = value; } } // Check to see if Findings property is set internal bool IsSetFindings() { return this._findings != null && this._findings.Count > 0; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The token that is required for pagination. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
30.013158
109
0.624726
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/GetFindingsResponse.cs
2,281
C#
using System; namespace UberStrok.Core.Views { [Serializable] public class BasicClanView { public BasicClanView() { } public int GroupId { get; set; } public int MembersCount { get; set; } = 50; public string Description { get; set; } public string Name { get; set; } public string Motto { get; set; } public string Address { get; set; } public DateTime FoundingDate { get; set; } public string Picture { get; set; } public GroupType Type { get; set; } public DateTime LastUpdated { get; set; } public string Tag { get; set; } public int MembersLimit { get; set; } public GroupColor ColorStyle { get; set; } public GroupFontStyle FontStyle { get; set; } public int ApplicationId { get; set; } public int OwnerCmid { get; set; } public string OwnerName { get; set; } public override string ToString() { string text = string.Concat(new object[] { "[Clan: [Id: ", this.GroupId, "][Members count: ", this.MembersCount, "][Description: ", this.Description, "]" }); string text2 = text; text = string.Concat(new string[] { text2, "[Name: ", this.Name, "][Motto: ", this.Name, "][Address: ", this.Address, "]" }); text2 = text; text = string.Concat(new object[] { text2, "[Creation date: ", this.FoundingDate, "][Picture: ", this.Picture, "][Type: ", this.Type, "][Last updated: ", this.LastUpdated, "]" }); text2 = text; text = string.Concat(new object[] { text2, "[Tag: ", this.Tag, "][Members limit: ", this.MembersLimit, "][Color style: ", this.ColorStyle, "][Font style: ", this.FontStyle, "]" }); text2 = text; return string.Concat(new object[] { text2, "[Application Id: ", this.ApplicationId, "][Owner Cmid: ", this.OwnerCmid, "][Owner name: ", this.OwnerName, "]]" }); } } }
24.478261
53
0.401066
[ "MIT" ]
PoH98/uberstrok
src/UberStrok.Core.Views/BasicClanView.cs
2,817
C#
using System.Collections.Generic; using System.Linq; using Pulse.Domain.EntryItems.Entities; using Pulse.Web.Controllers.Patients.ResponseModels; namespace Pulse.Web.Extensions { public static class SourceTextInfoExtensions { public static IList<SourceTextInfo> ToSourceTextInfoList(this IEnumerable<Allergy> allergies) { if (allergies == null || !allergies.Any()) { return new List<SourceTextInfo>(); } return allergies .Select(x => new SourceTextInfo { Source = x.Source, SourceId = x.SourceId, Text = x.Cause }).ToList(); } public static IList<SourceTextInfo> ToSourceTextInfoList(this IEnumerable<Diagnosis> diagnoses) { if (diagnoses == null || !diagnoses.Any()) { return new List<SourceTextInfo>(); } return diagnoses .Select(x => new SourceTextInfo { Source = x.Source, SourceId = x.SourceId, Text = x.Description }).ToList(); } public static IList<SourceTextInfo> ToSourceTextInfoList(this IEnumerable<Medication> medications) { if (medications == null || !medications.Any()) { return new List<SourceTextInfo>(); } return medications .Select(x => new SourceTextInfo { Source = x.Source, SourceId = x.SourceId, Text = x.Name }).ToList(); } public static IList<SourceTextInfo> ToSourceTextInfoList(this IEnumerable<Contact> contacts) { if (contacts == null || !contacts.Any()) { return new List<SourceTextInfo>(); } return contacts .Select(x => new SourceTextInfo { Source = x.Source, SourceId = x.SourceId, Text = x.Name }).ToList(); } } }
31.405405
107
0.468589
[ "Apache-2.0" ]
rowellx68/PulseTile-React
api/Pulse.Web/Extensions/SourceTextInfoExtensions.cs
2,326
C#
/* * Copyright 2014, 2015 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using IdentityServer3.Core.Extensions; using IdentityServer3.Core.Services.Default; using Microsoft.Owin; using System; using System.Diagnostics; using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web.Http; namespace IdentityServer3.Core.Results { internal class WelcomeActionResult : IHttpActionResult { readonly IOwinContext context; public WelcomeActionResult(IOwinContext context) { if (context == null) throw new ArgumentNullException("context"); this.context = context; } public Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken) { var baseUrl = context.GetIdentityServerBaseUrl(); var assembly = Assembly.GetExecutingAssembly(); var fvi = FileVersionInfo.GetVersionInfo(assembly.Location); string version = fvi.FileVersion; var html = AssetManager.LoadWelcomePage(baseUrl, version); var content = new StringContent(html, Encoding.UTF8, "text/html"); var response = new HttpResponseMessage { Content = content }; return Task.FromResult(response); } } }
32.066667
107
0.686071
[ "Apache-2.0" ]
AppliedSystems/IdentityServer3
source/Core/Results/WelcomeActionResult.cs
1,926
C#
using System; using System.Collections.Generic; using GSM.Software; namespace GSM.Tests.Software { class CallHistoryTest : Test { // Private Fields private readonly CallHistory callHistory = null; // Constructors public CallHistoryTest(CallHistory callHistory) { this.callHistory = callHistory; } // Methods public void GetPrice(decimal price) { List<string> info = new List<string>(); info.Add(String.Format("Minutes: {0}", this.callHistory.GetStartedMinutes())); info.Add(String.Format("Price {0}: {1:c}", price, this.callHistory.CalculatePrice(price))); Print("Calculating price", String.Join(Environment.NewLine, info)); } public void Remove(long id) { List<string> info = new List<string>(); info.Add(String.Format("Removed: {0}", this.callHistory.Get(id).ToString())); this.callHistory.Remove(id); info.Add("Remaining:"); info.Add(this.callHistory.ToString()); Print("Removing a call ID", String.Join(Environment.NewLine, info)); } public void RemoveLongestCall() { Call longestCall = this.callHistory.GetLongestCall(); this.callHistory.Remove(longestCall); Print("Remove longest call", longestCall.ToString()); } public void ClearHistory() { this.callHistory.Clear(); Print("Clear history", this.callHistory.ToString()); } } }
27.186441
103
0.581671
[ "MIT" ]
trinityimma/TelerikAcademy
Programming/3.ObjectOrientedProgramming/1.DefiningClassesPartOne/1.GSM.Tests/Software/CallHistoryTest.cs
1,604
C#
using Common.Logging; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Discount.Grpc.Extensions; using Serilog; namespace Discount.Grpc { public class Program { public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); host.MigrateDatabase<Program>(); host.Run(); } // Additional configuration is required to successfully run gRPC on macOS. // For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682 public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSerilog(SeriLogger.configure) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
32.172414
136
0.628081
[ "MIT" ]
rahulsahay19/Ecommerce-ASPNet
src/Services/Discount/Discount.Grpc/Program.cs
933
C#
using System; using System.Text; using System.Windows.Controls; using ICSharpCode.AvalonEdit; using ConscriptDesigner.Control; using ConscriptDesigner.Anchorables; using System.IO; namespace ConscriptDesigner.Content { /// <summary>A content file representing .conscript extension.</summary> public class ContentScript : ContentFile { /// <summary>Cached text used for searching.</summary> private string cachedText; //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- /// <summary>Conscructs the content script.</summary> public ContentScript(string name) : base(name) { this.cachedText = null; TreeViewItem.Source = DesignerImages.ConscriptFile; XmlInfo.ElementName = "None"; XmlInfo.CopyToOutputDirectory = "PreserveNewest"; } //----------------------------------------------------------------------------- // Script Navigatiuon //----------------------------------------------------------------------------- /// <summary>Loads the file text into the cache.</summary> public bool LoadText() { try { cachedText = File.ReadAllText(FilePath, Encoding.UTF8); return true; } catch (Exception ex) { DesignerControl.ShowExceptionMessage(ex, "search", Name); return false; } } /// <summary>Cleras the file text in the cache.</summary> public void UnloadText() { cachedText = null; } /// <summary>Navigates to the location in the file.</summary> public void GotoLocation(int line, int column) { if (!IsOpen) { if (!Open(false)) return; } Document.IsActive = true; Editor.GotoLocation(line, column); } /// <summary>Selects text in the editor.</summary> public void SelectText(int start, int length, bool focus) { if (!IsOpen) { if (!Open(false)) return; } Document.IsActive = true; Editor.SelectText(start, length, focus); } //----------------------------------------------------------------------------- // Override Events //----------------------------------------------------------------------------- /// <summary>Called when the file is opened.</summary> protected override void OnOpen() { Document = new ConscriptEditor(this); cachedText = null; Editor.FocusEditor(); } /// <summary>Called when the file is closed.</summary> protected override void OnClose() { } /// <summary>Called when the file is reloaded.</summary> protected override void OnReload() { Editor.Reload(); } /// <summary>Called when the file is saved.</summary> protected override void OnSave() { if (IsOpen) { Editor.Save(); } else if (cachedText != null) { File.WriteAllText(FilePath, cachedText, Encoding.UTF8); cachedText = null; } } /// <summary>Called when the file is renamed.</summary> protected override void OnRename() { if (IsOpen) { Editor.UpdateTitle(); } } /// <summary>Called during undo.</summary> protected override void OnUndo() { Editor.Undo(); } /// <summary>Called during redo.</summary> protected override void OnRedo() { Editor.Redo(); } /// <summary>Called when the modified override is changed.</summary> protected override void OnModifiedChanged() { if (IsOpen) { Editor.UpdateTitle(); } } /// <summary>Called when the file becomes outdated.</summary> protected override void OnFileOutdated() { cachedText = null; } //----------------------------------------------------------------------------- // Override Context Menu //----------------------------------------------------------------------------- /// <summary>Creates the context menu for the tree view item.</summary> protected override void CreateContextMenu(ContextMenu menu) { AddOpenContextMenuItem(menu); AddSeparatorContextMenuItem(menu); AddExcludeContextMenuItem(menu); AddSeparatorContextMenuItem(menu); AddClipboardContextMenuItems(menu, false); AddRenameContextMenuItem(menu); } //----------------------------------------------------------------------------- // Override Properties //----------------------------------------------------------------------------- /// <summary>Gets the type of the content file.</summary> public override ContentTypes ContentType { get { return ContentTypes.Conscript; } } /// <summary>Gets if the file is modified.</summary> protected override bool IsModifiedInternal { get { if (IsOpen) return Editor.IsModified; return false; } } /// <summary>Gets if the content file can undo any actions.</summary> public override bool CanUndo { get { if (IsOpen) return Editor.CanUndo; return false; } } /// <summary>Gets if the content file can redo any actions.</summary> public override bool CanRedo { get { if (IsOpen) return Editor.CanRedo; return false; } } //----------------------------------------------------------------------------- // Internal Properties //----------------------------------------------------------------------------- /// <summary>Gets the document as a conscript editor.</summary> private ConscriptEditor Editor { get { return Document as ConscriptEditor; } } //----------------------------------------------------------------------------- // Properties //----------------------------------------------------------------------------- /// <summary>Gets the loaded text either from the editor or the cache.</summary> public string LoadedText { get { if (IsOpen) return Editor.Text; return cachedText; } set { if (IsOpen) throw new Exception("Cannot set loaded text when conscript is open!"); cachedText = value; } } /// <summary>Gets the text selected in the editor.</summary> public string SelectedText { get { if (IsOpen) return Editor.SelectedText; return null; } } /// <summary>Gets the text editor control.</summary> public TextEditor TextEditor { get { if (IsOpen) return Editor.TextEditor; return null; } } } }
26.370213
82
0.547846
[ "MIT" ]
trigger-death/ZeldaOracle
ZeldaOracle/ConscriptDesigner/Content/ContentScript.cs
6,199
C#
#region License /* * Ext.cs * * Some parts of this code are derived from Mono (http://www.mono-project.com): * - GetStatusDescription is derived from HttpListenerResponse.cs (System.Net) * - IsPredefinedScheme is derived from Uri.cs (System) * - MaybeUri is derived from Uri.cs (System) * * The MIT License * * Copyright (c) 2001 Garrett Rooney * Copyright (c) 2003 Ian MacLean * Copyright (c) 2003 Ben Maurer * Copyright (c) 2003, 2005, 2009 Novell, Inc. (http://www.novell.com) * Copyright (c) 2009 Stephane Delcroix * Copyright (c) 2010-2016 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contributors /* * Contributors: * - Liryna <liryna.stark@gmail.com> * - Nikola Kovacevic <nikolak@outlook.com> * - Chris Swiedler */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.Compression; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; using WebSocketSharp.Server; namespace WebSocketSharp { /// <summary> /// Provides a set of static methods for websocket-sharp. /// </summary> public static class Ext { #region Private Fields private static readonly byte[] _last = new byte[] { 0x00 }; private static readonly int _retry = 5; private const string _tspecials = "()<>@,;:\\\"/[]?={} \t"; #endregion #region Private Methods private static byte[] compress (this byte[] data) { if (data.LongLength == 0) //return new byte[] { 0x00, 0x00, 0x00, 0xff, 0xff }; return data; using (var input = new MemoryStream (data)) return input.compressToArray (); } private static MemoryStream compress (this Stream stream) { var output = new MemoryStream (); if (stream.Length == 0) return output; stream.Position = 0; using (var ds = new DeflateStream (output, CompressionMode.Compress, true)) { stream.CopyTo (ds, 1024); ds.Close (); // BFINAL set to 1. output.Write (_last, 0, 1); output.Position = 0; return output; } } private static byte[] compressToArray (this Stream stream) { using (var output = stream.compress ()) { output.Close (); return output.ToArray (); } } private static byte[] decompress (this byte[] data) { if (data.LongLength == 0) return data; using (var input = new MemoryStream (data)) return input.decompressToArray (); } private static MemoryStream decompress (this Stream stream) { var output = new MemoryStream (); if (stream.Length == 0) return output; stream.Position = 0; using (var ds = new DeflateStream (stream, CompressionMode.Decompress, true)) { ds.CopyTo (output, 1024); output.Position = 0; return output; } } private static byte[] decompressToArray (this Stream stream) { using (var output = stream.decompress ()) { output.Close (); return output.ToArray (); } } private static void times (this ulong n, Action action) { for (ulong i = 0; i < n; i++) action (); } #endregion #region Internal Methods internal static byte[] Append (this ushort code, string reason) { var ret = code.InternalToByteArray (ByteOrder.Big); if (reason != null && reason.Length > 0) { var buff = new List<byte> (ret); buff.AddRange (Encoding.UTF8.GetBytes (reason)); ret = buff.ToArray (); } return ret; } internal static string CheckIfAvailable ( this ServerState state, bool ready, bool start, bool shutting) { return (!ready && (state == ServerState.Ready || state == ServerState.Stop)) || (!start && state == ServerState.Start) || (!shutting && state == ServerState.ShuttingDown) ? "This operation isn't available in: " + state.ToString ().ToLower () : null; } internal static string CheckIfAvailable ( this WebSocketState state, bool connecting, bool open, bool closing, bool closed) { return (!connecting && state == WebSocketState.Connecting) || (!open && state == WebSocketState.Open) || (!closing && state == WebSocketState.Closing) || (!closed && state == WebSocketState.Closed) ? "This operation isn't available in: " + state.ToString ().ToLower () : null; } internal static string CheckIfValidProtocols (this string[] protocols) { return protocols.Contains ( protocol => protocol == null || protocol.Length == 0 || !protocol.IsToken ()) ? "Contains an invalid value." : protocols.ContainsTwice () ? "Contains a value twice." : null; } internal static string CheckIfValidServicePath (this string path) { return path == null || path.Length == 0 ? "'path' is null or empty." : path[0] != '/' ? "'path' isn't an absolute path." : path.IndexOfAny (new[] { '?', '#' }) > -1 ? "'path' includes either or both query and fragment components." : null; } internal static string CheckIfValidSessionID (this string id) { return id == null || id.Length == 0 ? "'id' is null or empty." : null; } internal static string CheckIfValidWaitTime (this TimeSpan time) { return time <= TimeSpan.Zero ? "A wait time is zero or less." : null; } internal static bool CheckWaitTime (this TimeSpan time, out string message) { message = null; if (time <= TimeSpan.Zero) { message = "A wait time is zero or less."; return false; } return true; } internal static void Close (this HttpListenerResponse response, HttpStatusCode code) { response.StatusCode = (int) code; response.OutputStream.Close (); } internal static void CloseWithAuthChallenge ( this HttpListenerResponse response, string challenge) { response.Headers.InternalSet ("WWW-Authenticate", challenge, true); response.Close (HttpStatusCode.Unauthorized); } internal static byte[] Compress (this byte[] data, CompressionMethod method) { return method == CompressionMethod.Deflate ? data.compress () : data; } internal static Stream Compress (this Stream stream, CompressionMethod method) { return method == CompressionMethod.Deflate ? stream.compress () : stream; } internal static byte[] CompressToArray (this Stream stream, CompressionMethod method) { return method == CompressionMethod.Deflate ? stream.compressToArray () : stream.ToByteArray (); } internal static bool Contains<T> (this IEnumerable<T> source, Func<T, bool> condition) { foreach (T elm in source) if (condition (elm)) return true; return false; } internal static bool ContainsTwice (this string[] values) { var len = values.Length; Func<int, bool> contains = null; contains = idx => { if (idx < len - 1) { for (var i = idx + 1; i < len; i++) if (values[i] == values[idx]) return true; return contains (++idx); } return false; }; return contains (0); } internal static T[] Copy<T> (this T[] source, int length) { var dest = new T[length]; Array.Copy (source, 0, dest, 0, length); return dest; } internal static T[] Copy<T> (this T[] source, long length) { var dest = new T[length]; Array.Copy (source, 0, dest, 0, length); return dest; } internal static void CopyTo (this Stream source, Stream destination, int bufferLength) { var buff = new byte[bufferLength]; var nread = 0; while ((nread = source.Read (buff, 0, bufferLength)) > 0) destination.Write (buff, 0, nread); } internal static void CopyToAsync ( this Stream source, Stream destination, int bufferLength, Action completed, Action<Exception> error) { var buff = new byte[bufferLength]; AsyncCallback callback = null; callback = ar => { try { var nread = source.EndRead (ar); if (nread <= 0) { if (completed != null) completed (); return; } destination.Write (buff, 0, nread); source.BeginRead (buff, 0, bufferLength, callback, null); } catch (Exception ex) { if (error != null) error (ex); } }; try { source.BeginRead (buff, 0, bufferLength, callback, null); } catch (Exception ex) { if (error != null) error (ex); } } internal static byte[] Decompress (this byte[] data, CompressionMethod method) { return method == CompressionMethod.Deflate ? data.decompress () : data; } internal static Stream Decompress (this Stream stream, CompressionMethod method) { return method == CompressionMethod.Deflate ? stream.decompress () : stream; } internal static byte[] DecompressToArray (this Stream stream, CompressionMethod method) { return method == CompressionMethod.Deflate ? stream.decompressToArray () : stream.ToByteArray (); } /// <summary> /// Determines whether the specified <see cref="int"/> equals the specified <see cref="char"/>, /// and invokes the specified <c>Action&lt;int&gt;</c> delegate at the same time. /// </summary> /// <returns> /// <c>true</c> if <paramref name="value"/> equals <paramref name="c"/>; /// otherwise, <c>false</c>. /// </returns> /// <param name="value"> /// An <see cref="int"/> to compare. /// </param> /// <param name="c"> /// A <see cref="char"/> to compare. /// </param> /// <param name="action"> /// An <c>Action&lt;int&gt;</c> delegate that references the method(s) called /// at the same time as comparing. An <see cref="int"/> parameter to pass to /// the method(s) is <paramref name="value"/>. /// </param> internal static bool EqualsWith (this int value, char c, Action<int> action) { action (value); return value == c - 0; } /// <summary> /// Gets the absolute path from the specified <see cref="Uri"/>. /// </summary> /// <returns> /// A <see cref="string"/> that represents the absolute path if it's successfully found; /// otherwise, <see langword="null"/>. /// </returns> /// <param name="uri"> /// A <see cref="Uri"/> that represents the URI to get the absolute path from. /// </param> internal static string GetAbsolutePath (this Uri uri) { if (uri.IsAbsoluteUri) return uri.AbsolutePath; var original = uri.OriginalString; if (original[0] != '/') return null; var idx = original.IndexOfAny (new[] { '?', '#' }); return idx > 0 ? original.Substring (0, idx) : original; } internal static string GetMessage (this CloseStatusCode code) { return code == CloseStatusCode.ProtocolError ? "A WebSocket protocol error has occurred." : code == CloseStatusCode.UnsupportedData ? "Unsupported data has been received." : code == CloseStatusCode.Abnormal ? "An exception has occurred." : code == CloseStatusCode.InvalidData ? "Invalid data has been received." : code == CloseStatusCode.PolicyViolation ? "A policy violation has occurred." : code == CloseStatusCode.TooBig ? "A too big message has been received." : code == CloseStatusCode.MandatoryExtension ? "WebSocket client didn't receive expected extension(s)." : code == CloseStatusCode.ServerError ? "WebSocket server got an internal error." : code == CloseStatusCode.TlsHandshakeFailure ? "An error has occurred during a TLS handshake." : String.Empty; } /// <summary> /// Gets the name from the specified <see cref="string"/> that contains a pair of name and /// value separated by a separator character. /// </summary> /// <returns> /// A <see cref="string"/> that represents the name if any; otherwise, <c>null</c>. /// </returns> /// <param name="nameAndValue"> /// A <see cref="string"/> that contains a pair of name and value separated by /// a separator character. /// </param> /// <param name="separator"> /// A <see cref="char"/> that represents the separator character. /// </param> internal static string GetName (this string nameAndValue, char separator) { var idx = nameAndValue.IndexOf (separator); return idx > 0 ? nameAndValue.Substring (0, idx).Trim () : null; } /// <summary> /// Gets the value from the specified <see cref="string"/> that contains a pair of name and /// value separated by a separator character. /// </summary> /// <returns> /// A <see cref="string"/> that represents the value if any; otherwise, <c>null</c>. /// </returns> /// <param name="nameAndValue"> /// A <see cref="string"/> that contains a pair of name and value separated by /// a separator character. /// </param> /// <param name="separator"> /// A <see cref="char"/> that represents the separator character. /// </param> internal static string GetValue (this string nameAndValue, char separator) { var idx = nameAndValue.IndexOf (separator); return idx > -1 && idx < nameAndValue.Length - 1 ? nameAndValue.Substring (idx + 1).Trim () : null; } internal static string GetValue (this string nameAndValue, char separator, bool unquote) { var idx = nameAndValue.IndexOf (separator); if (idx < 0 || idx == nameAndValue.Length - 1) return null; var val = nameAndValue.Substring (idx + 1).Trim (); return unquote ? val.Unquote () : val; } internal static TcpListenerWebSocketContext GetWebSocketContext ( this TcpClient tcpClient, string protocol, bool secure, ServerSslConfiguration sslConfig, Logger logger) { return new TcpListenerWebSocketContext (tcpClient, protocol, secure, sslConfig, logger); } internal static byte[] InternalToByteArray (this ushort value, ByteOrder order) { var bytes = BitConverter.GetBytes (value); if (!order.IsHostOrder ()) Array.Reverse (bytes); return bytes; } internal static byte[] InternalToByteArray (this ulong value, ByteOrder order) { var bytes = BitConverter.GetBytes (value); if (!order.IsHostOrder ()) Array.Reverse (bytes); return bytes; } internal static bool IsCompressionExtension (this string value, CompressionMethod method) { return value.StartsWith (method.ToExtensionString ()); } internal static bool IsControl (this byte opcode) { return opcode > 0x7 && opcode < 0x10; } internal static bool IsControl (this Opcode opcode) { return opcode >= Opcode.Close; } internal static bool IsData (this byte opcode) { return opcode == 0x1 || opcode == 0x2; } internal static bool IsData (this Opcode opcode) { return opcode == Opcode.Text || opcode == Opcode.Binary; } internal static bool IsPortNumber (this int value) { return value > 0 && value < 65536; } internal static bool IsReserved (this ushort code) { return code == 1004 || code == 1005 || code == 1006 || code == 1015; } internal static bool IsReserved (this CloseStatusCode code) { return code == CloseStatusCode.Undefined || code == CloseStatusCode.NoStatus || code == CloseStatusCode.Abnormal || code == CloseStatusCode.TlsHandshakeFailure; } internal static bool IsSupported (this byte opcode) { return Enum.IsDefined (typeof (Opcode), opcode); } internal static bool IsText (this string value) { var len = value.Length; for (var i = 0; i < len; i++) { var c = value[i]; if (c < 0x20 && !"\r\n\t".Contains (c)) return false; if (c == 0x7f) return false; if (c == '\n' && ++i < len) { c = value[i]; if (!" \t".Contains (c)) return false; } } return true; } internal static bool IsToken (this string value) { foreach (var c in value) if (c < 0x20 || c >= 0x7f || _tspecials.Contains (c)) return false; return true; } internal static string Quote (this string value) { return String.Format ("\"{0}\"", value.Replace ("\"", "\\\"")); } internal static byte[] ReadBytes (this Stream stream, int length) { var buff = new byte[length]; var offset = 0; try { var nread = 0; while (length > 0) { nread = stream.Read (buff, offset, length); if (nread == 0) break; offset += nread; length -= nread; } } catch { } return buff.SubArray (0, offset); } internal static byte[] ReadBytes (this Stream stream, long length, int bufferLength) { using (var dest = new MemoryStream ()) { try { var buff = new byte[bufferLength]; var nread = 0; while (length > 0) { if (length < bufferLength) bufferLength = (int) length; nread = stream.Read (buff, 0, bufferLength); if (nread == 0) break; dest.Write (buff, 0, nread); length -= nread; } } catch { } dest.Close (); return dest.ToArray (); } } internal static void ReadBytesAsync ( this Stream stream, int length, Action<byte[]> completed, Action<Exception> error ) { var buff = new byte[length]; var offset = 0; var retry = 0; AsyncCallback callback = null; callback = ar => { try { var nread = stream.EndRead (ar); if (nread == 0 && retry < _retry) { retry++; stream.BeginRead (buff, offset, length, callback, null); return; } if (nread == 0 || nread == length) { if (completed != null) completed (buff.SubArray (0, offset + nread)); return; } retry = 0; offset += nread; length -= nread; stream.BeginRead (buff, offset, length, callback, null); } catch (Exception ex) { if (error != null) error (ex); } }; try { stream.BeginRead (buff, offset, length, callback, null); } catch (Exception ex) { if (error != null) error (ex); } } internal static void ReadBytesAsync ( this Stream stream, long length, int bufferLength, Action<byte[]> completed, Action<Exception> error ) { var dest = new MemoryStream (); var buff = new byte[bufferLength]; var retry = 0; Action<long> read = null; read = len => { if (len < bufferLength) bufferLength = (int) len; stream.BeginRead ( buff, 0, bufferLength, ar => { try { var nread = stream.EndRead (ar); if (nread > 0) dest.Write (buff, 0, nread); if (nread == 0 && retry < _retry) { retry++; read (len); return; } if (nread == 0 || nread == len) { if (completed != null) { dest.Close (); completed (dest.ToArray ()); } dest.Dispose (); return; } retry = 0; read (len - nread); } catch (Exception ex) { dest.Dispose (); if (error != null) error (ex); } }, null ); }; try { read (length); } catch (Exception ex) { dest.Dispose (); if (error != null) error (ex); } } internal static string RemovePrefix (this string value, params string[] prefixes) { var idx = 0; foreach (var prefix in prefixes) { if (value.StartsWith (prefix)) { idx = prefix.Length; break; } } return idx > 0 ? value.Substring (idx) : value; } internal static T[] Reverse<T> (this T[] array) { var len = array.Length; var reverse = new T[len]; var end = len - 1; for (var i = 0; i <= end; i++) reverse[i] = array[end - i]; return reverse; } internal static IEnumerable<string> SplitHeaderValue ( this string value, params char[] separators) { var len = value.Length; var seps = new string (separators); var buff = new StringBuilder (32); var escaped = false; var quoted = false; for (var i = 0; i < len; i++) { var c = value[i]; if (c == '"') { if (escaped) escaped = !escaped; else quoted = !quoted; } else if (c == '\\') { if (i < len - 1 && value[i + 1] == '"') escaped = true; } else if (seps.Contains (c)) { if (!quoted) { yield return buff.ToString (); buff.Length = 0; continue; } } else { } buff.Append (c); } if (buff.Length > 0) yield return buff.ToString (); } internal static byte[] ToByteArray (this Stream stream) { using (var output = new MemoryStream ()) { stream.Position = 0; stream.CopyTo (output, 1024); output.Close (); return output.ToArray (); } } internal static CompressionMethod ToCompressionMethod (this string value) { foreach (CompressionMethod method in Enum.GetValues (typeof (CompressionMethod))) if (method.ToExtensionString () == value) return method; return CompressionMethod.None; } internal static string ToExtensionString ( this CompressionMethod method, params string[] parameters) { if (method == CompressionMethod.None) return String.Empty; var m = String.Format ("permessage-{0}", method.ToString ().ToLower ()); if (parameters == null || parameters.Length == 0) return m; return String.Format ("{0}; {1}", m, parameters.ToString ("; ")); } internal static System.Net.IPAddress ToIPAddress (this string value) { if (value == null || value.Length == 0) return null; System.Net.IPAddress addr; if (System.Net.IPAddress.TryParse (value, out addr)) return addr; try { var addrs = System.Net.Dns.GetHostAddresses (value); return addrs[0]; } catch { return null; } } internal static List<TSource> ToList<TSource> (this IEnumerable<TSource> source) { return new List<TSource> (source); } internal static ushort ToUInt16 (this byte[] source, ByteOrder sourceOrder) { return BitConverter.ToUInt16 (source.ToHostOrder (sourceOrder), 0); } internal static ulong ToUInt64 (this byte[] source, ByteOrder sourceOrder) { return BitConverter.ToUInt64 (source.ToHostOrder (sourceOrder), 0); } internal static string TrimSlashFromEnd (this string value) { var ret = value.TrimEnd ('/'); return ret.Length > 0 ? ret : "/"; } /// <summary> /// Tries to create a new <see cref="Uri"/> for WebSocket with /// the specified <paramref name="uriString"/>. /// </summary> /// <returns> /// <c>true</c> if the <see cref="Uri"/> was successfully created; /// otherwise, <c>false</c>. /// </returns> /// <param name="uriString"> /// A <see cref="string"/> that represents a WebSocket URL to try. /// </param> /// <param name="result"> /// When this method returns, a <see cref="Uri"/> that /// represents the WebSocket URL or <see langword="null"/> /// if <paramref name="uriString"/> is invalid. /// </param> /// <param name="message"> /// When this method returns, a <see cref="string"/> that /// represents an error message or <see langword="null"/> /// if <paramref name="uriString"/> is valid. /// </param> internal static bool TryCreateWebSocketUri ( this string uriString, out Uri result, out string message ) { result = null; message = null; var uri = uriString.ToUri (); if (uri == null) { message = "An invalid URI string."; return false; } if (!uri.IsAbsoluteUri) { message = "A relative URI."; return false; } var schm = uri.Scheme; if (!(schm == "ws" || schm == "wss")) { message = "The scheme part is not 'ws' or 'wss'."; return false; } var port = uri.Port; if (port == 0) { message = "The port part is zero."; return false; } if (uri.Fragment.Length > 0) { message = "It includes the fragment component."; return false; } result = port != -1 ? uri : new Uri ( String.Format ( "{0}://{1}:{2}{3}", schm, uri.Host, schm == "ws" ? 80 : 443, uri.PathAndQuery ) ); return true; } internal static bool TryGetUTF8DecodedString (this byte[] bytes, out string s) { s = null; try { s = Encoding.UTF8.GetString (bytes); } catch { return false; } return true; } internal static bool TryGetUTF8EncodedBytes (this string s, out byte[] bytes) { bytes = null; try { bytes = Encoding.UTF8.GetBytes (s); } catch { return false; } return true; } internal static bool TryOpenRead ( this FileInfo fileInfo, out FileStream fileStream ) { fileStream = null; try { fileStream = fileInfo.OpenRead (); } catch { return false; } return true; } internal static string Unquote (this string value) { var start = value.IndexOf ('"'); if (start < 0) return value; var end = value.LastIndexOf ('"'); var len = end - start - 1; return len < 0 ? value : len == 0 ? String.Empty : value.Substring (start + 1, len).Replace ("\\\"", "\""); } internal static string UTF8Decode (this byte[] bytes) { try { return Encoding.UTF8.GetString (bytes); } catch { return null; } } internal static byte[] UTF8Encode (this string s) { return Encoding.UTF8.GetBytes (s); } internal static void WriteBytes (this Stream stream, byte[] bytes, int bufferLength) { using (var input = new MemoryStream (bytes)) input.CopyTo (stream, bufferLength); } internal static void WriteBytesAsync ( this Stream stream, byte[] bytes, int bufferLength, Action completed, Action<Exception> error) { var input = new MemoryStream (bytes); input.CopyToAsync ( stream, bufferLength, () => { if (completed != null) completed (); input.Dispose (); }, ex => { input.Dispose (); if (error != null) error (ex); }); } #endregion #region Public Methods /// <summary> /// Determines whether the specified <see cref="string"/> contains any of characters in /// the specified array of <see cref="char"/>. /// </summary> /// <returns> /// <c>true</c> if <paramref name="value"/> contains any of <paramref name="chars"/>; /// otherwise, <c>false</c>. /// </returns> /// <param name="value"> /// A <see cref="string"/> to test. /// </param> /// <param name="chars"> /// An array of <see cref="char"/> that contains characters to find. /// </param> public static bool Contains (this string value, params char[] chars) { return chars == null || chars.Length == 0 ? true : value == null || value.Length == 0 ? false : value.IndexOfAny (chars) > -1; } /// <summary> /// Determines whether the specified <see cref="NameValueCollection"/> contains /// the entry with the specified <paramref name="name"/>. /// </summary> /// <returns> /// <c>true</c> if <paramref name="collection"/> contains the entry with /// <paramref name="name"/>; otherwise, <c>false</c>. /// </returns> /// <param name="collection"> /// A <see cref="NameValueCollection"/> to test. /// </param> /// <param name="name"> /// A <see cref="string"/> that represents the key of the entry to find. /// </param> public static bool Contains (this NameValueCollection collection, string name) { return collection != null && collection.Count > 0 ? collection[name] != null : false; } /// <summary> /// Determines whether the specified <see cref="NameValueCollection"/> contains the entry with /// the specified both <paramref name="name"/> and <paramref name="value"/>. /// </summary> /// <returns> /// <c>true</c> if <paramref name="collection"/> contains the entry with both /// <paramref name="name"/> and <paramref name="value"/>; otherwise, <c>false</c>. /// </returns> /// <param name="collection"> /// A <see cref="NameValueCollection"/> to test. /// </param> /// <param name="name"> /// A <see cref="string"/> that represents the key of the entry to find. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the value of the entry to find. /// </param> public static bool Contains (this NameValueCollection collection, string name, string value) { if (collection == null || collection.Count == 0) return false; var vals = collection[name]; if (vals == null) return false; foreach (var val in vals.Split (',')) if (val.Trim ().Equals (value, StringComparison.OrdinalIgnoreCase)) return true; return false; } /// <summary> /// Emits the specified <see cref="EventHandler"/> delegate if it isn't <see langword="null"/>. /// </summary> /// <param name="eventHandler"> /// A <see cref="EventHandler"/> to emit. /// </param> /// <param name="sender"> /// An <see cref="object"/> from which emits this <paramref name="eventHandler"/>. /// </param> /// <param name="e"> /// A <see cref="EventArgs"/> that contains no event data. /// </param> public static void Emit (this EventHandler eventHandler, object sender, EventArgs e) { if (eventHandler != null) eventHandler (sender, e); } /// <summary> /// Emits the specified <c>EventHandler&lt;TEventArgs&gt;</c> delegate if it isn't /// <see langword="null"/>. /// </summary> /// <param name="eventHandler"> /// An <c>EventHandler&lt;TEventArgs&gt;</c> to emit. /// </param> /// <param name="sender"> /// An <see cref="object"/> from which emits this <paramref name="eventHandler"/>. /// </param> /// <param name="e"> /// A <c>TEventArgs</c> that represents the event data. /// </param> /// <typeparam name="TEventArgs"> /// The type of the event data generated by the event. /// </typeparam> public static void Emit<TEventArgs> ( this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs e) where TEventArgs : EventArgs { if (eventHandler != null) eventHandler (sender, e); } /// <summary> /// Gets the collection of the HTTP cookies from the specified HTTP <paramref name="headers"/>. /// </summary> /// <returns> /// A <see cref="CookieCollection"/> that receives a collection of the HTTP cookies. /// </returns> /// <param name="headers"> /// A <see cref="NameValueCollection"/> that contains a collection of the HTTP headers. /// </param> /// <param name="response"> /// <c>true</c> if <paramref name="headers"/> is a collection of the response headers; /// otherwise, <c>false</c>. /// </param> public static CookieCollection GetCookies (this NameValueCollection headers, bool response) { var name = response ? "Set-Cookie" : "Cookie"; return headers != null && headers.Contains (name) ? CookieCollection.Parse (headers[name], response) : new CookieCollection (); } /// <summary> /// Gets the description of the specified HTTP status <paramref name="code"/>. /// </summary> /// <returns> /// A <see cref="string"/> that represents the description of the HTTP status code. /// </returns> /// <param name="code"> /// One of <see cref="HttpStatusCode"/> enum values, indicates the HTTP status code. /// </param> public static string GetDescription (this HttpStatusCode code) { return ((int) code).GetStatusDescription (); } /// <summary> /// Gets the description of the specified HTTP status <paramref name="code"/>. /// </summary> /// <returns> /// A <see cref="string"/> that represents the description of the HTTP status code. /// </returns> /// <param name="code"> /// An <see cref="int"/> that represents the HTTP status code. /// </param> public static string GetStatusDescription (this int code) { switch (code) { case 100: return "Continue"; case 101: return "Switching Protocols"; case 102: return "Processing"; case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; case 207: return "Multi-Status"; case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 307: return "Temporary Redirect"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-Uri Too Long"; case 415: return "Unsupported Media Type"; case 416: return "Requested Range Not Satisfiable"; case 417: return "Expectation Failed"; case 422: return "Unprocessable Entity"; case 423: return "Locked"; case 424: return "Failed Dependency"; case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Timeout"; case 505: return "Http Version Not Supported"; case 507: return "Insufficient Storage"; } return String.Empty; } /// <summary> /// Determines whether the specified <see cref="ushort"/> is in the /// range of the status code for the WebSocket connection close. /// </summary> /// <remarks> /// <para> /// The ranges for the status code for the close are the following: /// </para> /// <list type="bullet"> /// <item> /// <term> /// 1000-2999: These numbers are reserved for definition by /// the WebSocket protocol. /// </term> /// </item> /// <item> /// <term> /// 3000-3999: These numbers are reserved for use by libraries, /// frameworks, and applications. /// </term> /// </item> /// <item> /// <term> /// 4000-4999: These numbers are reserved for private use. /// </term> /// </item> /// </list> /// </remarks> /// <returns> /// <c>true</c> if <paramref name="value"/> is in the range of /// the status code for the close; otherwise, <c>false</c>. /// </returns> /// <param name="value"> /// A <see cref="ushort"/> to test. /// </param> public static bool IsCloseStatusCode (this ushort value) { return value > 999 && value < 5000; } /// <summary> /// Determines whether the specified <see cref="string"/> is /// enclosed in the specified <see cref="char"/>. /// </summary> /// <returns> /// <c>true</c> if <paramref name="value"/> is enclosed in /// <paramref name="c"/>; otherwise, <c>false</c>. /// </returns> /// <param name="value"> /// A <see cref="string"/> to test. /// </param> /// <param name="c"> /// A <see cref="char"/> to find. /// </param> public static bool IsEnclosedIn (this string value, char c) { return value != null && value.Length > 1 && value[0] == c && value[value.Length - 1] == c; } /// <summary> /// Determines whether the specified <see cref="ByteOrder"/> is host (this computer /// architecture) byte order. /// </summary> /// <returns> /// <c>true</c> if <paramref name="order"/> is host byte order; otherwise, <c>false</c>. /// </returns> /// <param name="order"> /// One of the <see cref="ByteOrder"/> enum values, to test. /// </param> public static bool IsHostOrder (this ByteOrder order) { // true: !(true ^ true) or !(false ^ false) // false: !(true ^ false) or !(false ^ true) return !(BitConverter.IsLittleEndian ^ (order == ByteOrder.Little)); } /// <summary> /// Determines whether the specified <see cref="System.Net.IPAddress"/> /// represents a local IP address. /// </summary> /// <remarks> /// This local means NOT REMOTE for the current host. /// </remarks> /// <returns> /// <c>true</c> if <paramref name="address"/> represents a local IP address; /// otherwise, <c>false</c>. /// </returns> /// <param name="address"> /// A <see cref="System.Net.IPAddress"/> to test. /// </param> public static bool IsLocal (this System.Net.IPAddress address) { if (address == null) return false; if (address.Equals (System.Net.IPAddress.Any)) return true; if (address.Equals (System.Net.IPAddress.Loopback)) return true; if (Socket.OSSupportsIPv6) { if (address.Equals (System.Net.IPAddress.IPv6Any)) return true; if (address.Equals (System.Net.IPAddress.IPv6Loopback)) return true; } var host = System.Net.Dns.GetHostName (); var addrs = System.Net.Dns.GetHostAddresses (host); foreach (var addr in addrs) { if (address.Equals (addr)) return true; } return false; } /// <summary> /// Determines whether the specified <see cref="string"/> is /// <see langword="null"/> or an empty string. /// </summary> /// <returns> /// <c>true</c> if <paramref name="value"/> is <see langword="null"/> or /// an empty string; otherwise, <c>false</c>. /// </returns> /// <param name="value"> /// A <see cref="string"/> to test. /// </param> public static bool IsNullOrEmpty (this string value) { return value == null || value.Length == 0; } /// <summary> /// Determines whether the specified <see cref="string"/> is /// a predefined scheme. /// </summary> /// <returns> /// <c>true</c> if <paramref name="value"/> is a predefined scheme; /// otherwise, <c>false</c>. /// </returns> /// <param name="value"> /// A <see cref="string"/> to test. /// </param> public static bool IsPredefinedScheme (this string value) { if (value == null || value.Length < 2) return false; var c = value[0]; if (c == 'h') return value == "http" || value == "https"; if (c == 'w') return value == "ws" || value == "wss"; if (c == 'f') return value == "file" || value == "ftp"; if (c == 'g') return value == "gopher"; if (c == 'm') return value == "mailto"; if (c == 'n') { c = value[1]; return c == 'e' ? value == "news" || value == "net.pipe" || value == "net.tcp" : value == "nntp"; } return false; } /// <summary> /// Determines whether the specified <see cref="HttpListenerRequest"/> is /// an HTTP Upgrade request to switch to the specified <paramref name="protocol"/>. /// </summary> /// <returns> /// <c>true</c> if <paramref name="request"/> is an HTTP Upgrade request to switch to /// <paramref name="protocol"/>; otherwise, <c>false</c>. /// </returns> /// <param name="request"> /// A <see cref="HttpListenerRequest"/> that represents the HTTP request. /// </param> /// <param name="protocol"> /// A <see cref="string"/> that represents the protocol name. /// </param> /// <exception cref="ArgumentNullException"> /// <para> /// <paramref name="request"/> is <see langword="null"/>. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="protocol"/> is <see langword="null"/>. /// </para> /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="protocol"/> is empty. /// </exception> public static bool IsUpgradeTo (this HttpListenerRequest request, string protocol) { if (request == null) throw new ArgumentNullException ("request"); if (protocol == null) throw new ArgumentNullException ("protocol"); if (protocol.Length == 0) throw new ArgumentException ("An empty string.", "protocol"); return request.Headers.Contains ("Upgrade", protocol) && request.Headers.Contains ("Connection", "Upgrade"); } /// <summary> /// Determines whether the specified <see cref="string"/> is a URI string. /// </summary> /// <returns> /// <c>true</c> if <paramref name="value"/> may be a URI string; /// otherwise, <c>false</c>. /// </returns> /// <param name="value"> /// A <see cref="string"/> to test. /// </param> public static bool MaybeUri (this string value) { if (value == null || value.Length == 0) return false; var idx = value.IndexOf (':'); if (idx == -1) return false; if (idx >= 10) return false; var schm = value.Substring (0, idx); return schm.IsPredefinedScheme (); } /// <summary> /// Retrieves a sub-array from the specified <paramref name="array"/>. A sub-array starts at /// the specified element position in <paramref name="array"/>. /// </summary> /// <returns> /// An array of T that receives a sub-array, or an empty array of T if any problems with /// the parameters. /// </returns> /// <param name="array"> /// An array of T from which to retrieve a sub-array. /// </param> /// <param name="startIndex"> /// An <see cref="int"/> that represents the zero-based starting position of /// a sub-array in <paramref name="array"/>. /// </param> /// <param name="length"> /// An <see cref="int"/> that represents the number of elements to retrieve. /// </param> /// <typeparam name="T"> /// The type of elements in <paramref name="array"/>. /// </typeparam> public static T[] SubArray<T> (this T[] array, int startIndex, int length) { int len; if (array == null || (len = array.Length) == 0) return new T[0]; if (startIndex < 0 || length <= 0 || startIndex + length > len) return new T[0]; if (startIndex == 0 && length == len) return array; var subArray = new T[length]; Array.Copy (array, startIndex, subArray, 0, length); return subArray; } /// <summary> /// Retrieves a sub-array from the specified <paramref name="array"/>. A sub-array starts at /// the specified element position in <paramref name="array"/>. /// </summary> /// <returns> /// An array of T that receives a sub-array, or an empty array of T if any problems with /// the parameters. /// </returns> /// <param name="array"> /// An array of T from which to retrieve a sub-array. /// </param> /// <param name="startIndex"> /// A <see cref="long"/> that represents the zero-based starting position of /// a sub-array in <paramref name="array"/>. /// </param> /// <param name="length"> /// A <see cref="long"/> that represents the number of elements to retrieve. /// </param> /// <typeparam name="T"> /// The type of elements in <paramref name="array"/>. /// </typeparam> public static T[] SubArray<T> (this T[] array, long startIndex, long length) { long len; if (array == null || (len = array.LongLength) == 0) return new T[0]; if (startIndex < 0 || length <= 0 || startIndex + length > len) return new T[0]; if (startIndex == 0 && length == len) return array; var subArray = new T[length]; Array.Copy (array, startIndex, subArray, 0, length); return subArray; } /// <summary> /// Executes the specified <see cref="Action"/> delegate <paramref name="n"/> times. /// </summary> /// <param name="n"> /// An <see cref="int"/> is the number of times to execute. /// </param> /// <param name="action"> /// An <see cref="Action"/> delegate that references the method(s) to execute. /// </param> public static void Times (this int n, Action action) { if (n > 0 && action != null) ((ulong) n).times (action); } /// <summary> /// Executes the specified <see cref="Action"/> delegate <paramref name="n"/> times. /// </summary> /// <param name="n"> /// A <see cref="long"/> is the number of times to execute. /// </param> /// <param name="action"> /// An <see cref="Action"/> delegate that references the method(s) to execute. /// </param> public static void Times (this long n, Action action) { if (n > 0 && action != null) ((ulong) n).times (action); } /// <summary> /// Executes the specified <see cref="Action"/> delegate <paramref name="n"/> times. /// </summary> /// <param name="n"> /// A <see cref="uint"/> is the number of times to execute. /// </param> /// <param name="action"> /// An <see cref="Action"/> delegate that references the method(s) to execute. /// </param> public static void Times (this uint n, Action action) { if (n > 0 && action != null) ((ulong) n).times (action); } /// <summary> /// Executes the specified <see cref="Action"/> delegate <paramref name="n"/> times. /// </summary> /// <param name="n"> /// A <see cref="ulong"/> is the number of times to execute. /// </param> /// <param name="action"> /// An <see cref="Action"/> delegate that references the method(s) to execute. /// </param> public static void Times (this ulong n, Action action) { if (n > 0 && action != null) n.times (action); } /// <summary> /// Executes the specified <c>Action&lt;int&gt;</c> delegate <paramref name="n"/> times. /// </summary> /// <param name="n"> /// An <see cref="int"/> is the number of times to execute. /// </param> /// <param name="action"> /// An <c>Action&lt;int&gt;</c> delegate that references the method(s) to execute. /// An <see cref="int"/> parameter to pass to the method(s) is the zero-based count of /// iteration. /// </param> public static void Times (this int n, Action<int> action) { if (n > 0 && action != null) for (int i = 0; i < n; i++) action (i); } /// <summary> /// Executes the specified <c>Action&lt;long&gt;</c> delegate <paramref name="n"/> times. /// </summary> /// <param name="n"> /// A <see cref="long"/> is the number of times to execute. /// </param> /// <param name="action"> /// An <c>Action&lt;long&gt;</c> delegate that references the method(s) to execute. /// A <see cref="long"/> parameter to pass to the method(s) is the zero-based count of /// iteration. /// </param> public static void Times (this long n, Action<long> action) { if (n > 0 && action != null) for (long i = 0; i < n; i++) action (i); } /// <summary> /// Executes the specified <c>Action&lt;uint&gt;</c> delegate <paramref name="n"/> times. /// </summary> /// <param name="n"> /// A <see cref="uint"/> is the number of times to execute. /// </param> /// <param name="action"> /// An <c>Action&lt;uint&gt;</c> delegate that references the method(s) to execute. /// A <see cref="uint"/> parameter to pass to the method(s) is the zero-based count of /// iteration. /// </param> public static void Times (this uint n, Action<uint> action) { if (n > 0 && action != null) for (uint i = 0; i < n; i++) action (i); } /// <summary> /// Executes the specified <c>Action&lt;ulong&gt;</c> delegate <paramref name="n"/> times. /// </summary> /// <param name="n"> /// A <see cref="ulong"/> is the number of times to execute. /// </param> /// <param name="action"> /// An <c>Action&lt;ulong&gt;</c> delegate that references the method(s) to execute. /// A <see cref="ulong"/> parameter to pass to this method(s) is the zero-based count of /// iteration. /// </param> public static void Times (this ulong n, Action<ulong> action) { if (n > 0 && action != null) for (ulong i = 0; i < n; i++) action (i); } /// <summary> /// Converts the specified array of <see cref="byte"/> to the specified type data. /// </summary> /// <returns> /// A T converted from <paramref name="source"/>, or a default value of /// T if <paramref name="source"/> is an empty array of <see cref="byte"/> or /// if the type of T isn't <see cref="bool"/>, <see cref="char"/>, <see cref="double"/>, /// <see cref="float"/>, <see cref="int"/>, <see cref="long"/>, <see cref="short"/>, /// <see cref="uint"/>, <see cref="ulong"/>, or <see cref="ushort"/>. /// </returns> /// <param name="source"> /// An array of <see cref="byte"/> to convert. /// </param> /// <param name="sourceOrder"> /// One of the <see cref="ByteOrder"/> enum values, specifies the byte order of /// <paramref name="source"/>. /// </param> /// <typeparam name="T"> /// The type of the return. The T must be a value type. /// </typeparam> /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is <see langword="null"/>. /// </exception> public static T To<T> (this byte[] source, ByteOrder sourceOrder) where T : struct { if (source == null) throw new ArgumentNullException ("source"); if (source.Length == 0) return default (T); var type = typeof (T); var buff = source.ToHostOrder (sourceOrder); return type == typeof (Boolean) ? (T)(object) BitConverter.ToBoolean (buff, 0) : type == typeof (Char) ? (T)(object) BitConverter.ToChar (buff, 0) : type == typeof (Double) ? (T)(object) BitConverter.ToDouble (buff, 0) : type == typeof (Int16) ? (T)(object) BitConverter.ToInt16 (buff, 0) : type == typeof (Int32) ? (T)(object) BitConverter.ToInt32 (buff, 0) : type == typeof (Int64) ? (T)(object) BitConverter.ToInt64 (buff, 0) : type == typeof (Single) ? (T)(object) BitConverter.ToSingle (buff, 0) : type == typeof (UInt16) ? (T)(object) BitConverter.ToUInt16 (buff, 0) : type == typeof (UInt32) ? (T)(object) BitConverter.ToUInt32 (buff, 0) : type == typeof (UInt64) ? (T)(object) BitConverter.ToUInt64 (buff, 0) : default (T); } /// <summary> /// Converts the specified <paramref name="value"/> to an array of <see cref="byte"/>. /// </summary> /// <returns> /// An array of <see cref="byte"/> converted from <paramref name="value"/>. /// </returns> /// <param name="value"> /// A T to convert. /// </param> /// <param name="order"> /// One of the <see cref="ByteOrder"/> enum values, specifies the byte order of the return. /// </param> /// <typeparam name="T"> /// The type of <paramref name="value"/>. The T must be a value type. /// </typeparam> public static byte[] ToByteArray<T> (this T value, ByteOrder order) where T : struct { var type = typeof (T); var bytes = type == typeof (Boolean) ? BitConverter.GetBytes ((Boolean)(object) value) : type == typeof (Byte) ? new byte[] { (Byte)(object) value } : type == typeof (Char) ? BitConverter.GetBytes ((Char)(object) value) : type == typeof (Double) ? BitConverter.GetBytes ((Double)(object) value) : type == typeof (Int16) ? BitConverter.GetBytes ((Int16)(object) value) : type == typeof (Int32) ? BitConverter.GetBytes ((Int32)(object) value) : type == typeof (Int64) ? BitConverter.GetBytes ((Int64)(object) value) : type == typeof (Single) ? BitConverter.GetBytes ((Single)(object) value) : type == typeof (UInt16) ? BitConverter.GetBytes ((UInt16)(object) value) : type == typeof (UInt32) ? BitConverter.GetBytes ((UInt32)(object) value) : type == typeof (UInt64) ? BitConverter.GetBytes ((UInt64)(object) value) : WebSocket.EmptyBytes; if (bytes.Length > 1 && !order.IsHostOrder ()) Array.Reverse (bytes); return bytes; } /// <summary> /// Converts the order of the specified array of <see cref="byte"/> to the host byte order. /// </summary> /// <returns> /// An array of <see cref="byte"/> converted from <paramref name="source"/>. /// </returns> /// <param name="source"> /// An array of <see cref="byte"/> to convert. /// </param> /// <param name="sourceOrder"> /// One of the <see cref="ByteOrder"/> enum values, specifies the byte order of /// <paramref name="source"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is <see langword="null"/>. /// </exception> public static byte[] ToHostOrder (this byte[] source, ByteOrder sourceOrder) { if (source == null) throw new ArgumentNullException ("source"); return source.Length > 1 && !sourceOrder.IsHostOrder () ? source.Reverse () : source; } /// <summary> /// Converts the specified <paramref name="array"/> to a <see cref="string"/> that /// concatenates the each element of <paramref name="array"/> across the specified /// <paramref name="separator"/>. /// </summary> /// <returns> /// A <see cref="string"/> converted from <paramref name="array"/>, /// or <see cref="String.Empty"/> if <paramref name="array"/> is empty. /// </returns> /// <param name="array"> /// An array of T to convert. /// </param> /// <param name="separator"> /// A <see cref="string"/> that represents the separator string. /// </param> /// <typeparam name="T"> /// The type of elements in <paramref name="array"/>. /// </typeparam> /// <exception cref="ArgumentNullException"> /// <paramref name="array"/> is <see langword="null"/>. /// </exception> public static string ToString<T> (this T[] array, string separator) { if (array == null) throw new ArgumentNullException ("array"); var len = array.Length; if (len == 0) return String.Empty; if (separator == null) separator = String.Empty; var buff = new StringBuilder (64); (len - 1).Times (i => buff.AppendFormat ("{0}{1}", array[i].ToString (), separator)); buff.Append (array[len - 1].ToString ()); return buff.ToString (); } /// <summary> /// Converts the specified <see cref="string"/> to a <see cref="Uri"/>. /// </summary> /// <returns> /// A <see cref="Uri"/> converted from <paramref name="value"/> or /// <see langword="null"/> if the convert has failed. /// </returns> /// <param name="value"> /// A <see cref="string"/> to convert. /// </param> public static Uri ToUri (this string value) { Uri ret; Uri.TryCreate ( value, value.MaybeUri () ? UriKind.Absolute : UriKind.Relative, out ret ); return ret; } /// <summary> /// URL-decodes the specified <see cref="string"/>. /// </summary> /// <returns> /// A <see cref="string"/> that receives the decoded string or /// <paramref name="value"/> if it is <see langword="null"/> or empty. /// </returns> /// <param name="value"> /// A <see cref="string"/> to decode. /// </param> public static string UrlDecode (this string value) { return value != null && value.Length > 0 ? HttpUtility.UrlDecode (value) : value; } /// <summary> /// URL-encodes the specified <see cref="string"/>. /// </summary> /// <returns> /// A <see cref="string"/> that receives the encoded string or /// <paramref name="value"/> if it is <see langword="null"/> or empty. /// </returns> /// <param name="value"> /// A <see cref="string"/> to encode. /// </param> public static string UrlEncode (this string value) { return value != null && value.Length > 0 ? HttpUtility.UrlEncode (value) : value; } /// <summary> /// Writes and sends the specified <paramref name="content"/> data with the specified /// <see cref="HttpListenerResponse"/>. /// </summary> /// <param name="response"> /// A <see cref="HttpListenerResponse"/> that represents the HTTP response used to /// send the content data. /// </param> /// <param name="content"> /// An array of <see cref="byte"/> that represents the content data to send. /// </param> /// <exception cref="ArgumentNullException"> /// <para> /// <paramref name="response"/> is <see langword="null"/>. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="content"/> is <see langword="null"/>. /// </para> /// </exception> public static void WriteContent (this HttpListenerResponse response, byte[] content) { if (response == null) throw new ArgumentNullException ("response"); if (content == null) throw new ArgumentNullException ("content"); var len = content.LongLength; if (len == 0) { response.Close (); return; } response.ContentLength64 = len; var output = response.OutputStream; if (len <= Int32.MaxValue) output.Write (content, 0, (int) len); else output.WriteBytes (content, 1024); output.Close (); } #endregion } }
31.243867
100
0.551582
[ "Apache-2.0" ]
UMI3D/UMI3D-Tangram
Projet-Tangram/Assets/UMI3D SDK/dependencies/websocket-sharp-master/websocket-sharp/Ext.cs
63,675
C#
#pragma checksum "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\Manage\DownloadPersonalData.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "e3c13bd0255fd370ccd5c5aaf6bd29ffae443e28" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(RobofestWTECore.Areas.Identity.Pages.Account.Manage.Areas_Identity_Pages_Account_Manage_DownloadPersonalData), @"mvc.1.0.razor-page", @"/Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.RazorPageAttribute(@"/Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml", typeof(RobofestWTECore.Areas.Identity.Pages.Account.Manage.Areas_Identity_Pages_Account_Manage_DownloadPersonalData), null)] namespace RobofestWTECore.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 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\_ViewImports.cshtml" using Microsoft.AspNetCore.Identity; #line default #line hidden #line 2 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\_ViewImports.cshtml" using RobofestWTECore.Areas.Identity; #line default #line hidden #line 3 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\_ViewImports.cshtml" using RobofestWTECore.Models; #line default #line hidden #line 1 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\_ViewImports.cshtml" using RobofestWTECore.Areas.Identity.Pages.Account; #line default #line hidden #line 1 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\Manage\_ViewImports.cshtml" using RobofestWTECore.Areas.Identity.Pages.Account.Manage; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e3c13bd0255fd370ccd5c5aaf6bd29ffae443e28", @"/Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"8f01af31586d4d71935a25546449a3fe9dd15655", @"/Areas/Identity/Pages/_ViewImports.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e118981af79542720387edc66dc7e833a3977fef", @"/Areas/Identity/Pages/Account/_ViewImports.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3bca45448dc0ec8e84b1391bf0219d887ab8b089", @"/Areas/Identity/Pages/Account/Manage/_ViewImports.cshtml")] public class Areas_Identity_Pages_Account_Manage_DownloadPersonalData : global::Microsoft.AspNetCore.Mvc.RazorPages.Page { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "_ValidationScriptsPartial", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #line 3 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\Manage\DownloadPersonalData.cshtml" ViewData["Title"] = "Download Your Data"; ViewData["ActivePage"] = ManageNavPages.DownloadPersonalData; #line default #line hidden BeginContext(162, 6, true); WriteLiteral("\r\n<h4>"); EndContext(); BeginContext(169, 17, false); #line 8 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\Manage\DownloadPersonalData.cshtml" Write(ViewData["Title"]); #line default #line hidden EndContext(); BeginContext(186, 9, true); WriteLiteral("</h4>\r\n\r\n"); EndContext(); DefineSection("Scripts", async() => { BeginContext(213, 6, true); WriteLiteral("\r\n "); EndContext(); BeginContext(219, 44, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "f321967e81c943baaeeabc438b9b6e3f", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(263, 2, true); WriteLiteral("\r\n"); EndContext(); } ); } #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<DownloadPersonalDataModel> Html { get; private set; } public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<DownloadPersonalDataModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<DownloadPersonalDataModel>)PageContext?.ViewData; public DownloadPersonalDataModel Model => ViewData.Model; } } #pragma warning restore 1591
63.106061
312
0.7503
[ "MIT" ]
HDLOfficial/RobofestOSSWeb
RobofestWTECore/obj/Release/netcoreapp2.1/Razor/Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml.g.cs
8,330
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DomainModel { public class PostLinks { public int PostId { get; set; } public int LinkedPost { get; set; } } }
18.733333
44
0.644128
[ "MIT" ]
Rmood/SOVA
DomainModel/PostLinks.cs
283
C#
using System; using Newtonsoft.Json; namespace TdLib { /// <summary> /// Autogenerated TDLib APIs /// </summary> public static partial class TdApi { public partial class NotificationGroupType : Object { /// <summary> /// A group containing notifications of type notificationTypeNewMessage and notificationTypeNewPushMessage with unread mentions of the current user, replies to their messages, or a pinned message /// </summary> public class NotificationGroupTypeMentions : NotificationGroupType { /// <summary> /// Data type for serialization /// </summary> [JsonProperty("@type")] public override string DataType { get; set; } = "notificationGroupTypeMentions"; /// <summary> /// Extra data attached to the message /// </summary> [JsonProperty("@extra")] public override string Extra { get; set; } } } } }
32.058824
207
0.553211
[ "MIT" ]
YogurtTheHorse/tdsharp
TDLib.Api/Objects/NotificationGroupTypeMentions.cs
1,090
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum EnemyState { walk, attack, stagger, die } public class Enemy : MonoBehaviour { [HideInInspector]public EnemyState CurrentState; [Header("Movement and attack variables")] public float MoveSpeed; public float AttackKD; public bool isActive; [HideInInspector] public Rigidbody2D Body; [Header("Animations")] public float DeadAnimTime; [SerializeField] private float AttackAnimTime; [HideInInspector] public SpriteRenderer Sprite; [HideInInspector] public Animator Anim; [Header("Health variables")] public FloatValue MaxHealth; public float deffense; [HideInInspector] public float CurrentHealth; [HideInInspector] public float TimeKd; [Header("Items")] [SerializeField] private GameObject GoldenCoin; [SerializeField] private int baseDroppedCoins; [Header("Sigals")] [SerializeField] private Signal EnemyBorn; [SerializeField] private Signal EnemyDied; [Header("Interaction variables")] public string team; public GameObject Target; public virtual void Start() { Anim = GetComponent<Animator>(); Sprite = GetComponent<SpriteRenderer>(); Body = GetComponent<Rigidbody2D>(); CurrentHealth = MaxHealth.InitialValue; CurrentState = EnemyState.walk; TimeKd = AttackKD; Physics2D.queriesStartInColliders = false; if (EnemyBorn) { EnemyBorn.Raise(); } } public bool IsDead() { return CurrentHealth <= 0; } public void Attack() { StartCoroutine(AttackCo()); } private IEnumerator AttackCo() { if (CurrentState != EnemyState.attack) { CurrentState = EnemyState.attack; Anim.SetBool("IsAttacking", true); yield return new WaitForSeconds(AttackAnimTime); Anim.SetBool("IsAttacking", false); CurrentState = EnemyState.walk; } } virtual public void Knock(float KnockTime, float Damage) { if (!IsDead()) { CurrentHealth -= Damage * (1 - deffense); if (!IsDead()) { CurrentState = EnemyState.stagger; StartCoroutine(GetDamage()); StartCoroutine(KnockCo(KnockTime)); } else { Die(); } } } public IEnumerator GetDamage() { Anim.SetBool("IsGettingDamage", true); yield return new WaitForSeconds(0.3f); Anim.SetBool("IsGettingDamage", false); } public IEnumerator KnockCo(float KnockTime) { if (Body != null) { yield return new WaitForSeconds(KnockTime); Body.velocity = Vector2.zero; CurrentState = EnemyState.walk; Body.velocity = Vector2.zero; // Prevent unstopable impulse } } public virtual void Die() { Body.constraints = RigidbodyConstraints2D.FreezeAll; SpawnCoins(); StartCoroutine(DieCo()); BoxCollider2D[] temp = gameObject.GetComponents<BoxCollider2D>(); for (int i = 0; i < temp.Length; i++) { temp[i].enabled = false; } if (EnemyDied) { EnemyDied.Raise(); } } public virtual void SpawnCoins() { int rand = Random.Range(-3, 3); for (int i = 0; i < baseDroppedCoins + rand; i++) { Rigidbody2D temp = Instantiate(GoldenCoin, transform.position, Quaternion.identity).GetComponent<Rigidbody2D>(); temp.AddForce(new Vector2(Mathf.Sin(i), Mathf.Cos(i)) * i / 10f, ForceMode2D.Impulse); StartCoroutine(CoinSpawnCo(temp)); } } IEnumerator CoinSpawnCo(Rigidbody2D rig) { yield return new WaitForSeconds(0.2f); if (rig) { rig.constraints = RigidbodyConstraints2D.FreezeAll; } } public IEnumerator DieCo() { Anim.SetBool("IsDead", true); yield return new WaitForSeconds(DeadAnimTime); Anim.enabled = false; CurrentState = EnemyState.die; } public void FlipSprite(bool value) { Sprite.flipX = value; } public void WalkToTarget(Vector3 newPos) { FlipSprite(); Anim.SetBool("IsWalking", true); transform.position = newPos; } public void FlipSprite() { if (transform.position.x > Target.transform.position.x) { FlipSprite(true); } else { FlipSprite(false); } } public void ResetAnim() { CurrentState = EnemyState.walk; Anim.enabled = true; Anim.SetBool("IsWalking", false); Anim.SetBool("IsDead", false); Anim.SetBool("IsAttacking", false); } }
26.695876
125
0.562464
[ "MIT" ]
exeynod/ml-AI
Assets/Scripts/Enemy/Enemy.cs
5,181
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 ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Container for the parameters to the DescribeInternetGateways operation. /// Describes one or more of your internet gateways. /// </summary> public partial class DescribeInternetGatewaysRequest : AmazonEC2Request { private List<Filter> _filters = new List<Filter>(); private List<string> _internetGatewayIds = new List<string>(); private int? _maxResults; private string _nextToken; /// <summary> /// Gets and sets the property Filters. /// <para> /// One or more filters. /// </para> /// <ul> <li> /// <para> /// <code>attachment.state</code> - The current state of the attachment between the gateway /// and the VPC (<code>available</code>). Present only if a VPC is attached. /// </para> /// </li> <li> /// <para> /// <code>attachment.vpc-id</code> - The ID of an attached VPC. /// </para> /// </li> <li> /// <para> /// <code>internet-gateway-id</code> - The ID of the Internet gateway. /// </para> /// </li> <li> /// <para> /// <code>owner-id</code> - The ID of the AWS account that owns the internet gateway. /// </para> /// </li> <li> /// <para> /// <code>tag</code>:&lt;key&gt; - The key/value combination of a tag assigned to the /// resource. Use the tag key in the filter name and the tag value as the filter value. /// For example, to find all resources that have a tag with the key <code>Owner</code> /// and the value <code>TeamA</code>, specify <code>tag:Owner</code> for the filter name /// and <code>TeamA</code> for the filter value. /// </para> /// </li> <li> /// <para> /// <code>tag-key</code> - The key of a tag assigned to the resource. Use this filter /// to find all resources assigned a tag with a specific key, regardless of the tag value. /// </para> /// </li> </ul> /// </summary> public List<Filter> Filters { get { return this._filters; } set { this._filters = value; } } // Check to see if Filters property is set internal bool IsSetFilters() { return this._filters != null && this._filters.Count > 0; } /// <summary> /// Gets and sets the property InternetGatewayIds. /// <para> /// One or more internet gateway IDs. /// </para> /// /// <para> /// Default: Describes all your internet gateways. /// </para> /// </summary> public List<string> InternetGatewayIds { get { return this._internetGatewayIds; } set { this._internetGatewayIds = value; } } // Check to see if InternetGatewayIds property is set internal bool IsSetInternetGatewayIds() { return this._internetGatewayIds != null && this._internetGatewayIds.Count > 0; } /// <summary> /// Gets and sets the property MaxResults. /// <para> /// The maximum number of results to return with a single call. To retrieve the remaining /// results, make another call with the returned <code>nextToken</code> value. /// </para> /// </summary> [AWSProperty(Min=5, Max=1000)] public int MaxResults { get { return this._maxResults.GetValueOrDefault(); } set { this._maxResults = value; } } // Check to see if MaxResults property is set internal bool IsSetMaxResults() { return this._maxResults.HasValue; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The token for the next page of results. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
35.223684
102
0.553978
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/DescribeInternetGatewaysRequest.cs
5,354
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace Kernys.Bson { public class BSONValue { public enum ValueType { Double, String, Array, Binary, Boolean, UTCDateTime, None, Int32, Int64, Object }; private ValueType mValueType; private Double _double; private string _string; private byte[] _binary; private bool _bool; private DateTime _dateTime; private Int32 _int32; private Int64 _int64; /* protected static BSONValue convert(object obj) { if (obj as BSONValue != null) return obj as BSONValue; if (obj is Int32) return new BSONValue (obj as Int32); if (obj is Int64) return new BSONValue (obj as Int64); if (obj is byte[]) return new BSONValue (obj as byte[]); if (obj is DateTime) return new BSONValue (obj as DateTime); if (obj is string) return new BSONValue (obj as string); if (obj is bool) return new BSONValue (obj as bool); if (obj is double) return new BSONValue (obj as double); throw new InvalidCastException(); } */ /// Properties public ValueType valueType { get { return mValueType; } } public Double doubleValue { get { switch (mValueType) { case ValueType.Int32: return (double)_int32; case ValueType.Int64: return (double)_int64; case ValueType.Double: return _double; case ValueType.None: return float.NaN; } throw new Exception(string.Format("Original type is {0}. Cannot convert from {0} to double", mValueType)); } } public Int32 int32Value { get { switch (mValueType) { case ValueType.Int32: return (Int32)_int32; case ValueType.Int64: return (Int32)_int64; case ValueType.Double: return (Int32)_double; } throw new Exception(string.Format("Original type is {0}. Cannot convert from {0} to Int32", mValueType)); } } public Int64 int64Value { get { switch (mValueType) { case ValueType.Int32: return (Int64)_int32; case ValueType.Int64: return (Int64)_int64; case ValueType.Double: return (Int64)_double; } throw new Exception(string.Format("Original type is {0}. Cannot convert from {0} to Int64", mValueType)); } } public byte[] binaryValue { get { switch (mValueType) { case ValueType.Binary: return _binary; } throw new Exception(string.Format("Original type is {0}. Cannot convert from {0} to binary", mValueType)); } } public DateTime dateTimeValue { get { switch (mValueType) { case ValueType.UTCDateTime: return _dateTime; } throw new Exception(string.Format("Original type is {0}. Cannot convert from {0} to DateTime", mValueType)); } } public String stringValue { get { switch (mValueType) { case ValueType.Int32: return Convert.ToString(_int32); case ValueType.Int64: return Convert.ToString(_int64); case ValueType.Double: return Convert.ToString(_double); case ValueType.String: return _string != null ? _string.TrimEnd(new char[] { (char)0 }) : null; case ValueType.Boolean: return _bool == true ? "true" : "false"; case ValueType.Binary: return Encoding.UTF8.GetString(_binary).TrimEnd(new char[] { (char)0 }); } throw new Exception(string.Format("Original type is {0}. Cannot convert from {0} to string", mValueType)); } } public bool boolValue { get { switch (mValueType) { case ValueType.Boolean: return _bool; } throw new Exception(string.Format("Original type is {0}. Cannot convert from {0} to bool", mValueType)); } } public bool isNone { get { return mValueType == ValueType.None; } } public virtual BSONValue this[string key] { get { return null; } set { } } public virtual BSONValue this[int index] { get { return null; } set { } } public virtual void Clear() { } public virtual void Add(string key, BSONValue value) { } public virtual void Add(BSONValue value) { } public virtual bool Contains(BSONValue v) { return false; } public virtual bool ContainsKey(string key) { return false; } public static implicit operator BSONValue(double v) { return new BSONValue(v); } public static implicit operator BSONValue(Int32 v) { return new BSONValue(v); } public static implicit operator BSONValue(Int64 v) { return new BSONValue(v); } public static implicit operator BSONValue(byte[] v) { return new BSONValue(v); } public static implicit operator BSONValue(DateTime v) { return new BSONValue(v); } public static implicit operator BSONValue(string v) { return new BSONValue(v); } public static implicit operator BSONValue(bool v) { return new BSONValue(v); } public static implicit operator double(BSONValue v) { return v.doubleValue; } public static implicit operator Int32(BSONValue v) { return v.int32Value; } public static implicit operator Int64(BSONValue v) { return v.int64Value; } public static implicit operator byte[] (BSONValue v) { return v.binaryValue; } public static implicit operator DateTime(BSONValue v) { return v.dateTimeValue; } public static implicit operator string(BSONValue v) { return v.stringValue; } public static implicit operator bool(BSONValue v) { return v.boolValue; } /// protected BSONValue(ValueType valueType) { mValueType = valueType; } public BSONValue() { mValueType = ValueType.None; } public BSONValue(double v) { mValueType = ValueType.Double; _double = v; } public BSONValue(String v) { mValueType = ValueType.String; _string = v; } public BSONValue(byte[] v) { mValueType = ValueType.Binary; _binary = v; } public BSONValue(bool v) { mValueType = ValueType.Boolean; _bool = v; } public BSONValue(DateTime dt) { mValueType = ValueType.UTCDateTime; _dateTime = dt; } public BSONValue(Int32 v) { mValueType = ValueType.Int32; _int32 = v; } public BSONValue(Int64 v) { mValueType = ValueType.Int64; _int64 = v; } public static bool operator ==(BSONValue a, object b) { return System.Object.ReferenceEquals(a, b); } public static bool operator !=(BSONValue a, object b) { return !(a == b); } } public class BSONObject : BSONValue, IEnumerable { private Dictionary<string, BSONValue> mMap = new Dictionary<string, BSONValue>(); public BSONObject() : base(BSONValue.ValueType.Object) { } // // Properties // public ICollection<string> Keys { get { return mMap.Keys; } } public ICollection<BSONValue> Values { get { return mMap.Values; } } public int Count { get { return mMap.Count; } } // // Indexer // public override BSONValue this[string key] { get { return mMap[key]; } set { mMap[key] = value; } } // // Methods // public override void Clear() { mMap.Clear(); } public override void Add(string key, BSONValue value) { mMap.Add(key, value); } public override bool Contains(BSONValue v) { return mMap.ContainsValue(v); } public override bool ContainsKey(string key) { return mMap.ContainsKey(key); } public bool Remove(string key) { return mMap.Remove(key); } public bool TryGetValue(string key, out BSONValue value) { return mMap.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return mMap.GetEnumerator(); } } public class BSONArray : BSONValue, IEnumerable { List<BSONValue> mList = new List<BSONValue>(); public BSONArray() : base(BSONValue.ValueType.Array) { } // // Indexer // public override BSONValue this[int index] { get { return mList[index]; } set { mList[index] = value; } } public int Count { get { return mList.Count; } } // // Methods // public override void Add(BSONValue v) { mList.Add(v); } public int IndexOf(BSONValue item) { return mList.IndexOf(item); } public void Insert(int index, BSONValue item) { mList.Insert(index, item); } public bool Remove(BSONValue v) { return mList.Remove(v); } public void RemoveAt(int index) { mList.RemoveAt(index); } public override void Clear() { mList.Clear(); } public virtual bool Contains(BSONValue v) { return mList.Contains(v); } IEnumerator IEnumerable.GetEnumerator() { return mList.GetEnumerator(); } } public class SimpleBSON { private MemoryStream mMemoryStream; private BinaryReader mBinaryReader; private BinaryWriter mBinaryWriter; public static BSONObject Load(byte[] buf) { SimpleBSON bson = new SimpleBSON(buf); return bson.decodeDocument(); } public static byte[] Dump(BSONObject obj) { SimpleBSON bson = new SimpleBSON(); MemoryStream ms = new MemoryStream(); bson.encodeDocument(ms, obj); byte[] buf = new byte[ms.Position]; ms.Seek(0, SeekOrigin.Begin); ms.Read(buf, 0, buf.Length); return buf; } private SimpleBSON(byte[] buf = null) { if (buf != null) { mMemoryStream = new MemoryStream(buf); mBinaryReader = new BinaryReader(mMemoryStream); } else { mMemoryStream = new MemoryStream(); mBinaryWriter = new BinaryWriter(mMemoryStream); } } private BSONValue decodeElement(out string name) { byte elementType = mBinaryReader.ReadByte(); if (elementType == 0x01) { // Double name = decodeCString(); return new BSONValue(mBinaryReader.ReadDouble()); } else if (elementType == 0x02) { // String name = decodeCString(); return new BSONValue(decodeString()); } else if (elementType == 0x03) { // Document name = decodeCString(); return decodeDocument(); } else if (elementType == 0x04) { // Array name = decodeCString(); return decodeArray(); } else if (elementType == 0x05) { // Binary name = decodeCString(); int length = mBinaryReader.ReadInt32(); byte binaryType = mBinaryReader.ReadByte(); return new BSONValue(mBinaryReader.ReadBytes(length)); } else if (elementType == 0x08) { // Boolean name = decodeCString(); return new BSONValue(mBinaryReader.ReadBoolean()); } else if (elementType == 0x09) { // DateTime name = decodeCString(); Int64 time = mBinaryReader.ReadInt64(); return new BSONValue(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) + new TimeSpan(time * 10000)); } else if (elementType == 0x0A) { // None name = decodeCString(); return new BSONValue(); } else if (elementType == 0x10) { // Int32 name = decodeCString(); return new BSONValue(mBinaryReader.ReadInt32()); } else if (elementType == 0x12) { // Int64 name = decodeCString(); return new BSONValue(mBinaryReader.ReadInt64()); } throw new Exception(string.Format("Don't know elementType={0}", elementType)); } private BSONObject decodeDocument() { int length = mBinaryReader.ReadInt32() - 4; BSONObject obj = new BSONObject(); int i = (int)mBinaryReader.BaseStream.Position; while (mBinaryReader.BaseStream.Position < i + length - 1) { string name; BSONValue value = decodeElement(out name); obj.Add(name, value); } mBinaryReader.ReadByte(); // zero return obj; } private BSONArray decodeArray() { BSONObject obj = decodeDocument(); int i = 0; BSONArray array = new BSONArray(); while (obj.ContainsKey(Convert.ToString(i))) { array.Add(obj[Convert.ToString(i)]); i += 1; } return array; } private string decodeString() { int length = mBinaryReader.ReadInt32(); byte[] buf = mBinaryReader.ReadBytes(length); return Encoding.UTF8.GetString(buf); } private string decodeCString() { var ms = new MemoryStream(); while (true) { byte buf = (byte)mBinaryReader.ReadByte(); if (buf == 0) break; ms.WriteByte(buf); } return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position); } private void encodeElement(MemoryStream ms, string name, BSONValue v) { switch (v.valueType) { case BSONValue.ValueType.Double: ms.WriteByte(0x01); encodeCString(ms, name); encodeDouble(ms, v.doubleValue); return; case BSONValue.ValueType.String: ms.WriteByte(0x02); encodeCString(ms, name); encodeString(ms, v.stringValue); return; case BSONValue.ValueType.Object: ms.WriteByte(0x03); encodeCString(ms, name); encodeDocument(ms, v as BSONObject); return; case BSONValue.ValueType.Array: ms.WriteByte(0x04); encodeCString(ms, name); encodeArray(ms, v as BSONArray); return; case BSONValue.ValueType.Binary: ms.WriteByte(0x05); encodeCString(ms, name); encodeBinary(ms, v.binaryValue); return; case BSONValue.ValueType.Boolean: ms.WriteByte(0x08); encodeCString(ms, name); encodeBool(ms, v.boolValue); return; case BSONValue.ValueType.UTCDateTime: ms.WriteByte(0x09); encodeCString(ms, name); encodeUTCDateTime(ms, v.dateTimeValue); return; case BSONValue.ValueType.None: ms.WriteByte(0x0A); encodeCString(ms, name); return; case BSONValue.ValueType.Int32: ms.WriteByte(0x10); encodeCString(ms, name); encodeInt32(ms, v.int32Value); return; case BSONValue.ValueType.Int64: ms.WriteByte(0x12); encodeCString(ms, name); encodeInt64(ms, v.int64Value); return; }; } private void encodeDocument(MemoryStream ms, BSONObject obj) { MemoryStream dms = new MemoryStream(); foreach (string str in obj.Keys) { encodeElement(dms, str, obj[str]); } BinaryWriter bw = new BinaryWriter(ms); bw.Write((Int32)(dms.Position + 4 + 1)); bw.Write(dms.GetBuffer(), 0, (int)dms.Position); bw.Write((byte)0); } private void encodeArray(MemoryStream ms, BSONArray lst) { var obj = new BSONObject(); for (int i = 0; i < lst.Count; ++i) { obj.Add(Convert.ToString(i), lst[i]); } encodeDocument(ms, obj); } private void encodeBinary(MemoryStream ms, byte[] buf) { byte[] aBuf = BitConverter.GetBytes(buf.Length); ms.Write(aBuf, 0, aBuf.Length); ms.WriteByte(0); ms.Write(buf, 0, buf.Length); } private void encodeCString(MemoryStream ms, string v) { byte[] buf = new UTF8Encoding().GetBytes(v); ms.Write(buf, 0, buf.Length); ms.WriteByte(0); } private void encodeString(MemoryStream ms, string v) { byte[] strBuf = new UTF8Encoding().GetBytes(v); byte[] buf = BitConverter.GetBytes(strBuf.Length + 1); ms.Write(buf, 0, buf.Length); ms.Write(strBuf, 0, strBuf.Length); ms.WriteByte(0); } private void encodeDouble(MemoryStream ms, double v) { byte[] buf = BitConverter.GetBytes(v); ms.Write(buf, 0, buf.Length); } private void encodeBool(MemoryStream ms, bool v) { byte[] buf = BitConverter.GetBytes(v); ms.Write(buf, 0, buf.Length); } private void encodeInt32(MemoryStream ms, Int32 v) { byte[] buf = BitConverter.GetBytes(v); ms.Write(buf, 0, buf.Length); } private void encodeInt64(MemoryStream ms, Int64 v) { byte[] buf = BitConverter.GetBytes(v); ms.Write(buf, 0, buf.Length); } private void encodeUTCDateTime(MemoryStream ms, DateTime dt) { TimeSpan span; if (dt.Kind == DateTimeKind.Local) { span = (dt - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).ToLocalTime()); } else { span = dt - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); } byte[] buf = BitConverter.GetBytes((Int64)(span.TotalSeconds * 1000)); ms.Write(buf, 0, buf.Length); } } }
28.689258
125
0.460575
[ "MIT" ]
cuekYT/GTproxy
Kernys.Bson/SimpleBSON.cs
22,437
C#
//----------------------------------------------------------------------- // <copyright file="TestSubscriber.cs" company="Akka.NET Project"> // Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Actor; using Akka.Event; using Akka.Streams.Actors; using Akka.TestKit; using Reactive.Streams; namespace Akka.Streams.TestKit { public static class TestSubscriber { #region messages public interface ISubscriberEvent : INoSerializationVerificationNeeded, IDeadLetterSuppression { } public struct OnSubscribe : ISubscriberEvent { public readonly ISubscription Subscription; public OnSubscribe(ISubscription subscription) { Subscription = subscription; } public override string ToString() => $"TestSubscriber.OnSubscribe({Subscription})"; } public struct OnNext<T> : ISubscriberEvent { public readonly T Element; public OnNext(T element) { Element = element; } public override string ToString() => $"TestSubscriber.OnNext({Element})"; } public sealed class OnComplete: ISubscriberEvent { public static readonly OnComplete Instance = new OnComplete(); private OnComplete() { } public override string ToString() => "TestSubscriber.OnComplete"; } public struct OnError : ISubscriberEvent { public readonly Exception Cause; public OnError(Exception cause) { Cause = cause; } public override string ToString() => $"TestSubscriber.OnError({Cause.Message})"; } #endregion /// <summary> /// Implementation of <see cref="ISubscriber{T}"/> that allows various assertions. All timeouts are dilated automatically, /// for more details about time dilation refer to <see cref="TestKit"/>. /// </summary> public class ManualProbe<T> : ISubscriber<T> { private readonly TestKitBase _testKit; private readonly TestProbe _probe; internal ManualProbe(TestKitBase testKit) { _testKit = testKit; _probe = testKit.CreateTestProbe(); } private volatile ISubscription _subscription; public void OnSubscribe(ISubscription subscription) => _probe.Ref.Tell(new OnSubscribe(subscription)); public void OnError(Exception cause) => _probe.Ref.Tell(new OnError(cause)); public void OnComplete() => _probe.Ref.Tell(TestSubscriber.OnComplete.Instance); public void OnNext(T element) => _probe.Ref.Tell(new OnNext<T>(element)); /// <summary> /// Expects and returns <see cref="ISubscription"/>. /// </summary> public ISubscription ExpectSubscription() { _subscription = _probe.ExpectMsg<OnSubscribe>().Subscription; return _subscription; } /// <summary> /// Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>). /// </summary> public ISubscriberEvent ExpectEvent() => _probe.ExpectMsg<ISubscriberEvent>(); /// <summary> /// Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>). /// </summary> public ISubscriberEvent ExpectEvent(TimeSpan max) => _probe.ExpectMsg<ISubscriberEvent>(max); /// <summary> /// Fluent DSL. Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>). /// </summary> public ManualProbe<T> ExpectEvent(ISubscriberEvent e) { _probe.ExpectMsg(e); return this; } /// <summary> /// Expect and return a stream element. /// </summary> public T ExpectNext() { return ExpectNext(_testKit.Dilated(_probe.TestKitSettings.SingleExpectDefault)); } /// <summary> /// Expect and return a stream element during specified time or timeout. /// </summary> public T ExpectNext(TimeSpan timeout) { var t = _probe.RemainingOrDilated(timeout); switch (_probe.ReceiveOne(t)) { case null: throw new Exception($"Expected OnNext(_), yet no element signaled during {timeout}"); case OnNext<T> message: return message.Element; case var other: throw new Exception($"expected OnNext, found {other}"); } } /// <summary> /// Fluent DSL. Expect a stream element. /// </summary> public ManualProbe<T> ExpectNext(T element) { _probe.ExpectMsg<OnNext<T>>(x => AssertEquals(x.Element, element, "Expected '{0}', but got '{1}'", element, x.Element)); return this; } /// <summary> /// Fluent DSL. Expect a stream element during specified time or timeout. /// </summary> public ManualProbe<T> ExpectNext(TimeSpan timeout, T element) { _probe.ExpectMsg<OnNext<T>>(x => AssertEquals(x.Element, element, "Expected '{0}', but got '{1}'", element, x.Element), timeout); return this; } /// <summary> /// Fluent DSL. Expect a stream element during specified timeout. /// </summary> public ManualProbe<T> ExpectNext(T element, TimeSpan timeout) { _probe.ExpectMsg<OnNext<T>>(x => AssertEquals(x.Element, element, "Expected '{0}', but got '{1}'", element, x.Element), timeout); return this; } /// <summary> /// Fluent DSL. Expect multiple stream elements. /// </summary> public ManualProbe<T> ExpectNext(T e1, T e2, params T[] elems) { var len = elems.Length + 2; var e = ExpectNextN(len).ToArray(); AssertEquals(e.Length, len, "expected to get {0} events, but got {1}", len, e.Length); AssertEquals(e[0], e1, "expected [0] element to be {0} but found {1}", e1, e[0]); AssertEquals(e[1], e2, "expected [1] element to be {0} but found {1}", e2, e[1]); for (var i = 0; i < elems.Length; i++) { var j = i + 2; AssertEquals(e[j], elems[i], "expected [{2}] element to be {0} but found {1}", elems[i], e[j], j); } return this; } /// <summary> /// FluentDSL. Expect multiple stream elements in arbitrary order. /// </summary> public ManualProbe<T> ExpectNextUnordered(T e1, T e2, params T[] elems) { var len = elems.Length + 2; var e = ExpectNextN(len).ToArray(); AssertEquals(e.Length, len, "expected to get {0} events, but got {1}", len, e.Length); var expectedSet = new HashSet<T>(elems) {e1, e2}; expectedSet.ExceptWith(e); Assert(expectedSet.Count == 0, "unexpected elements [{0}] found in the result", string.Join(", ", expectedSet)); return this; } /// <summary> /// Expect and return the next <paramref name="n"/> stream elements. /// </summary> public IEnumerable<T> ExpectNextN(long n) { var res = new List<T>((int)n); for (int i = 0; i < n; i++) { var next = _probe.ExpectMsg<OnNext<T>>(); res.Add(next.Element); } return res; } /// <summary> /// Fluent DSL. Expect the given elements to be signalled in order. /// </summary> public ManualProbe<T> ExpectNextN(IEnumerable<T> all) { foreach (var x in all) _probe.ExpectMsg<OnNext<T>>(y => AssertEquals(y.Element, x, "Expected one of ({0}), but got '{1}'", string.Join(", ", all), y.Element)); return this; } /// <summary> /// Fluent DSL. Expect the given elements to be signalled in any order. /// </summary> public ManualProbe<T> ExpectNextUnorderedN(IEnumerable<T> all) { var collection = new HashSet<T>(all); while (collection.Count > 0) { var next = ExpectNext(); Assert(collection.Contains(next), $"expected one of (${string.Join(", ", collection)}), but received {next}"); collection.Remove(next); } return this; } /// <summary> /// Fluent DSL. Expect completion. /// </summary> public ManualProbe<T> ExpectComplete() { _probe.ExpectMsg<OnComplete>(); return this; } /// <summary> /// Expect and return the signalled <see cref="Exception"/>. /// </summary> public Exception ExpectError() => _probe.ExpectMsg<OnError>().Cause; /// <summary> /// Expect subscription to be followed immediately by an error signal. By default single demand will be signaled in order to wake up a possibly lazy upstream. /// <seealso cref="ExpectSubscriptionAndError(bool)"/> /// </summary> public Exception ExpectSubscriptionAndError() => ExpectSubscriptionAndError(true); /// <summary> /// Expect subscription to be followed immediately by an error signal. Depending on the `signalDemand` parameter demand may be signaled /// immediately after obtaining the subscription in order to wake up a possibly lazy upstream.You can disable this by setting the `signalDemand` parameter to `false`. /// <seealso cref="ExpectSubscriptionAndError()"/> /// </summary> public Exception ExpectSubscriptionAndError(bool signalDemand) { var sub = ExpectSubscription(); if(signalDemand) sub.Request(1); return ExpectError(); } /// <summary> /// Fluent DSL. Expect subscription followed by immediate stream completion. By default single demand will be signaled in order to wake up a possibly lazy upstream /// </summary> /// <seealso cref="ExpectSubscriptionAndComplete(bool)"/> public ManualProbe<T> ExpectSubscriptionAndComplete() => ExpectSubscriptionAndComplete(true); /// <summary> /// Fluent DSL. Expect subscription followed by immediate stream completion. Depending on the `signalDemand` parameter /// demand may be signaled immediately after obtaining the subscription in order to wake up a possibly lazy upstream. /// You can disable this by setting the `signalDemand` parameter to `false`. /// </summary> /// <seealso cref="ExpectSubscriptionAndComplete()"/> public ManualProbe<T> ExpectSubscriptionAndComplete(bool signalDemand) { var sub = ExpectSubscription(); if (signalDemand) sub.Request(1); ExpectComplete(); return this; } /// <summary> /// Expect given next element or error signal, returning whichever was signaled. /// </summary> public object ExpectNextOrError() { var message = _probe.FishForMessage(m => m is OnNext<T> || m is OnError, hint: "OnNext(_) or error"); if (message is OnNext<T> next) return next.Element; return ((OnError) message).Cause; } /// <summary> /// Fluent DSL. Expect given next element or error signal. /// </summary> public ManualProbe<T> ExpectNextOrError(T element, Exception cause) { _probe.FishForMessage( m => m is OnNext<T> next && next.Element.Equals(element) || m is OnError error && error.Cause.Equals(cause), hint: $"OnNext({element}) or {cause.GetType().Name}"); return this; } /// <summary> /// Expect given next element or stream completion, returning whichever was signaled. /// </summary> public object ExpectNextOrComplete() { var message = _probe.FishForMessage(m => m is OnNext<T> || m is OnComplete, hint: "OnNext(_) or OnComplete"); if (message is OnNext<T> next) return next.Element; return message; } /// <summary> /// Fluent DSL. Expect given next element or stream completion. /// </summary> public ManualProbe<T> ExpectNextOrComplete(T element) { _probe.FishForMessage( m => m is OnNext<T> next && next.Element.Equals(element) || m is OnComplete, hint: $"OnNext({element}) or OnComplete"); return this; } /// <summary> /// Fluent DSL. Same as <see cref="ExpectNoMsg(TimeSpan)"/>, but correctly treating the timeFactor. /// </summary> public ManualProbe<T> ExpectNoMsg() { _probe.ExpectNoMsg(); return this; } /// <summary> /// Fluent DSL. Assert that no message is received for the specified time. /// </summary> public ManualProbe<T> ExpectNoMsg(TimeSpan remaining) { _probe.ExpectNoMsg(remaining); return this; } /// <summary> /// Expect next element and test it with the <paramref name="predicate"/> /// </summary> /// <typeparam name="TOther">The <see cref="Type"/> of the expected message</typeparam> /// <param name="predicate">The <see cref="Predicate{T}"/> that is applied to the message</param> /// <returns>The next element</returns> public TOther ExpectNext<TOther>(Predicate<TOther> predicate) => _probe.ExpectMsg<OnNext<TOther>>(x => predicate(x.Element)).Element; /// <summary> /// Expect next element and test it with the <paramref name="predicate"/> /// </summary> /// <typeparam name="TOther">The <see cref="Type"/> of the expected message</typeparam> /// <param name="predicate">The <see cref="Predicate{T}"/> that is applied to the message</param> /// <returns>this</returns> public ManualProbe<T> MatchNext<TOther>(Predicate<TOther> predicate) { _probe.ExpectMsg<OnNext<TOther>>(x => predicate(x.Element)); return this; } public TOther ExpectEvent<TOther>(Func<ISubscriberEvent, TOther> func) => func(_probe.ExpectMsg<ISubscriberEvent>(hint: "message matching function")); /// <summary> /// Receive messages for a given duration or until one does not match a given partial function. /// </summary> public IEnumerable<TOther> ReceiveWhile<TOther>(TimeSpan? max = null, TimeSpan? idle = null, Func<object, TOther> filter = null, int msgs = int.MaxValue) where TOther : class { return _probe.ReceiveWhile(max, idle, filter, msgs); } /// <summary> /// Drains a given number of messages /// </summary> public IEnumerable<TOther> ReceiveWithin<TOther>(TimeSpan max, int messages = int.MaxValue) where TOther : class { return _probe.ReceiveWhile(max, max, msg => (msg as OnNext)?.Element as TOther, messages); } /// <summary> /// Execute code block while bounding its execution time between <paramref name="min"/> and /// <paramref name="max"/>. <see cref="Within{TOther}(TimeSpan,TimeSpan,Func{TOther})"/> blocks may be nested. /// All methods in this class which take maximum wait times are available in a version which implicitly uses /// the remaining time governed by the innermost enclosing <see cref="Within{TOther}(TimeSpan,TimeSpan,Func{TOther})"/> block. /// /// <para /> /// /// Note that the timeout is scaled using <see cref="TestKitBase.Dilated"/>, which uses the /// configuration entry "akka.test.timefactor", while the min Duration is not. /// /// <![CDATA[ /// var ret = probe.Within(Timespan.FromMilliseconds(50), () => /// { /// test.Tell("ping"); /// return ExpectMsg<string>(); /// }); /// ]]> /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <param name="execute"></param> /// <returns></returns> public TOther Within<TOther>(TimeSpan min, TimeSpan max, Func<TOther> execute) => _probe.Within(min, max, execute); /// <summary> /// Sane as calling Within(TimeSpan.Zero, max, function). /// </summary> public TOther Within<TOther>(TimeSpan max, Func<TOther> execute) => _probe.Within(max, execute); /// <summary> /// Attempt to drain the stream into a strict collection (by requesting <see cref="long.MaxValue"/> elements). /// </summary> /// <remarks> /// Use with caution: Be warned that this may not be a good idea if the stream is infinite or its elements are very large! /// </remarks> public IList<T> ToStrict(TimeSpan atMost) { var deadline = DateTime.UtcNow + atMost; // if no subscription was obtained yet, we expect it if (_subscription == null) ExpectSubscription(); _subscription.Request(long.MaxValue); var result = new List<T>(); while (true) { var e = ExpectEvent(TimeSpan.FromTicks(Math.Max(deadline.Ticks - DateTime.UtcNow.Ticks, 0))); if (e is OnError error) throw new ArgumentException( $"ToStrict received OnError while draining stream! Accumulated elements: ${string.Join(", ", result)}", error.Cause); if (e is OnComplete) break; if (e is OnNext<T> next) result.Add(next.Element); } return result; } private void Assert(bool predicate, string format, params object[] args) { if (!predicate) throw new Exception(string.Format(format, args)); } private void AssertEquals<T1, T2>(T1 x, T2 y, string format, params object[] args) { if (!Equals(x, y)) throw new Exception(string.Format(format, args)); } } /// <summary> /// Single subscription tracking for <see cref="ManualProbe{T}"/>. /// </summary> public class Probe<T> : ManualProbe<T> { private readonly Lazy<ISubscription> _subscription; internal Probe(TestKitBase testKit) : base(testKit) { _subscription = new Lazy<ISubscription>(ExpectSubscription); } /// <summary> /// Asserts that a subscription has been received or will be received /// </summary> public Probe<T> EnsureSubscription() { var _ = _subscription.Value; // initializes lazy val return this; } public Probe<T> Request(long n) { _subscription.Value.Request(n); return this; } public Probe<T> RequestNext(T element) { _subscription.Value.Request(1); ExpectNext(element); return this; } public Probe<T> Cancel() { _subscription.Value.Cancel(); return this; } /// <summary> /// Request and expect a stream element. /// </summary> public T RequestNext() { _subscription.Value.Request(1); return ExpectNext(); } /// <summary> /// Request and expect a stream element during the specified time or timeout. /// </summary> public T RequestNext(TimeSpan timeout) { _subscription.Value.Request(1); return ExpectNext(timeout); } } public static ManualProbe<T> CreateManualSubscriberProbe<T>(this TestKitBase testKit) { return new ManualProbe<T>(testKit); } public static Probe<T> CreateSubscriberProbe<T>(this TestKitBase testKit) { return new Probe<T>(testKit); } } }
41.361818
186
0.523759
[ "Apache-2.0" ]
Bogdan-Rotund/akka.net
src/core/Akka.Streams.TestKit/TestSubscriber.cs
22,751
C#
using J2N.Threading; using J2N.Threading.Atomic; using Lucene.Net.Analysis.Standard; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Store; using Lucene.Net.Support.Threading; using Lucene.Net.Util; using NUnit.Framework; using RandomizedTesting.Generators; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using JCG = J2N.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; using Lucene.Net.Attributes; namespace Lucene.Net.Search { /* * 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 Analyzer = Lucene.Net.Analysis.Analyzer; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IIndexableField = Lucene.Net.Index.IIndexableField; using IndexCommit = Lucene.Net.Index.IndexCommit; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig; using IOUtils = Lucene.Net.Util.IOUtils; using KeepOnlyLastCommitDeletionPolicy = Lucene.Net.Index.KeepOnlyLastCommitDeletionPolicy; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using NoMergePolicy = Lucene.Net.Index.NoMergePolicy; using NRTCachingDirectory = Lucene.Net.Store.NRTCachingDirectory; using OpenMode = Lucene.Net.Index.OpenMode; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SnapshotDeletionPolicy = Lucene.Net.Index.SnapshotDeletionPolicy; using Term = Lucene.Net.Index.Term; using TextField = Lucene.Net.Documents.TextField; using ThreadedIndexingAndSearchingTestCase = Lucene.Net.Index.ThreadedIndexingAndSearchingTestCase; using TrackingIndexWriter = Lucene.Net.Index.TrackingIndexWriter; using Version = Lucene.Net.Util.LuceneVersion; [SuppressCodecs("SimpleText", "Memory", "Direct")] [TestFixture] public class TestControlledRealTimeReopenThread : ThreadedIndexingAndSearchingTestCase { // Not guaranteed to reflect deletes: private SearcherManager nrtNoDeletes; // Is guaranteed to reflect deletes: private SearcherManager nrtDeletes; private TrackingIndexWriter genWriter; private ControlledRealTimeReopenThread<IndexSearcher> nrtDeletesThread; private ControlledRealTimeReopenThread<IndexSearcher> nrtNoDeletesThread; private readonly DisposableThreadLocal<long?> lastGens = new DisposableThreadLocal<long?>(); private bool warmCalled; // LUCENENET specific - cleanup DisposableThreadLocal instances public override void AfterClass() { lastGens.Dispose(); base.AfterClass(); } [Test] [Slow] public virtual void TestControlledRealTimeReopenThread_Mem() { RunTest("TestControlledRealTimeReopenThread"); } protected override IndexSearcher GetFinalSearcher() { if (Verbose) { Console.WriteLine("TEST: finalSearcher maxGen=" + maxGen); } nrtDeletesThread.WaitForGeneration(maxGen); return nrtDeletes.Acquire(); } protected override Directory GetDirectory(Directory @in) { // Randomly swap in NRTCachingDir if (Random.NextBoolean()) { if (Verbose) { Console.WriteLine("TEST: wrap NRTCachingDir"); } return new NRTCachingDirectory(@in, 5.0, 60.0); } else { return @in; } } protected override void UpdateDocuments(Term id, IEnumerable<IEnumerable<IIndexableField>> docs) { long gen = genWriter.UpdateDocuments(id, docs); // Randomly verify the update "took": if (Random.Next(20) == 2) { if (Verbose) { Console.WriteLine(Thread.CurrentThread.Name + ": nrt: verify " + id); } nrtDeletesThread.WaitForGeneration(gen); IndexSearcher s = nrtDeletes.Acquire(); if (Verbose) { Console.WriteLine(Thread.CurrentThread.Name + ": nrt: got searcher=" + s); } try { assertEquals(docs.Count(), s.Search(new TermQuery(id), 10).TotalHits); } finally { nrtDeletes.Release(s); } } lastGens.Value = gen; } protected override void AddDocuments(Term id, IEnumerable<IEnumerable<IIndexableField>> docs) { long gen = genWriter.AddDocuments(docs); // Randomly verify the add "took": if (Random.Next(20) == 2) { if (Verbose) { Console.WriteLine(Thread.CurrentThread.Name + ": nrt: verify " + id); } nrtNoDeletesThread.WaitForGeneration(gen); IndexSearcher s = nrtNoDeletes.Acquire(); if (Verbose) { Console.WriteLine(Thread.CurrentThread.Name + ": nrt: got searcher=" + s); } try { assertEquals(docs.Count(), s.Search(new TermQuery(id), 10).TotalHits); } finally { nrtNoDeletes.Release(s); } } lastGens.Value = gen; } protected override void AddDocument(Term id, IEnumerable<IIndexableField> doc) { long gen = genWriter.AddDocument(doc); // Randomly verify the add "took": if (Random.Next(20) == 2) { if (Verbose) { Console.WriteLine(Thread.CurrentThread.Name + ": nrt: verify " + id); } nrtNoDeletesThread.WaitForGeneration(gen); IndexSearcher s = nrtNoDeletes.Acquire(); if (Verbose) { Console.WriteLine(Thread.CurrentThread.Name + ": nrt: got searcher=" + s); } try { assertEquals(1, s.Search(new TermQuery(id), 10).TotalHits); } finally { nrtNoDeletes.Release(s); } } lastGens.Value = gen; } protected override void UpdateDocument(Term id, IEnumerable<IIndexableField> doc) { long gen = genWriter.UpdateDocument(id, doc); // Randomly verify the udpate "took": if (Random.Next(20) == 2) { if (Verbose) { Console.WriteLine(Thread.CurrentThread.Name + ": nrt: verify " + id); } nrtDeletesThread.WaitForGeneration(gen); IndexSearcher s = nrtDeletes.Acquire(); if (Verbose) { Console.WriteLine(Thread.CurrentThread.Name + ": nrt: got searcher=" + s); } try { assertEquals(1, s.Search(new TermQuery(id), 10).TotalHits); } finally { nrtDeletes.Release(s); } } lastGens.Value = gen; } protected override void DeleteDocuments(Term id) { long gen = genWriter.DeleteDocuments(id); // randomly verify the delete "took": if (Random.Next(20) == 7) { if (Verbose) { Console.WriteLine(Thread.CurrentThread.Name + ": nrt: verify del " + id); } nrtDeletesThread.WaitForGeneration(gen); IndexSearcher s = nrtDeletes.Acquire(); if (Verbose) { Console.WriteLine(Thread.CurrentThread.Name + ": nrt: got searcher=" + s); } try { assertEquals(0, s.Search(new TermQuery(id), 10).TotalHits); } finally { nrtDeletes.Release(s); } } lastGens.Value = gen; } protected override void DoAfterWriter(TaskScheduler es) { double minReopenSec = 0.01 + 0.05 * Random.NextDouble(); double maxReopenSec = minReopenSec * (1.0 + 10 * Random.NextDouble()); if (Verbose) { Console.WriteLine("TEST: make SearcherManager maxReopenSec=" + maxReopenSec + " minReopenSec=" + minReopenSec); } genWriter = new TrackingIndexWriter(m_writer); SearcherFactory sf = new SearcherFactoryAnonymousClass(this, es); nrtNoDeletes = new SearcherManager(m_writer, false, sf); nrtDeletes = new SearcherManager(m_writer, true, sf); nrtDeletesThread = new ControlledRealTimeReopenThread<IndexSearcher>(genWriter, nrtDeletes, maxReopenSec, minReopenSec); nrtDeletesThread.Name = "NRTDeletes Reopen Thread"; nrtDeletesThread.Priority = (ThreadPriority)Math.Min((int)Thread.CurrentThread.Priority + 2, (int)ThreadPriority.Highest); nrtDeletesThread.IsBackground = (true); nrtDeletesThread.Start(); nrtNoDeletesThread = new ControlledRealTimeReopenThread<IndexSearcher>(genWriter, nrtNoDeletes, maxReopenSec, minReopenSec); nrtNoDeletesThread.Name = "NRTNoDeletes Reopen Thread"; nrtNoDeletesThread.Priority = (ThreadPriority)Math.Min((int)Thread.CurrentThread.Priority + 2, (int)ThreadPriority.Highest); nrtNoDeletesThread.IsBackground = (true); nrtNoDeletesThread.Start(); } private class SearcherFactoryAnonymousClass : SearcherFactory { private readonly TestControlledRealTimeReopenThread outerInstance; private TaskScheduler es; public SearcherFactoryAnonymousClass(TestControlledRealTimeReopenThread outerInstance, TaskScheduler es) { this.outerInstance = outerInstance; this.es = es; } public override IndexSearcher NewSearcher(IndexReader r) { outerInstance.warmCalled = true; IndexSearcher s = new IndexSearcher(r, es); s.Search(new TermQuery(new Term("body", "united")), 10); return s; } } protected override void DoAfterIndexingThreadDone() { long? gen = lastGens.Value; if (gen != null) { AddMaxGen((long)gen); } } private long maxGen = -1; private void AddMaxGen(long gen) { UninterruptableMonitor.Enter(this); try { maxGen = Math.Max(gen, maxGen); } finally { UninterruptableMonitor.Exit(this); } } protected override void DoSearching(TaskScheduler es, long stopTime) { RunSearchThreads(stopTime); } protected override IndexSearcher GetCurrentSearcher() { // Test doesn't assert deletions until the end, so we // can randomize whether dels must be applied SearcherManager nrt; if (Random.NextBoolean()) { nrt = nrtDeletes; } else { nrt = nrtNoDeletes; } return nrt.Acquire(); } protected override void ReleaseSearcher(IndexSearcher s) { // NOTE: a bit iffy... technically you should release // against the same SearcherManager you acquired from... but // both impls just decRef the underlying reader so we // can get away w/ cheating: nrtNoDeletes.Release(s); } protected override void DoClose() { Assert.IsTrue(warmCalled); if (Verbose) { Console.WriteLine("TEST: now close SearcherManagers"); } nrtDeletesThread.Dispose(); nrtDeletes.Dispose(); nrtNoDeletesThread.Dispose(); nrtNoDeletes.Dispose(); } /* * LUCENE-3528 - NRTManager hangs in certain situations */ [Test] public virtual void TestThreadStarvationNoDeleteNRTReader() { IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); conf.SetMergePolicy(Random.NextBoolean() ? NoMergePolicy.COMPOUND_FILES : NoMergePolicy.NO_COMPOUND_FILES); Directory d = NewDirectory(); CountdownEvent latch = new CountdownEvent(1); CountdownEvent signal = new CountdownEvent(1); LatchedIndexWriter _writer = new LatchedIndexWriter(d, conf, latch, signal); TrackingIndexWriter writer = new TrackingIndexWriter(_writer); SearcherManager manager = new SearcherManager(_writer, false, null); Document doc = new Document(); doc.Add(NewTextField("test", "test", Field.Store.YES)); writer.AddDocument(doc); manager.MaybeRefresh(); var t = new ThreadAnonymousClass(this, latch, signal, writer, manager); t.Start(); _writer.waitAfterUpdate = true; // wait in addDocument to let some reopens go through long lastGen = writer.UpdateDocument(new Term("foo", "bar"), doc); // once this returns the doc is already reflected in the last reopen assertFalse(manager.IsSearcherCurrent()); // false since there is a delete in the queue IndexSearcher searcher = manager.Acquire(); try { assertEquals(2, searcher.IndexReader.NumDocs); } finally { manager.Release(searcher); } ControlledRealTimeReopenThread<IndexSearcher> thread = new ControlledRealTimeReopenThread<IndexSearcher>(writer, manager, 0.01, 0.01); thread.Start(); // start reopening if (Verbose) { Console.WriteLine("waiting now for generation " + lastGen); } AtomicBoolean finished = new AtomicBoolean(false); var waiter = new ThreadAnonymousClass2(this, lastGen, thread, finished); waiter.Start(); manager.MaybeRefresh(); waiter.Join(1000); if (!finished) { waiter.Interrupt(); fail("thread deadlocked on waitForGeneration"); } thread.Dispose(); thread.Join(); IOUtils.Dispose(manager, _writer, d); } private class ThreadAnonymousClass : ThreadJob { private readonly TestControlledRealTimeReopenThread outerInstance; private readonly CountdownEvent latch; private readonly CountdownEvent signal; private readonly TrackingIndexWriter writer; private readonly SearcherManager manager; public ThreadAnonymousClass(TestControlledRealTimeReopenThread outerInstance, CountdownEvent latch, CountdownEvent signal, TrackingIndexWriter writer, SearcherManager manager) { this.outerInstance = outerInstance; this.latch = latch; this.signal = signal; this.writer = writer; this.manager = manager; } public override void Run() { try { signal.Wait(); manager.MaybeRefresh(); writer.DeleteDocuments(new TermQuery(new Term("foo", "barista"))); manager.MaybeRefresh(); // kick off another reopen so we inc. the internal gen } catch (Exception e) when (e.IsException()) { e.printStackTrace(); } finally { latch.Reset(latch.CurrentCount == 0 ? 0 : latch.CurrentCount - 1); // let the add below finish } } } private class ThreadAnonymousClass2 : ThreadJob { private readonly TestControlledRealTimeReopenThread outerInstance; private readonly long lastGen; private readonly ControlledRealTimeReopenThread<IndexSearcher> thread; private readonly AtomicBoolean finished; public ThreadAnonymousClass2(TestControlledRealTimeReopenThread outerInstance, long lastGen, ControlledRealTimeReopenThread<IndexSearcher> thread, AtomicBoolean finished) { this.outerInstance = outerInstance; this.lastGen = lastGen; this.thread = thread; this.finished = finished; } public override void Run() { try { thread.WaitForGeneration(lastGen); } catch (Exception ie) when (ie.IsInterruptedException()) { Thread.CurrentThread.Interrupt(); throw RuntimeException.Create(ie); } finished.Value = true; } } public class LatchedIndexWriter : IndexWriter { internal CountdownEvent latch; internal bool waitAfterUpdate = false; internal CountdownEvent signal; public LatchedIndexWriter(Directory d, IndexWriterConfig conf, CountdownEvent latch, CountdownEvent signal) : base(d, conf) { this.latch = latch; this.signal = signal; } public override void UpdateDocument(Term term, IEnumerable<IIndexableField> doc, Analyzer analyzer) { base.UpdateDocument(term, doc, analyzer); try { if (waitAfterUpdate) { signal.Reset(signal.CurrentCount == 0 ? 0 : signal.CurrentCount - 1); latch.Wait(); } } catch (Exception ie) when (ie.IsInterruptedException()) { throw new Util.ThreadInterruptedException(ie); } } } [Test] public virtual void TestEvilSearcherFactory() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir); w.Commit(); IndexReader other = DirectoryReader.Open(dir); SearcherFactory theEvilOne = new SearcherFactoryAnonymousClass2(this, other); try { new SearcherManager(w.IndexWriter, false, theEvilOne); fail("didn't hit expected exception"); } catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } w.Dispose(); other.Dispose(); dir.Dispose(); } private class SearcherFactoryAnonymousClass2 : SearcherFactory { private readonly TestControlledRealTimeReopenThread outerInstance; private readonly IndexReader other; public SearcherFactoryAnonymousClass2(TestControlledRealTimeReopenThread outerInstance, IndexReader other) { this.outerInstance = outerInstance; this.other = other; } public override IndexSearcher NewSearcher(IndexReader ignored) { return LuceneTestCase.NewSearcher(other); } } [Test] public virtual void TestListenerCalled() { Directory dir = NewDirectory(); IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null)); AtomicBoolean afterRefreshCalled = new AtomicBoolean(false); SearcherManager sm = new SearcherManager(iw, true, new SearcherFactory()); sm.AddListener(new RefreshListenerAnonymousClass(this, afterRefreshCalled)); iw.AddDocument(new Document()); iw.Commit(); assertFalse(afterRefreshCalled); sm.MaybeRefreshBlocking(); assertTrue(afterRefreshCalled); sm.Dispose(); iw.Dispose(); dir.Dispose(); } private class RefreshListenerAnonymousClass : ReferenceManager.IRefreshListener { private readonly TestControlledRealTimeReopenThread outerInstance; private AtomicBoolean afterRefreshCalled; public RefreshListenerAnonymousClass(TestControlledRealTimeReopenThread outerInstance, AtomicBoolean afterRefreshCalled) { this.outerInstance = outerInstance; this.afterRefreshCalled = afterRefreshCalled; } public void BeforeRefresh() { } public void AfterRefresh(bool didRefresh) { if (didRefresh) { afterRefreshCalled.Value = true; } } } // LUCENE-5461 [Test] public virtual void TestCRTReopen() { //test behaving badly //should be high enough int maxStaleSecs = 20; //build crap data just to store it. string s = " abcdefghijklmnopqrstuvwxyz "; char[] chars = s.ToCharArray(); StringBuilder builder = new StringBuilder(2048); for (int i = 0; i < 2048; i++) { builder.Append(chars[Random.Next(chars.Length)]); } string content = builder.ToString(); SnapshotDeletionPolicy sdp = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy()); Directory dir = new NRTCachingDirectory(NewFSDirectory(CreateTempDir("nrt")), 5, 128); IndexWriterConfig config = new IndexWriterConfig( #pragma warning disable 612, 618 Version.LUCENE_46, #pragma warning restore 612, 618 new MockAnalyzer(Random)); config.SetIndexDeletionPolicy(sdp); config.SetOpenMode(OpenMode.CREATE_OR_APPEND); IndexWriter iw = new IndexWriter(dir, config); SearcherManager sm = new SearcherManager(iw, true, new SearcherFactory()); TrackingIndexWriter tiw = new TrackingIndexWriter(iw); ControlledRealTimeReopenThread<IndexSearcher> controlledRealTimeReopenThread = new ControlledRealTimeReopenThread<IndexSearcher>(tiw, sm, maxStaleSecs, 0); controlledRealTimeReopenThread.IsBackground = (true); controlledRealTimeReopenThread.Start(); IList<ThreadJob> commitThreads = new JCG.List<ThreadJob>(); for (int i = 0; i < 500; i++) { if (i > 0 && i % 50 == 0) { ThreadJob commitThread = new RunnableAnonymousClass(this, sdp, dir, iw); commitThread.Start(); commitThreads.Add(commitThread); } Document d = new Document(); d.Add(new TextField("count", i + "", Field.Store.NO)); d.Add(new TextField("content", content, Field.Store.YES)); long start = J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond; // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results long l = tiw.AddDocument(d); controlledRealTimeReopenThread.WaitForGeneration(l); long wait = (J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond) - start; // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results assertTrue("waited too long for generation " + wait, wait < (maxStaleSecs * 1000)); IndexSearcher searcher = sm.Acquire(); TopDocs td = searcher.Search(new TermQuery(new Term("count", i + "")), 10); sm.Release(searcher); assertEquals(1, td.TotalHits); } foreach (ThreadJob commitThread in commitThreads) { commitThread.Join(); } controlledRealTimeReopenThread.Dispose(); sm.Dispose(); iw.Dispose(); dir.Dispose(); } private class RunnableAnonymousClass : ThreadJob { private readonly TestControlledRealTimeReopenThread outerInstance; private SnapshotDeletionPolicy sdp; private Directory dir; private IndexWriter iw; public RunnableAnonymousClass(TestControlledRealTimeReopenThread outerInstance, SnapshotDeletionPolicy sdp, Directory dir, IndexWriter iw) { this.outerInstance = outerInstance; this.sdp = sdp; this.dir = dir; this.iw = iw; } public override void Run() { try { iw.Commit(); IndexCommit ic = sdp.Snapshot(); foreach (string name in ic.FileNames) { //distribute, and backup //System.out.println(names); assertTrue(SlowFileExists(dir, name)); } } catch (Exception e) when (e.IsException()) { throw RuntimeException.Create(e); } } } /// <summary> /// This test was purposely written in a way that demonstrates how to use the /// ControlledRealTimeReopenThread. It contains seperate Asserts for each of /// several use cases rather then trying to brake these use cases up into /// seperate unit tests. This combined approach makes the behavior of /// ControlledRealTimeReopenThread easier to understand. /// </summary> // LUCENENET specific - An extra test to demonstrate use of ControlledRealTimeReopen. [Test] [LuceneNetSpecific] [Ignore("Run Manually (contains timing code that doesn't play well with other tests)")] public void TestStraightForwardDemonstration() { RAMDirectory indexDir = new RAMDirectory(); Analyzer standardAnalyzer = new StandardAnalyzer(TEST_VERSION_CURRENT); IndexWriterConfig indexConfig = new IndexWriterConfig(TEST_VERSION_CURRENT, standardAnalyzer); IndexWriter indexWriter = new IndexWriter(indexDir, indexConfig); TrackingIndexWriter trackingWriter = new TrackingIndexWriter(indexWriter); Document doc = new Document(); doc.Add(new Int32Field("id", 1, Field.Store.YES)); doc.Add(new StringField("name", "Doc1", Field.Store.YES)); trackingWriter.AddDocument(doc); SearcherManager searcherManager = new SearcherManager(indexWriter, applyAllDeletes: true, null); //Reopen SearcherManager every 1 secs via background thread if no thread waiting for newer generation. //Reopen SearcherManager after .2 secs if another thread IS waiting on a newer generation. var controlledRealTimeReopenThread = new ControlledRealTimeReopenThread<IndexSearcher>(trackingWriter, searcherManager, 1, 0.2); //Start() will start a seperate thread that will invoke the object's Run(). However, //calling Run() directly would execute that code on the current thread rather then a new thread //which would defeat the purpose of using controlledRealTimeReopenThread. This aspect of the API //is not as intuitive as it could be. ie. Call Start() not Run(). controlledRealTimeReopenThread.IsBackground = true; //Set as a background thread controlledRealTimeReopenThread.Name = "Controlled Real Time Reopen Thread"; controlledRealTimeReopenThread.Priority = (ThreadPriority)Math.Min((int)Thread.CurrentThread.Priority + 2, (int)ThreadPriority.Highest); controlledRealTimeReopenThread.Start(); //An indexSearcher only sees Doc1 IndexSearcher indexSearcher = searcherManager.Acquire(); try { TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1); assertEquals(1, topDocs.TotalHits); //There is only one doc } finally { searcherManager.Release(indexSearcher); } //Add a 2nd document doc = new Document(); doc.Add(new Int32Field("id", 2, Field.Store.YES)); doc.Add(new StringField("name", "Doc2", Field.Store.YES)); trackingWriter.AddDocument(doc); //Demonstrate that we can only see the first doc because we haven't //waited 1 sec or called WaitForGeneration indexSearcher = searcherManager.Acquire(); try { TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1); assertEquals(1, topDocs.TotalHits); //Can see both docs due to auto refresh after 1.1 secs } finally { searcherManager.Release(indexSearcher); } //Demonstrate that we can see both docs after we wait a little more //then 1 sec so that controlledRealTimeReopenThread max interval is exceeded //and it calls MaybeRefresh Thread.Sleep(1100); //wait 1.1 secs as ms indexSearcher = searcherManager.Acquire(); try { TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1); assertEquals(2, topDocs.TotalHits); //Can see both docs due to auto refresh after 1.1 secs } finally { searcherManager.Release(indexSearcher); } //Add a 3rd document doc = new Document(); doc.Add(new Int32Field("id", 3, Field.Store.YES)); doc.Add(new StringField("name", "Doc3", Field.Store.YES)); long generation = trackingWriter.AddDocument(doc); //Demonstrate that if we call WaitForGeneration our wait will be // .2 secs or less (the min interval we set earlier) and then we will //see all 3 documents. Stopwatch stopwatch = Stopwatch.StartNew(); controlledRealTimeReopenThread.WaitForGeneration(generation); stopwatch.Stop(); assertTrue(stopwatch.Elapsed.TotalMilliseconds <= 200 + 30); //30ms is fudged factor to account for call overhead. indexSearcher = searcherManager.Acquire(); try { TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1); assertEquals(3, topDocs.TotalHits); //Can see both docs due to auto refresh after 1.1 secs } finally { searcherManager.Release(indexSearcher); } controlledRealTimeReopenThread.Dispose(); searcherManager.Dispose(); indexWriter.Dispose(); indexDir.Dispose(); } /// <summary> /// In this test multiple threads are created each of which is waiting on the same /// generation before doing a search. These threads will all stack up on the /// WaitForGeneration(generation) call. All threads should return from this call /// in approximately in the time expected, namely the value for targetMinStaleSec passed /// to ControlledRealTimeReopenThread in it's constructor. /// </summary> // LUCENENET specific - An extra test to test multithreaded use of ControlledRealTimeReopen. [Test] [LuceneNetSpecific] [Ignore("Run Manually (contains timing code that doesn't play well with other tests)")] public void TestMultithreadedWaitForGeneration() { Thread CreateWorker(int threadNum, ControlledRealTimeReopenThread<IndexSearcher> controlledReopen, long generation, SearcherManager searcherManager, List<ThreadOutput> outputList) { ThreadStart threadStart = delegate { Stopwatch stopwatch = Stopwatch.StartNew(); controlledReopen.WaitForGeneration(generation); stopwatch.Stop(); double milliSecsWaited = stopwatch.Elapsed.TotalMilliseconds; int numRecs = 0; IndexSearcher indexSearcher = searcherManager.Acquire(); try { TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1); numRecs = topDocs.TotalHits; } finally { searcherManager.Release(indexSearcher); } lock (outputList) { outputList.Add(new ThreadOutput { ThreadNum = threadNum, NumRecs = numRecs, MilliSecsWaited = milliSecsWaited }); } }; return new Thread(threadStart); } int threadCount = 3; List<ThreadOutput> outputList = new List<ThreadOutput>(); RAMDirectory indexDir = new RAMDirectory(); Analyzer standardAnalyzer = new StandardAnalyzer(TEST_VERSION_CURRENT); IndexWriterConfig indexConfig = new IndexWriterConfig(TEST_VERSION_CURRENT, standardAnalyzer); IndexWriter indexWriter = new IndexWriter(indexDir, indexConfig); TrackingIndexWriter trackingWriter = new TrackingIndexWriter(indexWriter); //Add two documents Document doc = new Document(); doc.Add(new Int32Field("id", 1, Field.Store.YES)); doc.Add(new StringField("name", "Doc1", Field.Store.YES)); long generation = trackingWriter.AddDocument(doc); doc.Add(new Int32Field("id", 2, Field.Store.YES)); doc.Add(new StringField("name", "Doc3", Field.Store.YES)); generation = trackingWriter.AddDocument(doc); SearcherManager searcherManager = new SearcherManager(indexWriter, applyAllDeletes: true, null); //Reopen SearcherManager every 2 secs via background thread if no thread waiting for newer generation. //Reopen SearcherManager after .2 secs if another thread IS waiting on a newer generation. double maxRefreshSecs = 2.0; double minRefreshSecs = .2; var controlledRealTimeReopenThread = new ControlledRealTimeReopenThread<IndexSearcher>(trackingWriter, searcherManager, maxRefreshSecs, minRefreshSecs); //Start() will start a seperate thread that will invoke the object's Run(). However, //calling Run() directly would execute that code on the current thread rather then a new thread //which would defeat the purpose of using controlledRealTimeReopenThread. This aspect of the API //is not as intuitive as it could be. ie. Call Start() not Run(). controlledRealTimeReopenThread.IsBackground = true; //Set as a background thread controlledRealTimeReopenThread.Name = "Controlled Real Time Reopen Thread"; controlledRealTimeReopenThread.Priority = (ThreadPriority)Math.Min((int)Thread.CurrentThread.Priority + 2, (int)ThreadPriority.Highest); controlledRealTimeReopenThread.Start(); //Create the threads for doing searchers List<Thread> threadList = new List<Thread>(); for (int i = 1; i <= threadCount; i++) { threadList.Add(CreateWorker(i, controlledRealTimeReopenThread, generation, searcherManager, outputList)); } //Start all the threads foreach (Thread thread in threadList) { thread.Start(); } //wait for the threads to finish. foreach (Thread thread in threadList) { thread.Join(); //will wait here until the thread terminates. } //Now make sure that no thread waited longer then our min refresh time //plus a small fudge factor. Also verify that all threads resported back and //each saw 2 records. //Verify all threads reported back a result. assertEquals(threadCount, outputList.Count); int millisecsPerSec = 1000; foreach (ThreadOutput output in outputList) { //Verify the thread saw exactly 2 docs assertEquals(2, output.NumRecs); //Verify the thread wait time was around what was expected. Assert.True(output.MilliSecsWaited <= (minRefreshSecs * millisecsPerSec) + 30); //30ms is fudged factor to account for call overhead } controlledRealTimeReopenThread.Dispose(); //will kill and join to the thread Assert.False(controlledRealTimeReopenThread.IsAlive); //to prove that Dispose really does kill the thread. searcherManager.Dispose(); indexWriter.Dispose(); indexDir.Dispose(); } [DebuggerDisplay("ThreadNum:{ThreadNum}, NumRecs:{NumRecs}, MilliSecsWaited:{MilliSecsWaited}")] public class ThreadOutput { public int ThreadNum { get; set; } public int NumRecs { get; set; } public double MilliSecsWaited { get; set; } } } }
40.049751
197
0.574012
[ "Apache-2.0" ]
10088/lucenenet
src/Lucene.Net.Tests/Search/TestControlledRealTimeReopenThread.cs
40,252
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.PolicyInsights.Latest { /// <summary> /// The remediation definition. /// </summary> public partial class RemediationAtResourceGroup : Pulumi.CustomResource { /// <summary> /// The time at which the remediation was created. /// </summary> [Output("createdOn")] public Output<string> CreatedOn { get; private set; } = null!; /// <summary> /// The deployment status summary for all deployments created by the remediation. /// </summary> [Output("deploymentStatus")] public Output<Outputs.RemediationDeploymentSummaryResponse> DeploymentStatus { get; private set; } = null!; /// <summary> /// The filters that will be applied to determine which resources to remediate. /// </summary> [Output("filters")] public Output<Outputs.RemediationFiltersResponse?> Filters { get; private set; } = null!; /// <summary> /// The time at which the remediation was last updated. /// </summary> [Output("lastUpdatedOn")] public Output<string> LastUpdatedOn { get; private set; } = null!; /// <summary> /// The name of the remediation. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The resource ID of the policy assignment that should be remediated. /// </summary> [Output("policyAssignmentId")] public Output<string?> PolicyAssignmentId { get; private set; } = null!; /// <summary> /// The policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. /// </summary> [Output("policyDefinitionReferenceId")] public Output<string?> PolicyDefinitionReferenceId { get; private set; } = null!; /// <summary> /// The status of the remediation. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. /// </summary> [Output("resourceDiscoveryMode")] public Output<string?> ResourceDiscoveryMode { get; private set; } = null!; /// <summary> /// The type of the remediation. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a RemediationAtResourceGroup resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public RemediationAtResourceGroup(string name, RemediationAtResourceGroupArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:policyinsights/latest:RemediationAtResourceGroup", name, args ?? new RemediationAtResourceGroupArgs(), MakeResourceOptions(options, "")) { } private RemediationAtResourceGroup(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:policyinsights/latest:RemediationAtResourceGroup", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:policyinsights/v20180701preview:RemediationAtResourceGroup"}, new Pulumi.Alias { Type = "azure-nextgen:policyinsights/v20190701:RemediationAtResourceGroup"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing RemediationAtResourceGroup resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static RemediationAtResourceGroup Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new RemediationAtResourceGroup(name, id, options); } } public sealed class RemediationAtResourceGroupArgs : Pulumi.ResourceArgs { /// <summary> /// The filters that will be applied to determine which resources to remediate. /// </summary> [Input("filters")] public Input<Inputs.RemediationFiltersArgs>? Filters { get; set; } /// <summary> /// The resource ID of the policy assignment that should be remediated. /// </summary> [Input("policyAssignmentId")] public Input<string>? PolicyAssignmentId { get; set; } /// <summary> /// The policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. /// </summary> [Input("policyDefinitionReferenceId")] public Input<string>? PolicyDefinitionReferenceId { get; set; } /// <summary> /// The name of the remediation. /// </summary> [Input("remediationName", required: true)] public Input<string> RemediationName { get; set; } = null!; /// <summary> /// The way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. /// </summary> [Input("resourceDiscoveryMode")] public Input<string>? ResourceDiscoveryMode { get; set; } /// <summary> /// Resource group name. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; public RemediationAtResourceGroupArgs() { } } }
42.464286
188
0.626156
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/PolicyInsights/Latest/RemediationAtResourceGroup.cs
7,134
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Ultz Limited")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyDescriptionAttribute("Beagle Framework is a database access technology for C#, extracted from Ultz Onli" + "ne for public use. This package binds Beagle to MySQL")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.1.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.1.0")] [assembly: System.Reflection.AssemblyProductAttribute("Beagle Framework")] [assembly: System.Reflection.AssemblyTitleAttribute("Ultz.BeagleFramework.MySql")] [assembly: System.Reflection.AssemblyVersionAttribute("1.1.0.0")] // Generated by the MSBuild WriteCodeFragment class.
46.538462
143
0.67438
[ "MIT" ]
Ultz/BeagleFramework
Ultz.BeagleFramework.MySql/obj/Debug/netstandard2.0/Ultz.BeagleFramework.MySql.AssemblyInfo.cs
1,210
C#
using Core.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Core.DataAccess { public interface IEntityRepository<T> where T : class, IEntity, new() { // CRUD Operations void Add(T entity); void Update(T entity); void Delete(T entity); List<T> GetAll(Expression<Func<T, bool>> filter = null); T Get(Expression<Func<T, bool>> filter); } }
24.619048
73
0.669246
[ "MIT" ]
tuncerrstm/ReCapProject
Core/DataAccess/IEntityRepository.cs
519
C#
#region License // Copyright 2015-2021 John Källén // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; namespace Pytocs.Core.CodeModel { public class IndentingTextWriter { private TextWriter writer; private bool atStartOfLine; private static HashSet<string> csharpKeywords = new HashSet<string> { "base", "bool", "const", "case", "checked", "class", "decimal", "default", "do", "enum", "event", "explicit", "false", "in", "implicit", "int", "lock", "long", "namespace", "new", "operator", "out", "override", "ref", "readonly", "sizeof", "static", "string", "struct", "switch", "this", "true", }; public IndentingTextWriter(TextWriter writer) { this.writer = writer; this.atStartOfLine = true; } public int IndentLevel { get; set; } public void Write(string s) { EnsureIndentation(); this.writer.Write(s); } internal void WriteLine() { EnsureIndentation(); writer.WriteLine(); atStartOfLine = true; } internal void WriteLine(string str) { EnsureIndentation(); writer.WriteLine(str); atStartOfLine = true; } public void WriteName(string name) { EnsureIndentation(); if (NameNeedsQuoting(name)) writer.Write("@"); writer.Write(name); } public static string QuoteName(string name) { if (NameNeedsQuoting(name)) return "@" + name; else return name; } public static bool NameNeedsQuoting(string name) { if (name.Contains("__")) return true; return csharpKeywords.Contains(name); } internal void Write(string format, params object [] args) { EnsureIndentation(); writer.Write(format, args); } private void EnsureIndentation() { if (atStartOfLine) { writer.Write(new string(' ', 4 * IndentLevel)); atStartOfLine = false; } } public void WriteDottedName(string dottedString) { var sep = false; foreach (var name in dottedString.Split('.')) { if (sep) writer.Write('.'); sep = true; WriteName(name); } } public void Write(char ch) { EnsureIndentation(); writer.Write(ch); } } }
24.766667
76
0.491252
[ "Apache-2.0" ]
amwsaq/pytocs
src/Core/CodeModel/IndentingTextWriter.cs
3,717
C#
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2014 Tasharen Entertainment //---------------------------------------------- #if UNITY_EDITOR || !UNITY_FLASH #define REFLECTION_SUPPORT #endif #if REFLECTION_SUPPORT using System.Reflection; using System.Diagnostics; #endif using UnityEngine; using System; /// <summary> /// Reference to a specific field or property that can be set via inspector. /// </summary> [System.Serializable] public class PropertyReference { [SerializeField] Component mTarget; [SerializeField] string mName; #if REFLECTION_SUPPORT FieldInfo mField = null; PropertyInfo mProperty = null; #endif /// <summary> /// Event delegate's target object. /// </summary> public Component target { get { return mTarget; } set { mTarget = value; #if REFLECTION_SUPPORT mProperty = null; mField = null; #endif } } /// <summary> /// Event delegate's method name. /// </summary> public string name { get { return mName; } set { mName = value; #if REFLECTION_SUPPORT mProperty = null; mField = null; #endif } } /// <summary> /// Whether this delegate's values have been set. /// </summary> public bool isValid { get { return (mTarget != null && !string.IsNullOrEmpty(mName)); } } /// <summary> /// Whether the target script is actually enabled. /// </summary> public bool isEnabled { get { if (mTarget == null) return false; MonoBehaviour mb = (mTarget as MonoBehaviour); return (mb == null || mb.enabled); } } public PropertyReference () { } public PropertyReference (Component target, string fieldName) { mTarget = target; mName = fieldName; } /// <summary> /// Helper function that returns the property type. /// </summary> public Type GetPropertyType () { #if REFLECTION_SUPPORT if (mProperty == null && mField == null && isValid) Cache(); if (mProperty != null) return mProperty.PropertyType; if (mField != null) return mField.FieldType; #endif #if UNITY_EDITOR || !UNITY_FLASH return typeof(void); #else return null; #endif } /// <summary> /// Equality operator. /// </summary> public override bool Equals (object obj) { if (obj == null) { return !isValid; } if (obj is PropertyReference) { PropertyReference pb = obj as PropertyReference; return (mTarget == pb.mTarget && string.Equals(mName, pb.mName)); } return false; } static int s_Hash = "PropertyBinding".GetHashCode(); /// <summary> /// Used in equality operators. /// </summary> public override int GetHashCode () { return s_Hash; } /// <summary> /// Set the delegate callback using the target and method names. /// </summary> public void Set (Component target, string methodName) { mTarget = target; mName = methodName; } /// <summary> /// Clear the event delegate. /// </summary> public void Clear () { mTarget = null; mName = null; } /// <summary> /// Reset the cached references. /// </summary> public void Reset () { #if REFLECTION_SUPPORT mField = null; mProperty = null; #endif } /// <summary> /// Convert the delegate to its string representation. /// </summary> public override string ToString () { return ToString(mTarget, name); } /// <summary> /// Convenience function that converts the specified component + property pair into its string representation. /// </summary> static public string ToString (Component comp, string property) { if (comp != null) { string typeName = comp.GetType().ToString(); int period = typeName.LastIndexOf('.'); if (period > 0) typeName = typeName.Substring(period + 1); if (!string.IsNullOrEmpty(property)) return typeName + "." + property; else return typeName + ".[property]"; } return null; } #if REFLECTION_SUPPORT /// <summary> /// Retrieve the property's value. /// </summary> [DebuggerHidden] [DebuggerStepThrough] public object Get () { if (mProperty == null && mField == null && isValid) Cache(); if (mProperty != null) { if (mProperty.CanRead) return mProperty.GetValue(mTarget, null); } else if (mField != null) { return mField.GetValue(mTarget); } return null; } /// <summary> /// Assign the bound property's value. /// </summary> [DebuggerHidden] [DebuggerStepThrough] public bool Set (object value) { if (mProperty == null && mField == null && isValid) Cache(); if (mProperty == null && mField == null) return false; if (value == null) { try { if (mProperty != null) mProperty.SetValue(mTarget, null, null); else mField.SetValue(mTarget, null); } catch (Exception) { return false; } } // Can we set the value? if (!Convert(ref value)) { if (Application.isPlaying) UnityEngine.Debug.LogError("Unable to convert " + value.GetType() + " to " + GetPropertyType()); } else if (mField != null) { mField.SetValue(mTarget, value); return true; } else if (mProperty.CanWrite) { mProperty.SetValue(mTarget, value, null); return true; } return false; } /// <summary> /// Cache the field or property. /// </summary> [DebuggerHidden] [DebuggerStepThrough] bool Cache () { if (mTarget != null && !string.IsNullOrEmpty(mName)) { Type type = mTarget.GetType(); #if NETFX_CORE mField = type.GetRuntimeField(mName); mProperty = type.GetRuntimeProperty(mName); #else mField = type.GetField(mName); mProperty = type.GetProperty(mName); #endif } else { mField = null; mProperty = null; } return (mField != null || mProperty != null); } /// <summary> /// Whether we can assign the property using the specified value. /// </summary> bool Convert (ref object value) { if (mTarget == null) return false; Type to = GetPropertyType(); Type from; if (value == null) { #if NETFX_CORE if (!to.GetTypeInfo().IsClass) return false; #else if (!to.IsClass) return false; #endif from = to; } else from = value.GetType(); return Convert(ref value, from, to); } #else // Everything below = no reflection support public object Get () { Debug.LogError("Reflection is not supported on this platform"); return null; } public bool Set (object value) { Debug.LogError("Reflection is not supported on this platform"); return false; } bool Cache () { return false; } bool Convert (ref object value) { return false; } #endif /// <summary> /// Whether we can convert one type to another for assignment purposes. /// </summary> static public bool Convert (Type from, Type to) { object temp = null; return Convert(ref temp, from, to); } /// <summary> /// Whether we can convert one type to another for assignment purposes. /// </summary> static public bool Convert (object value, Type to) { if (value == null) { value = null; return Convert(ref value, to, to); } return Convert(ref value, value.GetType(), to); } /// <summary> /// Whether we can convert one type to another for assignment purposes. /// </summary> static public bool Convert (ref object value, Type from, Type to) { #if REFLECTION_SUPPORT // If the value can be assigned as-is, we're done #if NETFX_CORE if (to.GetTypeInfo().IsAssignableFrom(from.GetTypeInfo())) return true; #else if (to.IsAssignableFrom(from)) return true; #endif #else if (from == to) return true; #endif // If the target type is a string, just convert the value if (to == typeof(string)) { value = (value != null) ? value.ToString() : "null"; return true; } // If the value is null we should not proceed further if (value == null) return false; if (to == typeof(int)) { if (from == typeof(string)) { int val; if (int.TryParse((string)value, out val)) { value = val; return true; } } else if (from == typeof(float)) { value = Mathf.RoundToInt((float)value); return true; } } else if (to == typeof(float)) { if (from == typeof(string)) { float val; if (float.TryParse((string)value, out val)) { value = val; return true; } } } return false; } }
19.603365
111
0.638627
[ "MIT" ]
741645596/batgame
Assets/NGUI/Scripts/Internal/PropertyReference.cs
8,156
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Containers; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Match; using osu.Game.Users; namespace osu.Game.Screens.OnlinePlay { /// <summary> /// A <see cref="CompositeDrawable"/> that exposes bindables for <see cref="Room"/> properties. /// </summary> public class OnlinePlayComposite : CompositeDrawable { [Resolved(typeof(Room))] protected Bindable<long?> RoomID { get; private set; } [Resolved(typeof(Room), nameof(Room.Name))] protected Bindable<string> RoomName { get; private set; } [Resolved(typeof(Room))] protected Bindable<User> Host { get; private set; } [Resolved(typeof(Room))] protected Bindable<RoomStatus> Status { get; private set; } [Resolved(typeof(Room))] protected Bindable<MatchType> Type { get; private set; } [Resolved(typeof(Room))] protected BindableList<PlaylistItem> Playlist { get; private set; } [Resolved(typeof(Room))] protected BindableList<User> RecentParticipants { get; private set; } [Resolved(typeof(Room))] protected Bindable<int> ParticipantCount { get; private set; } [Resolved(typeof(Room))] protected Bindable<int?> MaxParticipants { get; private set; } [Resolved(typeof(Room))] protected Bindable<int?> MaxAttempts { get; private set; } [Resolved(typeof(Room))] public Bindable<PlaylistAggregateScore> UserScore { get; private set; } [Resolved(typeof(Room))] protected Bindable<DateTimeOffset?> EndDate { get; private set; } [Resolved(typeof(Room))] protected Bindable<RoomAvailability> Availability { get; private set; } [Resolved(typeof(Room), nameof(Room.Password))] public Bindable<string> Password { get; private set; } [Resolved(typeof(Room))] protected Bindable<TimeSpan?> Duration { get; private set; } /// <summary> /// The currently selected item in the <see cref="RoomSubScreen"/>, or the first item from <see cref="Playlist"/> /// if this <see cref="OnlinePlayComposite"/> is not within a <see cref="RoomSubScreen"/>. /// </summary> protected readonly Bindable<PlaylistItem> SelectedItem = new Bindable<PlaylistItem>(); protected override void LoadComplete() { base.LoadComplete(); Playlist.BindCollectionChanged((_, __) => UpdateSelectedItem(), true); } protected virtual void UpdateSelectedItem() { SelectedItem.Value = Playlist.FirstOrDefault(); } } }
35.630952
122
0.632142
[ "MIT" ]
1uws/osu
osu.Game/Screens/OnlinePlay/OnlinePlayComposite.cs
2,910
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace Switcher.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init (); LoadApplication (new Switcher.App ()); return base.FinishedLaunching (app, options); } } }
31.375
95
0.749004
[ "MIT" ]
Zyver-Meeps/Switcher.Old
Switcher/Switcher.iOS/AppDelegate.cs
1,006
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using Ti_poll.Clases; namespace Ti_poll { /// <summary> /// Interaction logic for Perfil.xaml /// </summary> public partial class Perfil : Window { public Perfil() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { nickname.Content = Database.CurrentUser.Nickname; name.Text = Database.CurrentUser.Name; age.Text = Database.CurrentUser.Age.ToString(); points.Text = Database.CurrentUser.Points.ToString(); gender.Text = Database.CurrentUser.Backgrounds.Gender; relationship.Text = Database.CurrentUser.Backgrounds.Relationship; country.Text = Database.CurrentUser.Backgrounds.Country; ethnicity.Text = Database.CurrentUser.Backgrounds.Ethnicity; income.Text = Database.CurrentUser.Backgrounds.Income.ToString(); sexuality.Text = Database.CurrentUser.Backgrounds.Sexuality; } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Owner.Show(); } private void save_Click(object sender, RoutedEventArgs e) { if (name.Text.Length > 0) Database.CurrentUser.Name = name.Text; if (password.Password.Length > 0) Database.CurrentUser.Password = Database.CurrentUser.Password = Database.encrypt_text(password.Password); if (age.Text.Length > 0 && int.TryParse(age.Text, out int Age)) Database.CurrentUser.Age = Age; if (income.Text.Length > 0 && double.TryParse(income.Text, out double Income)) Database.CurrentUser.Backgrounds.Income = Income; if (gender.Text.Length > 0) Database.CurrentUser.Backgrounds.Gender = gender.Text; if (country.Text.Length > 0) Database.CurrentUser.Backgrounds.Country = country.Text; if (ethnicity.Text.Length > 0) Database.CurrentUser.Backgrounds.Ethnicity = ethnicity.Text; if (sexuality.Text.Length > 0) Database.CurrentUser.Backgrounds.Sexuality = sexuality.Text; if (relationship.Text.Length > 0) Database.CurrentUser.Backgrounds.Relationship = relationship.Text; Database.data.save(); MessageBox.Show("Se guardo correctamente!"); } private void exit_Click(object sender, RoutedEventArgs e) { Close(); } } }
38.30137
151
0.669528
[ "MIT" ]
ClarkThyLord/Ti-poll
Ti-poll/Ti-poll/Profile.xaml.cs
2,798
C#
using System.ComponentModel; namespace EtherCATMaster { /// <summary> /// 軸狀態編號。 /// </summary> public enum AxisStates { /// <summary> /// 軸尚未啟用。 /// </summary> [Description("軸尚未啟用。")] MC_AS_DISABLED = 0, /// <summary> /// 軸啟用且為停止狀態,準備接收新的運動命令。 /// </summary> [Description("軸啟用且為停止狀態,準備接收新的運動命令。")] MC_AS_STANDSTILL = 1, /// <summary> /// 軸目前出現錯誤且為停止狀態。 /// </summary> [Description("軸目前出現錯誤且為停止狀態。")] MC_AS_ERRORSTOP = 2, /// <summary> /// 軸目前在停止運動中。 /// </summary> [Description("軸目前在停止運動中。")] MC_AS_STOPPING = 3, /// <summary> /// 軸目前在原點復歸中。 /// </summary> [Description("軸目前在原點復歸中。")] MC_AS_HOMING = 4, /// <summary> /// 軸目前單軸運動中。 /// </summary> [Description("軸目前單軸運動中。")] MC_AS_DISCRETEMOTION = 5, /// <summary> /// 軸目前連續運動中。 /// </summary> [Description("軸目前連續運動中。")] MC_AS_CONTINUOUSMOTION = 6, /// <summary> /// 軸目前同步運動中,軸在群組中,群組正在進行補間運動。 /// </summary> [Description("軸目前同步運動中,軸在群組中,群組正在進行補間運動。")] MC_AS_SYNCHRONIZEDMOTION = 7, /// <summary> /// 方向盤運動中(?)。 /// </summary> [Description("方向盤運動中(?)。")] MC_AS_STEERWHEELMOTION = 8 } }
24.929825
51
0.478536
[ "BSD-3-Clause" ]
Muzsor/MicroIPC
EtherCATMaster/Enum/AxisStates.cs
1,883
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using UAlbion.Api; namespace UAlbion.TestCommon { public class MockFileSystem : IFileSystem { static readonly char[] SeparatorChars = { '\\', '/' }; readonly DirNode _root = new(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "" : "/"); readonly Func<string, bool> _maskingFunc; public MockFileSystem(Func<string, bool> maskingFunc) => _maskingFunc = maskingFunc ?? throw new ArgumentNullException(nameof(maskingFunc)); public MockFileSystem(bool fallBackToFileSystem) => _maskingFunc = fallBackToFileSystem ? (Func<string, bool>)(_ => true) : _ => false; interface INode { string Path { get; } } class DirNode : Dictionary<string, INode>, INode { public DirNode(string path) => Path = path; public string Path { get; } public override string ToString() => Path; } class FileNode : INode { public FileNode(string path) { Path = path; Stream = new MemoryStream(); } public string Path { get; } public MemoryStream Stream { get; } public override string ToString() => $"{Path} ({Stream.Length} bytes)"; } INode GetDir(string path) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException(nameof(path)); if (path.Length > 260) throw new PathTooLongException(); INode node = _root; foreach (var part in path.Split(SeparatorChars, StringSplitOptions.RemoveEmptyEntries)) { if (!(node is DirNode dir)) return null; if (dir.TryGetValue(part, out node)) continue; var nodePath = Path.Combine(dir.Path, part); if (_maskingFunc(nodePath) && Directory.Exists(nodePath)) { node = new DirNode(nodePath); dir[part] = node; } else return null; } return node; } (DirNode, INode) GetFile(string path) { if (!(GetDir(Path.GetDirectoryName(path)) is DirNode dir)) throw new DirectoryNotFoundException($"Could not find a part of the path '{path}'."); var filename = Path.GetFileName(path); dir.TryGetValue(filename, out var node); if (node == null && _maskingFunc(path) && File.Exists(path)) { var newFile = new FileNode(Path.Combine(dir.Path, filename)); using var s = File.OpenRead(path); s.CopyTo(newFile.Stream); dir[filename] = newFile; node = newFile; } return (dir, node); } public void CreateDirectory(string path) { path = Path.GetFullPath(path); if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException(nameof(path)); if (path.Length > 260) throw new PathTooLongException(); INode node = _root; foreach (var part in path.Split(SeparatorChars, StringSplitOptions.RemoveEmptyEntries)) { switch (node) { case FileNode file: throw new IOException($"Cannot create \"{file.Path}\" because a file or directory with the same name already exists."); case DirNode dir: if (!dir.TryGetValue(part, out node)) { node = new DirNode(Path.Combine(dir.Path, part)); dir[part] = node; } break; } } } static Regex FilterToRegex(string filter) { var sb = new StringBuilder(); sb.Append('^'); foreach (var c in filter) { switch (c) { case '*': sb.Append(".*"); break; case '?': sb.Append('.'); break; case '.': sb.Append("\\."); break; default: sb.Append(c); break; } } sb.Append('$'); return new Regex(sb.ToString()); } public bool FileExists(string path) { path = Path.GetFullPath(path); if (!(GetDir(Path.GetDirectoryName(path)) is DirNode dir)) return false; var filename = Path.GetFileName(path); var result = dir.ContainsKey(filename); return !result && _maskingFunc(path) ? File.Exists(path) : result; } public bool DirectoryExists(string path) { path = Path.GetFullPath(path); return GetDir(path) is DirNode; } public IEnumerable<string> EnumerateDirectory(string path, string filter = null) { path = Path.GetFullPath(path); if (!(GetDir(path) is DirNode dir)) return Enumerable.Empty<string>(); var regex = filter == null ? null : FilterToRegex(filter); return dir .Where(kvp => kvp.Value is FileNode && (regex?.IsMatch(kvp.Key) ?? true)) .Select(x => x.Value.Path); } public Stream OpenRead(string path) => GetFile(Path.GetFullPath(path)) switch { ({ }, FileNode file) => new MockFileStream(file.Stream, true), ({ }, DirNode _) => throw new UnauthorizedAccessException($"Access to the path '{path}' is denied."), _ => throw new FileNotFoundException($"Could not find file '{path}'.") }; public Stream OpenWriteTruncate(string path) { path = Path.GetFullPath(path); var filename = Path.GetFileName(path); switch (GetFile(path)) { case ({ }, FileNode file): file.Stream.Position = 0; file.Stream.SetLength(0); return new MockFileStream(file.Stream); case ({ }, DirNode _): throw new UnauthorizedAccessException($"Access to the path '{path}' is denied."); case ({ } dir, null): var newFile = new FileNode($"{dir.Path}\\{filename}"); dir[filename] = newFile; return new MockFileStream(newFile.Stream); default: throw new FileNotFoundException($"Could not find file '{path}'."); } } public void DeleteFile(string path) { path = Path.GetFullPath(path); var (dir, file) = GetFile(path); if (file == null) return; dir.Remove(Path.GetFileName(path)); } public string ReadAllText(string path) { path = Path.GetFullPath(path); using var s = OpenRead(path); using var sr = new StreamReader(s); return sr.ReadToEnd(); } public void WriteAllText(string path, string fullText) { path = Path.GetFullPath(path); using var s = OpenWriteTruncate(path); using var sw = new StreamWriter(s); sw.Write(fullText); } public IEnumerable<string> ReadAllLines(string path) { path = Path.GetFullPath(path); using var s = OpenRead(path); using var sr = new StreamReader(s); while (!sr.EndOfStream) yield return sr.ReadLine(); } public byte[] ReadAllBytes(string path) { path = Path.GetFullPath(path); using var s = OpenRead(path); using var br = new BinaryReader(s); return br.ReadBytes((int)s.Length); } public void WriteAllBytes(string path, byte[] bytes) { path = Path.GetFullPath(path); using var s = OpenWriteTruncate(path); using var bw = new BinaryWriter(s); bw.Write(bytes); } } }
35.820513
148
0.51885
[ "MIT" ]
Metibor/ualbion
src/Tests/UAlbion.TestCommon/MockFileSystem.cs
8,384
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("LibrarySystem.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LibrarySystem.Web")] [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("7baa7f74-a7a1-4837-bd0b-4102e4f00563")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.833333
84
0.751836
[ "MIT" ]
ArnaudovSt/LibrarySystem
LibrarySystem/LibrarySystem.Web/Properties/AssemblyInfo.cs
1,365
C#
using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Markup; namespace Wpf.Controls { /// <summary> /// Implemetation of a Split Button /// </summary> [TemplatePart(Name = "PART_DropDown", Type = typeof(Button))] [ContentProperty("Items")] [DefaultProperty("Items")] public class SplitButton : Button { // AddOwner Dependency properties public static readonly DependencyProperty HorizontalOffsetProperty; public static readonly DependencyProperty IsContextMenuOpenProperty; public static readonly DependencyProperty ModeProperty; public static readonly DependencyProperty PlacementProperty; public static readonly DependencyProperty PlacementRectangleProperty; public static readonly DependencyProperty VerticalOffsetProperty; /// <summary> /// Static Constructor /// </summary> static SplitButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata(typeof(SplitButton))); IsContextMenuOpenProperty = DependencyProperty.Register("IsContextMenuOpen", typeof(bool), typeof(SplitButton), new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnIsContextMenuOpenChanged))); ModeProperty = DependencyProperty.Register("Mode", typeof(SplitButtonMode), typeof(SplitButton), new FrameworkPropertyMetadata(SplitButtonMode.Split)); // AddOwner properties from the ContextMenuService class, we need callbacks from these properties // to update the Buttons ContextMenu properties PlacementProperty = ContextMenuService.PlacementProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata(PlacementMode.Bottom, new PropertyChangedCallback(OnPlacementChanged))); PlacementRectangleProperty = ContextMenuService.PlacementRectangleProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata(Rect.Empty, new PropertyChangedCallback(OnPlacementRectangleChanged))); HorizontalOffsetProperty = ContextMenuService.HorizontalOffsetProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata(0.0, new PropertyChangedCallback(OnHorizontalOffsetChanged))); VerticalOffsetProperty = ContextMenuService.VerticalOffsetProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata(0.0, new PropertyChangedCallback(OnVerticalOffsetChanged))); } /* * Overrides * */ /// <summary> /// OnApplyTemplate override, set up the click event for the dropdown if present in the template /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); // set up the click event handler for the dropdown button ButtonBase dropDown = this.Template.FindName("PART_DropDown", this) as ButtonBase; if (dropDown != null) dropDown.Click += Dropdown_Click; } /// <summary> /// Handles the Base Buttons OnClick event /// </summary> protected override void OnClick() { switch (Mode) { case SplitButtonMode.Dropdown: OnDropdown(); break; default: base.OnClick(); // forward on the Click event to the user break; } } /* * Properties * */ /// <summary> /// The Split Button's Items property maps to the base classes ContextMenu.Items property /// </summary> public ItemCollection Items { get { EnsureContextMenuIsValid(); return this.ContextMenu.Items; } } /* * DependencyProperty CLR wrappers * */ /// <summary> /// Gets or sets the IsContextMenuOpen property. /// </summary> public bool IsContextMenuOpen { get { return (bool)GetValue(IsContextMenuOpenProperty); } set { SetValue(IsContextMenuOpenProperty, value); } } /// <summary> /// Placement of the Context menu /// </summary> public PlacementMode Placement { get { return (PlacementMode)GetValue(PlacementProperty); } set { SetValue(PlacementProperty, value); } } /// <summary> /// PlacementRectangle of the Context menu /// </summary> public Rect PlacementRectangle { get { return (Rect)GetValue(PlacementRectangleProperty); } set { SetValue(PlacementRectangleProperty, value); } } /// <summary> /// HorizontalOffset of the Context menu /// </summary> public double HorizontalOffset { get { return (double)GetValue(HorizontalOffsetProperty); } set { SetValue(HorizontalOffsetProperty, value); } } /// <summary> /// VerticalOffset of the Context menu /// </summary> public double VerticalOffset { get { return (double)GetValue(VerticalOffsetProperty); } set { SetValue(VerticalOffsetProperty, value); } } /// <summary> /// Defines the Mode of operation of the Button /// </summary> /// <remarks> /// The SplitButton two Modes are /// Split (default), - the button has two parts, a normal button and a dropdown which exposes the ContextMenu /// Dropdown - the button acts like a combobox, clicking anywhere on the button opens the Context Menu /// </remarks> public SplitButtonMode Mode { get { return (SplitButtonMode)GetValue(ModeProperty); } set { SetValue(ModeProperty, value); } } /* * DependencyPropertyChanged callbacks * */ private static void OnIsContextMenuOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SplitButton s = (SplitButton)d; s.EnsureContextMenuIsValid(); if (!s.ContextMenu.HasItems) return; bool value = (bool)e.NewValue; if (value && !s.ContextMenu.IsOpen) s.ContextMenu.IsOpen = true; else if (!value && s.ContextMenu.IsOpen) s.ContextMenu.IsOpen = false; } /// <summary> /// Placement Property changed callback, pass the value through to the buttons context menu /// </summary> private static void OnPlacementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SplitButton s = d as SplitButton; if (s == null) return; s.EnsureContextMenuIsValid(); s.ContextMenu.Placement = (PlacementMode)e.NewValue; } /// <summary> /// PlacementRectangle Property changed callback, pass the value through to the buttons context menu /// </summary> private static void OnPlacementRectangleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SplitButton s = d as SplitButton; if (s == null) return; s.EnsureContextMenuIsValid(); s.ContextMenu.PlacementRectangle = (Rect)e.NewValue; } /// <summary> /// HorizontalOffset Property changed callback, pass the value through to the buttons context menu /// </summary> private static void OnHorizontalOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SplitButton s = d as SplitButton; if (s == null) return; s.EnsureContextMenuIsValid(); s.ContextMenu.HorizontalOffset = (double)e.NewValue; } /// <summary> /// VerticalOffset Property changed callback, pass the value through to the buttons context menu /// </summary> private static void OnVerticalOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SplitButton s = d as SplitButton; if (s == null) return; s.EnsureContextMenuIsValid(); s.ContextMenu.VerticalOffset = (double)e.NewValue; } /* * Helper Methods * */ /// <summary> /// Make sure the Context menu is not null /// </summary> private void EnsureContextMenuIsValid() { if (this.ContextMenu == null) { this.ContextMenu = new ContextMenu(); this.ContextMenu.PlacementTarget = this; this.ContextMenu.Placement = Placement; this.ContextMenu.Opened += ((sender, routedEventArgs) => IsContextMenuOpen = true); this.ContextMenu.Closed += ((sender, routedEventArgs) => IsContextMenuOpen = false); } } private void OnDropdown() { EnsureContextMenuIsValid(); if (!this.ContextMenu.HasItems) return; this.ContextMenu.IsOpen = !IsContextMenuOpen; // open it if closed, close it if open } /* * Events * */ /// <summary> /// Event Handler for the Drop Down Button's Click event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Dropdown_Click(object sender, RoutedEventArgs e) { OnDropdown(); e.Handled = true; } } }
36.458781
220
0.583956
[ "Apache-2.0" ]
mcleo-d/SFE-Minuet-DesktopClient
minuet/Paragon.Runtime/WPF/Download/SplitButton.cs
10,174
C#
using UnityScreenNavigator.Runtime.Foundation.AssetLoader; namespace Demo.Scripts { public class DemoAssetLoader : AssetLoaderObject { private readonly ResourcesAssetLoader _loader = new ResourcesAssetLoader(); public override AssetLoadHandle<T> Load<T>(string key) { return _loader.Load<T>(GetResourceKey(key)); } public override AssetLoadHandle<T> LoadAsync<T>(string key) { return _loader.LoadAsync<T>(GetResourceKey(key)); } public override void Release(AssetLoadHandle handle) { _loader.Release(handle); } private string GetResourceKey(string key) { return $"Prefabs/prefab_demo_{key}"; } } }
26.413793
83
0.625326
[ "MIT" ]
Haruma-K/UnityScreenNavigator
Assets/Demo/Scripts/DemoAssetLoader.cs
766
C#
namespace BUR_UI { partial class Form1 { /// <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(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.lblUser = new System.Windows.Forms.Label(); this.lblPos = new System.Windows.Forms.Label(); this.grpUser = new System.Windows.Forms.GroupBox(); this.btnAdmin = new System.Windows.Forms.Button(); this.btnLogOut = new System.Windows.Forms.Button(); this.picPic = new System.Windows.Forms.PictureBox(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.createToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sAAOToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.monthlyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.deleteToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.label4 = new System.Windows.Forms.Label(); this.picBanner = new System.Windows.Forms.PictureBox(); this.pnlMain = new System.Windows.Forms.Panel(); this.label18 = new System.Windows.Forms.Label(); this.toolStrip = new System.Windows.Forms.ToolStrip(); this.toolBtnCreate = new System.Windows.Forms.ToolStripButton(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolBtnEdit = new System.Windows.Forms.ToolStripButton(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolBtnPrint = new System.Windows.Forms.ToolStripButton(); this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.toolBtnDelete = new System.Windows.Forms.ToolStripButton(); this.toolStripLabel4 = new System.Windows.Forms.ToolStripLabel(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripLabel5 = new System.Windows.Forms.ToolStripLabel(); this.dataGridMain = new System.Windows.Forms.DataGridView(); this.colBURNumber = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colOffice = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colPayee = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colDate = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colStaff = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.txtSearch = new System.Windows.Forms.TextBox(); this.pnlCreate = new System.Windows.Forms.Panel(); this.lblSign = new System.Windows.Forms.Label(); this.cmbSign = new System.Windows.Forms.ComboBox(); this.txtPayee = new System.Windows.Forms.TextBox(); this.txtBURNumber = new System.Windows.Forms.MaskedTextBox(); this.txtPR = new System.Windows.Forms.TextBox(); this.button5 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.grpParticulars = new System.Windows.Forms.GroupBox(); this.cmbCode = new System.Windows.Forms.ComboBox(); this.label11 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.btnEdit = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.numAmount = new System.Windows.Forms.NumericUpDown(); this.txtAcctName = new System.Windows.Forms.TextBox(); this.cmbClass = new System.Windows.Forms.ComboBox(); this.dataGridParticulars = new System.Windows.Forms.DataGridView(); this.colClassification = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colAcct_Code = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colAcct_Name = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colAmount = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.txtDescription = new System.Windows.Forms.TextBox(); this.cmbPayee = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.cmbOffice = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.dlgPrint = new System.Windows.Forms.PrintPreviewDialog(); this.pnlAdmin = new System.Windows.Forms.Panel(); this.tabAdmin = new System.Windows.Forms.TabControl(); this.tabPageUsers = new System.Windows.Forms.TabPage(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.button1 = new System.Windows.Forms.Button(); this.btnEditStaff = new System.Windows.Forms.Button(); this.btnAddStaff = new System.Windows.Forms.Button(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.picStaffPic = new System.Windows.Forms.PictureBox(); this.lblStaffType = new System.Windows.Forms.Label(); this.label30 = new System.Windows.Forms.Label(); this.lblStaffPosition = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.lblStaffName = new System.Windows.Forms.Label(); this.label19 = new System.Windows.Forms.Label(); this.lblStaffNumber = new System.Windows.Forms.Label(); this.label25 = new System.Windows.Forms.Label(); this.dGridUsers = new System.Windows.Forms.DataGridView(); this.staffNumber = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.staffName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.staffType = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.staffPosition = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.staffPic = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.tabOffices = new System.Windows.Forms.TabPage(); this.grpOfficeActions = new System.Windows.Forms.GroupBox(); this.btnDeleteOffice = new System.Windows.Forms.Button(); this.btnEditOffice = new System.Windows.Forms.Button(); this.btnAddOffice = new System.Windows.Forms.Button(); this.grpOfficeDetails = new System.Windows.Forms.GroupBox(); this.lblOfficeHeadPos = new System.Windows.Forms.Label(); this.label26 = new System.Windows.Forms.Label(); this.lblOfficeHead = new System.Windows.Forms.Label(); this.label24 = new System.Windows.Forms.Label(); this.lblOfficeName = new System.Windows.Forms.Label(); this.label22 = new System.Windows.Forms.Label(); this.dGridOffices = new System.Windows.Forms.DataGridView(); this.officeCode = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.officeNameFull = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.officeAbbr = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.officehead = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.officeheadPos = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.tabPayees = new System.Windows.Forms.TabPage(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.lblPayeeOffice = new System.Windows.Forms.Label(); this.label29 = new System.Windows.Forms.Label(); this.lblPayeePos = new System.Windows.Forms.Label(); this.label20 = new System.Windows.Forms.Label(); this.lblPayeeName = new System.Windows.Forms.Label(); this.label23 = new System.Windows.Forms.Label(); this.lblPayeeNumber = new System.Windows.Forms.Label(); this.label27 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.button2 = new System.Windows.Forms.Button(); this.btnEditPayee = new System.Windows.Forms.Button(); this.btnAddPayee = new System.Windows.Forms.Button(); this.dGridPayee = new System.Windows.Forms.DataGridView(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.tabAccounts = new System.Windows.Forms.TabPage(); this.grpAcctDetails = new System.Windows.Forms.GroupBox(); this.txtAcctCode = new System.Windows.Forms.TextBox(); this.btnDeleteAccount = new System.Windows.Forms.Button(); this.btnEditAccount = new System.Windows.Forms.Button(); this.cmbAcctClass = new System.Windows.Forms.ComboBox(); this.label17 = new System.Windows.Forms.Label(); this.txtEditAcctName = new System.Windows.Forms.TextBox(); this.label16 = new System.Windows.Forms.Label(); this.numAB = new System.Windows.Forms.NumericUpDown(); this.label10 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.lblAcctClass = new System.Windows.Forms.Label(); this.lblAcctName = new System.Windows.Forms.Label(); this.lblAcctCode = new System.Windows.Forms.Label(); this.dataGridAccounts = new System.Windows.Forms.DataGridView(); this.colAcctCode = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colAcctName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colAcctClass = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colAB = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.tabLogs = new System.Windows.Forms.TabPage(); this.txtLogs = new System.Windows.Forms.TextBox(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.grpUser.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picPic)).BeginInit(); this.contextMenuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picBanner)).BeginInit(); this.pnlMain.SuspendLayout(); this.toolStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridMain)).BeginInit(); this.pnlCreate.SuspendLayout(); this.grpParticulars.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numAmount)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridParticulars)).BeginInit(); this.pnlAdmin.SuspendLayout(); this.tabAdmin.SuspendLayout(); this.tabPageUsers.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picStaffPic)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dGridUsers)).BeginInit(); this.tabOffices.SuspendLayout(); this.grpOfficeActions.SuspendLayout(); this.grpOfficeDetails.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dGridOffices)).BeginInit(); this.tabPayees.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dGridPayee)).BeginInit(); this.tabAccounts.SuspendLayout(); this.grpAcctDetails.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numAB)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridAccounts)).BeginInit(); this.tabLogs.SuspendLayout(); this.SuspendLayout(); // // lblUser // this.lblUser.AutoSize = true; this.lblUser.ForeColor = System.Drawing.Color.White; this.lblUser.Location = new System.Drawing.Point(113, 28); this.lblUser.Name = "lblUser"; this.lblUser.Size = new System.Drawing.Size(88, 17); this.lblUser.TabIndex = 3; this.lblUser.Text = "PLDC Kirimaki"; // // lblPos // this.lblPos.AutoSize = true; this.lblPos.ForeColor = System.Drawing.Color.White; this.lblPos.Location = new System.Drawing.Point(113, 45); this.lblPos.Name = "lblPos"; this.lblPos.Size = new System.Drawing.Size(70, 17); this.lblPos.TabIndex = 4; this.lblPos.Text = "Challenger"; // // grpUser // this.grpUser.BackColor = System.Drawing.Color.Transparent; this.grpUser.Controls.Add(this.btnAdmin); this.grpUser.Controls.Add(this.btnLogOut); this.grpUser.Controls.Add(this.picPic); this.grpUser.Controls.Add(this.lblPos); this.grpUser.Controls.Add(this.lblUser); this.grpUser.Location = new System.Drawing.Point(890, 4); this.grpUser.Name = "grpUser"; this.grpUser.Size = new System.Drawing.Size(362, 125); this.grpUser.TabIndex = 5; this.grpUser.TabStop = false; // // btnAdmin // this.btnAdmin.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnAdmin.Location = new System.Drawing.Point(163, 80); this.btnAdmin.Name = "btnAdmin"; this.btnAdmin.Size = new System.Drawing.Size(102, 35); this.btnAdmin.TabIndex = 5; this.btnAdmin.Text = "Admin Panel"; this.btnAdmin.UseVisualStyleBackColor = true; this.btnAdmin.Visible = false; this.btnAdmin.Click += new System.EventHandler(this.btnAdmin_Click); // // btnLogOut // this.btnLogOut.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnLogOut.Location = new System.Drawing.Point(271, 80); this.btnLogOut.Name = "btnLogOut"; this.btnLogOut.Size = new System.Drawing.Size(75, 35); this.btnLogOut.TabIndex = 0; this.btnLogOut.Text = "Log out"; this.btnLogOut.UseVisualStyleBackColor = true; this.btnLogOut.Click += new System.EventHandler(this.btnLogOut_Click); // // picPic // this.picPic.Image = global::BUR_UI.Properties.Resources.ChallengerBadge; this.picPic.Location = new System.Drawing.Point(18, 24); this.picPic.Name = "picPic"; this.picPic.Size = new System.Drawing.Size(89, 86); this.picPic.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.picPic.TabIndex = 2; this.picPic.TabStop = false; // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.createToolStripMenuItem, this.editToolStripMenuItem, this.deleteToolStripMenuItem, this.printToolStripMenuItem, this.deleteToolStripMenuItem1}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(131, 114); // // createToolStripMenuItem // this.createToolStripMenuItem.Image = global::BUR_UI.Properties.Resources.Add_New2; this.createToolStripMenuItem.Name = "createToolStripMenuItem"; this.createToolStripMenuItem.Size = new System.Drawing.Size(130, 22); this.createToolStripMenuItem.Text = "Create"; this.createToolStripMenuItem.Click += new System.EventHandler(this.createToolStripMenuItem_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.sAAOToolStripMenuItem, this.monthlyToolStripMenuItem}); this.editToolStripMenuItem.Image = global::BUR_UI.Properties.Resources.generate; this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(130, 22); this.editToolStripMenuItem.Text = "Generate..."; this.editToolStripMenuItem.Click += new System.EventHandler(this.editToolStripMenuItem_Click); // // sAAOToolStripMenuItem // this.sAAOToolStripMenuItem.Name = "sAAOToolStripMenuItem"; this.sAAOToolStripMenuItem.Size = new System.Drawing.Size(119, 22); this.sAAOToolStripMenuItem.Text = "SAAO"; this.sAAOToolStripMenuItem.Click += new System.EventHandler(this.sAAOToolStripMenuItem_Click); // // monthlyToolStripMenuItem // this.monthlyToolStripMenuItem.Name = "monthlyToolStripMenuItem"; this.monthlyToolStripMenuItem.Size = new System.Drawing.Size(119, 22); this.monthlyToolStripMenuItem.Text = "Monthly"; this.monthlyToolStripMenuItem.Click += new System.EventHandler(this.monthlyToolStripMenuItem_Click); // // deleteToolStripMenuItem // this.deleteToolStripMenuItem.Image = global::BUR_UI.Properties.Resources.Data_Edit; this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem"; this.deleteToolStripMenuItem.Size = new System.Drawing.Size(130, 22); this.deleteToolStripMenuItem.Text = "Edit"; this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripMenuItem_Click); // // printToolStripMenuItem // this.printToolStripMenuItem.Image = global::BUR_UI.Properties.Resources.Printer; this.printToolStripMenuItem.Name = "printToolStripMenuItem"; this.printToolStripMenuItem.Size = new System.Drawing.Size(130, 22); this.printToolStripMenuItem.Text = "Print"; // // deleteToolStripMenuItem1 // this.deleteToolStripMenuItem1.Image = global::BUR_UI.Properties.Resources.Trash_can___03; this.deleteToolStripMenuItem1.Name = "deleteToolStripMenuItem1"; this.deleteToolStripMenuItem1.Size = new System.Drawing.Size(130, 22); this.deleteToolStripMenuItem1.Text = "Delete"; // // label4 // this.label4.AutoSize = true; this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Font = new System.Drawing.Font("Segoe UI Light", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.ForeColor = System.Drawing.Color.White; this.label4.Location = new System.Drawing.Point(842, 655); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(403, 17); this.label4.TabIndex = 10; this.label4.Text = "Copyright © 2016-2017 Seven-Fifty, Pamantasan ng Lungsod ng Maynila"; // // picBanner // this.picBanner.BackColor = System.Drawing.Color.Transparent; this.picBanner.Image = global::BUR_UI.Properties.Resources.header; this.picBanner.Location = new System.Drawing.Point(-3, 13); this.picBanner.Name = "picBanner"; this.picBanner.Size = new System.Drawing.Size(604, 125); this.picBanner.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.picBanner.TabIndex = 11; this.picBanner.TabStop = false; this.picBanner.Click += new System.EventHandler(this.picBanner_Click); // // pnlMain // this.pnlMain.BackColor = System.Drawing.Color.Transparent; this.pnlMain.Controls.Add(this.label18); this.pnlMain.Controls.Add(this.toolStrip); this.pnlMain.Controls.Add(this.dataGridMain); this.pnlMain.Controls.Add(this.txtSearch); this.pnlMain.Location = new System.Drawing.Point(13, 145); this.pnlMain.Name = "pnlMain"; this.pnlMain.Size = new System.Drawing.Size(1239, 507); this.pnlMain.TabIndex = 12; // // label18 // this.label18.AutoSize = true; this.label18.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label18.Location = new System.Drawing.Point(15, 11); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(47, 17); this.label18.TabIndex = 15; this.label18.Text = "Search"; // // toolStrip // this.toolStrip.AutoSize = false; this.toolStrip.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolBtnCreate, this.toolStripLabel1, this.toolStripSeparator1, this.toolBtnEdit, this.toolStripLabel2, this.toolStripSeparator2, this.toolBtnPrint, this.toolStripLabel3, this.toolStripSeparator3, this.toolBtnDelete, this.toolStripLabel4, this.toolStripSeparator4, this.toolStripButton1, this.toolStripLabel5}); this.toolStrip.Location = new System.Drawing.Point(806, 3); this.toolStrip.Name = "toolStrip"; this.toolStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; this.toolStrip.Size = new System.Drawing.Size(371, 27); this.toolStrip.Stretch = true; this.toolStrip.TabIndex = 14; this.toolStrip.Text = "toolStrip1"; // // toolBtnCreate // this.toolBtnCreate.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolBtnCreate.Image = global::BUR_UI.Properties.Resources.Add_New2; this.toolBtnCreate.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolBtnCreate.Name = "toolBtnCreate"; this.toolBtnCreate.Size = new System.Drawing.Size(23, 24); this.toolBtnCreate.Text = "toolStripButton1"; this.toolBtnCreate.Click += new System.EventHandler(this.toolBtnCreate_Click); // // toolStripLabel1 // this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(41, 24); this.toolStripLabel1.Text = "Create"; // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 27); // // toolBtnEdit // this.toolBtnEdit.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolBtnEdit.Image = global::BUR_UI.Properties.Resources.generate; this.toolBtnEdit.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolBtnEdit.Name = "toolBtnEdit"; this.toolBtnEdit.Size = new System.Drawing.Size(23, 24); this.toolBtnEdit.Text = "toolStripButton2"; this.toolBtnEdit.Click += new System.EventHandler(this.toolBtnEdit_Click); // // toolStripLabel2 // this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Size = new System.Drawing.Size(54, 24); this.toolStripLabel2.Text = "Generate"; // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 27); // // toolBtnPrint // this.toolBtnPrint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolBtnPrint.Image = global::BUR_UI.Properties.Resources.Data_Edit; this.toolBtnPrint.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolBtnPrint.Name = "toolBtnPrint"; this.toolBtnPrint.Size = new System.Drawing.Size(23, 24); this.toolBtnPrint.Text = "toolStripButton3"; this.toolBtnPrint.Click += new System.EventHandler(this.toolBtnPrint_Click); // // toolStripLabel3 // this.toolStripLabel3.Name = "toolStripLabel3"; this.toolStripLabel3.Size = new System.Drawing.Size(27, 24); this.toolStripLabel3.Text = "Edit"; // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(6, 27); // // toolBtnDelete // this.toolBtnDelete.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolBtnDelete.Image = global::BUR_UI.Properties.Resources.Printer; this.toolBtnDelete.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolBtnDelete.Name = "toolBtnDelete"; this.toolBtnDelete.Size = new System.Drawing.Size(23, 24); this.toolBtnDelete.Text = "toolStripButton4"; this.toolBtnDelete.Click += new System.EventHandler(this.toolBtnDelete_Click); // // toolStripLabel4 // this.toolStripLabel4.Name = "toolStripLabel4"; this.toolStripLabel4.Size = new System.Drawing.Size(32, 24); this.toolStripLabel4.Text = "Print"; // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(6, 27); // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = global::BUR_UI.Properties.Resources.Trash_can___03; this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 24); this.toolStripButton1.Text = "toolStripButton1"; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // toolStripLabel5 // this.toolStripLabel5.Name = "toolStripLabel5"; this.toolStripLabel5.Size = new System.Drawing.Size(40, 24); this.toolStripLabel5.Text = "Delete"; // // dataGridMain // this.dataGridMain.AllowUserToAddRows = false; this.dataGridMain.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dataGridMain.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridMain.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colBURNumber, this.colOffice, this.colPayee, this.colDate, this.colStaff}); this.dataGridMain.ContextMenuStrip = this.contextMenuStrip1; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle1.ForeColor = System.Drawing.Color.Black; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.dataGridMain.DefaultCellStyle = dataGridViewCellStyle1; this.dataGridMain.Location = new System.Drawing.Point(3, 36); this.dataGridMain.MultiSelect = false; this.dataGridMain.Name = "dataGridMain"; this.dataGridMain.RowHeadersWidth = 4; this.dataGridMain.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridMain.Size = new System.Drawing.Size(1233, 468); this.dataGridMain.TabIndex = 13; // // colBURNumber // this.colBURNumber.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colBURNumber.HeaderText = "BUR Number"; this.colBURNumber.Name = "colBURNumber"; this.colBURNumber.ReadOnly = true; // // colOffice // this.colOffice.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colOffice.HeaderText = "Office"; this.colOffice.Name = "colOffice"; this.colOffice.ReadOnly = true; // // colPayee // this.colPayee.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colPayee.HeaderText = "Payee"; this.colPayee.Name = "colPayee"; this.colPayee.ReadOnly = true; // // colDate // this.colDate.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colDate.HeaderText = "Date"; this.colDate.Name = "colDate"; this.colDate.ReadOnly = true; // // colStaff // this.colStaff.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colStaff.HeaderText = "Staff"; this.colStaff.Name = "colStaff"; this.colStaff.ReadOnly = true; // // txtSearch // this.txtSearch.Location = new System.Drawing.Point(67, 8); this.txtSearch.Name = "txtSearch"; this.txtSearch.Size = new System.Drawing.Size(292, 25); this.txtSearch.TabIndex = 10; this.txtSearch.TextChanged += new System.EventHandler(this.txtSearch_TextChanged); // // pnlCreate // this.pnlCreate.BackColor = System.Drawing.Color.Transparent; this.pnlCreate.Controls.Add(this.lblSign); this.pnlCreate.Controls.Add(this.cmbSign); this.pnlCreate.Controls.Add(this.txtPayee); this.pnlCreate.Controls.Add(this.txtBURNumber); this.pnlCreate.Controls.Add(this.txtPR); this.pnlCreate.Controls.Add(this.button5); this.pnlCreate.Controls.Add(this.button4); this.pnlCreate.Controls.Add(this.grpParticulars); this.pnlCreate.Controls.Add(this.label7); this.pnlCreate.Controls.Add(this.label6); this.pnlCreate.Controls.Add(this.txtDescription); this.pnlCreate.Controls.Add(this.cmbPayee); this.pnlCreate.Controls.Add(this.label3); this.pnlCreate.Controls.Add(this.cmbOffice); this.pnlCreate.Controls.Add(this.label5); this.pnlCreate.Controls.Add(this.label2); this.pnlCreate.Controls.Add(this.label1); this.pnlCreate.Location = new System.Drawing.Point(12, 144); this.pnlCreate.Name = "pnlCreate"; this.pnlCreate.Size = new System.Drawing.Size(1240, 508); this.pnlCreate.TabIndex = 15; this.pnlCreate.Visible = false; this.pnlCreate.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlCreate_Paint); // // lblSign // this.lblSign.AutoSize = true; this.lblSign.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblSign.ForeColor = System.Drawing.Color.White; this.lblSign.Location = new System.Drawing.Point(44, 370); this.lblSign.Name = "lblSign"; this.lblSign.Size = new System.Drawing.Size(122, 21); this.lblSign.TabIndex = 19; this.lblSign.Text = "Signatory Office"; this.lblSign.Visible = false; // // cmbSign // this.cmbSign.DropDownHeight = 210; this.cmbSign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbSign.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmbSign.FormattingEnabled = true; this.cmbSign.IntegralHeight = false; this.cmbSign.Location = new System.Drawing.Point(193, 367); this.cmbSign.Name = "cmbSign"; this.cmbSign.Size = new System.Drawing.Size(330, 29); this.cmbSign.TabIndex = 18; this.cmbSign.Visible = false; // // txtPayee // this.txtPayee.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtPayee.Location = new System.Drawing.Point(193, 160); this.txtPayee.Name = "txtPayee"; this.txtPayee.Size = new System.Drawing.Size(330, 29); this.txtPayee.TabIndex = 17; this.txtPayee.Visible = false; // // txtBURNumber // this.txtBURNumber.Location = new System.Drawing.Point(193, 85); this.txtBURNumber.Mask = "1\\01-0000-00-0000"; this.txtBURNumber.Name = "txtBURNumber"; this.txtBURNumber.Size = new System.Drawing.Size(330, 25); this.txtBURNumber.TabIndex = 16; // // txtPR // this.txtPR.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtPR.Location = new System.Drawing.Point(193, 310); this.txtPR.Name = "txtPR"; this.txtPR.Size = new System.Drawing.Size(330, 29); this.txtPR.TabIndex = 15; // // button5 // this.button5.BackColor = System.Drawing.SystemColors.Control; this.button5.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button5.Location = new System.Drawing.Point(992, 434); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(103, 43); this.button5.TabIndex = 14; this.button5.Text = "Cancel"; this.button5.UseVisualStyleBackColor = false; this.button5.Click += new System.EventHandler(this.button5_Click); // // button4 // this.button4.BackColor = System.Drawing.SystemColors.Control; this.button4.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button4.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button4.Location = new System.Drawing.Point(1101, 434); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(117, 43); this.button4.TabIndex = 13; this.button4.Text = "Create"; this.button4.UseVisualStyleBackColor = false; this.button4.Click += new System.EventHandler(this.button4_Click); // // grpParticulars // this.grpParticulars.Controls.Add(this.cmbCode); this.grpParticulars.Controls.Add(this.label11); this.grpParticulars.Controls.Add(this.label9); this.grpParticulars.Controls.Add(this.label8); this.grpParticulars.Controls.Add(this.btnEdit); this.grpParticulars.Controls.Add(this.btnDelete); this.grpParticulars.Controls.Add(this.btnAdd); this.grpParticulars.Controls.Add(this.numAmount); this.grpParticulars.Controls.Add(this.txtAcctName); this.grpParticulars.Controls.Add(this.cmbClass); this.grpParticulars.Controls.Add(this.dataGridParticulars); this.grpParticulars.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.grpParticulars.ForeColor = System.Drawing.Color.White; this.grpParticulars.Location = new System.Drawing.Point(578, 52); this.grpParticulars.Name = "grpParticulars"; this.grpParticulars.Size = new System.Drawing.Size(646, 287); this.grpParticulars.TabIndex = 12; this.grpParticulars.TabStop = false; this.grpParticulars.Text = "Particulars"; // // cmbCode // this.cmbCode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbCode.Enabled = false; this.cmbCode.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmbCode.FormattingEnabled = true; this.cmbCode.Location = new System.Drawing.Point(157, 42); this.cmbCode.Name = "cmbCode"; this.cmbCode.Size = new System.Drawing.Size(317, 29); this.cmbCode.TabIndex = 7; this.cmbCode.SelectedIndexChanged += new System.EventHandler(this.cmbCode_SelectedIndexChanged); // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.Location = new System.Drawing.Point(477, 22); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(53, 17); this.label11.TabIndex = 16; this.label11.Text = "Amount"; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.Location = new System.Drawing.Point(153, 22); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(39, 17); this.label9.TabIndex = 14; this.label9.Text = "Code"; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.Location = new System.Drawing.Point(3, 22); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(83, 17); this.label8.TabIndex = 13; this.label8.Text = "Classification"; // // btnEdit // this.btnEdit.BackColor = System.Drawing.SystemColors.Control; this.btnEdit.Enabled = false; this.btnEdit.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.btnEdit.Location = new System.Drawing.Point(537, 126); this.btnEdit.Name = "btnEdit"; this.btnEdit.Size = new System.Drawing.Size(103, 35); this.btnEdit.TabIndex = 12; this.btnEdit.Text = "Edit"; this.btnEdit.UseVisualStyleBackColor = false; this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click); // // btnDelete // this.btnDelete.BackColor = System.Drawing.SystemColors.Control; this.btnDelete.Enabled = false; this.btnDelete.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.btnDelete.Location = new System.Drawing.Point(537, 166); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(103, 35); this.btnDelete.TabIndex = 11; this.btnDelete.Text = "Delete"; this.btnDelete.UseVisualStyleBackColor = false; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // btnAdd // this.btnAdd.BackColor = System.Drawing.SystemColors.Control; this.btnAdd.Enabled = false; this.btnAdd.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.btnAdd.Location = new System.Drawing.Point(537, 86); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(103, 35); this.btnAdd.TabIndex = 10; this.btnAdd.Text = "Add"; this.btnAdd.UseVisualStyleBackColor = false; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // numAmount // this.numAmount.DecimalPlaces = 2; this.numAmount.Location = new System.Drawing.Point(480, 42); this.numAmount.Maximum = new decimal(new int[] { 999999999, 0, 0, 0}); this.numAmount.Name = "numAmount"; this.numAmount.Size = new System.Drawing.Size(160, 29); this.numAmount.TabIndex = 9; this.numAmount.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtAcctName // this.txtAcctName.Cursor = System.Windows.Forms.Cursors.No; this.txtAcctName.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtAcctName.Location = new System.Drawing.Point(229, 42); this.txtAcctName.Name = "txtAcctName"; this.txtAcctName.ReadOnly = true; this.txtAcctName.Size = new System.Drawing.Size(245, 29); this.txtAcctName.TabIndex = 8; this.txtAcctName.TextChanged += new System.EventHandler(this.txtAcctName_TextChanged); // // cmbClass // this.cmbClass.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbClass.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmbClass.FormattingEnabled = true; this.cmbClass.Location = new System.Drawing.Point(6, 42); this.cmbClass.Name = "cmbClass"; this.cmbClass.Size = new System.Drawing.Size(145, 29); this.cmbClass.TabIndex = 6; this.cmbClass.SelectedIndexChanged += new System.EventHandler(this.cmbClass_SelectedIndexChanged); // // dataGridParticulars // this.dataGridParticulars.AllowUserToAddRows = false; this.dataGridParticulars.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridParticulars.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colClassification, this.colAcct_Code, this.colAcct_Name, this.colAmount}); this.dataGridParticulars.Location = new System.Drawing.Point(6, 76); this.dataGridParticulars.Name = "dataGridParticulars"; this.dataGridParticulars.ReadOnly = true; this.dataGridParticulars.RowHeadersWidth = 4; this.dataGridParticulars.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridParticulars.Size = new System.Drawing.Size(525, 205); this.dataGridParticulars.TabIndex = 0; this.dataGridParticulars.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridParticulars_CellContentClick); this.dataGridParticulars.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridParticulars_CellValueChanged); this.dataGridParticulars.RowsRemoved += new System.Windows.Forms.DataGridViewRowsRemovedEventHandler(this.dataGridParticulars_RowsRemoved); this.dataGridParticulars.SelectionChanged += new System.EventHandler(this.dataGridParticulars_SelectionChanged); // // colClassification // this.colClassification.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colClassification.FillWeight = 75F; this.colClassification.HeaderText = "Classification"; this.colClassification.Name = "colClassification"; this.colClassification.ReadOnly = true; // // colAcct_Code // this.colAcct_Code.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colAcct_Code.FillWeight = 50F; this.colAcct_Code.HeaderText = "Account Code"; this.colAcct_Code.Name = "colAcct_Code"; this.colAcct_Code.ReadOnly = true; // // colAcct_Name // this.colAcct_Name.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colAcct_Name.HeaderText = "Account Name"; this.colAcct_Name.Name = "colAcct_Name"; this.colAcct_Name.ReadOnly = true; // // colAmount // this.colAmount.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colAmount.FillWeight = 75F; this.colAmount.HeaderText = "Amount"; this.colAmount.Name = "colAmount"; this.colAmount.ReadOnly = true; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.ForeColor = System.Drawing.Color.White; this.label7.Location = new System.Drawing.Point(77, 313); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(91, 21); this.label7.TabIndex = 11; this.label7.Text = "PR Number"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.ForeColor = System.Drawing.Color.White; this.label6.Location = new System.Drawing.Point(77, 203); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(89, 21); this.label6.TabIndex = 9; this.label6.Text = "Description"; // // txtDescription // this.txtDescription.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtDescription.Location = new System.Drawing.Point(193, 200); this.txtDescription.Multiline = true; this.txtDescription.Name = "txtDescription"; this.txtDescription.Size = new System.Drawing.Size(330, 100); this.txtDescription.TabIndex = 8; this.txtDescription.TextChanged += new System.EventHandler(this.txtDescription_TextChanged); // // cmbPayee // this.cmbPayee.DropDownHeight = 210; this.cmbPayee.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbPayee.Enabled = false; this.cmbPayee.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmbPayee.FormattingEnabled = true; this.cmbPayee.IntegralHeight = false; this.cmbPayee.Location = new System.Drawing.Point(193, 160); this.cmbPayee.Name = "cmbPayee"; this.cmbPayee.Size = new System.Drawing.Size(330, 29); this.cmbPayee.TabIndex = 7; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.ForeColor = System.Drawing.Color.White; this.label3.Location = new System.Drawing.Point(116, 163); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(50, 21); this.label3.TabIndex = 6; this.label3.Text = "Payee"; // // cmbOffice // this.cmbOffice.DropDownHeight = 210; this.cmbOffice.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbOffice.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmbOffice.FormattingEnabled = true; this.cmbOffice.IntegralHeight = false; this.cmbOffice.Location = new System.Drawing.Point(193, 120); this.cmbOffice.Name = "cmbOffice"; this.cmbOffice.Size = new System.Drawing.Size(330, 29); this.cmbOffice.TabIndex = 5; this.cmbOffice.SelectedIndexChanged += new System.EventHandler(this.cmbOffice_SelectedIndexChanged); // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.ForeColor = System.Drawing.Color.White; this.label5.Location = new System.Drawing.Point(115, 123); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(51, 21); this.label5.TabIndex = 3; this.label5.Text = "Office"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(64, 85); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(102, 21); this.label2.TabIndex = 1; this.label2.Text = "BUR Number"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Segoe UI Semibold", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(24, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(124, 47); this.label1.TabIndex = 0; this.label1.Text = "Create"; // // dlgPrint // this.dlgPrint.AutoScrollMargin = new System.Drawing.Size(0, 0); this.dlgPrint.AutoScrollMinSize = new System.Drawing.Size(0, 0); this.dlgPrint.ClientSize = new System.Drawing.Size(400, 300); this.dlgPrint.Enabled = true; this.dlgPrint.Icon = ((System.Drawing.Icon)(resources.GetObject("dlgPrint.Icon"))); this.dlgPrint.Name = "dlgPrint"; this.dlgPrint.Visible = false; this.dlgPrint.Load += new System.EventHandler(this.dlgPrint_Load); // // pnlAdmin // this.pnlAdmin.BackColor = System.Drawing.Color.Transparent; this.pnlAdmin.Controls.Add(this.tabAdmin); this.pnlAdmin.Location = new System.Drawing.Point(12, 147); this.pnlAdmin.Name = "pnlAdmin"; this.pnlAdmin.Size = new System.Drawing.Size(1240, 505); this.pnlAdmin.TabIndex = 16; this.pnlAdmin.Visible = false; // // tabAdmin // this.tabAdmin.Controls.Add(this.tabPageUsers); this.tabAdmin.Controls.Add(this.tabOffices); this.tabAdmin.Controls.Add(this.tabPayees); this.tabAdmin.Controls.Add(this.tabAccounts); this.tabAdmin.Controls.Add(this.tabLogs); this.tabAdmin.Location = new System.Drawing.Point(13, 6); this.tabAdmin.Name = "tabAdmin"; this.tabAdmin.SelectedIndex = 0; this.tabAdmin.Size = new System.Drawing.Size(1224, 496); this.tabAdmin.TabIndex = 0; // // tabPageUsers // this.tabPageUsers.BackColor = System.Drawing.SystemColors.ControlDarkDark; this.tabPageUsers.Controls.Add(this.groupBox3); this.tabPageUsers.Controls.Add(this.groupBox4); this.tabPageUsers.Controls.Add(this.dGridUsers); this.tabPageUsers.Location = new System.Drawing.Point(4, 26); this.tabPageUsers.Name = "tabPageUsers"; this.tabPageUsers.Padding = new System.Windows.Forms.Padding(3); this.tabPageUsers.Size = new System.Drawing.Size(1216, 466); this.tabPageUsers.TabIndex = 0; this.tabPageUsers.Text = "Users"; // // groupBox3 // this.groupBox3.Controls.Add(this.button1); this.groupBox3.Controls.Add(this.btnEditStaff); this.groupBox3.Controls.Add(this.btnAddStaff); this.groupBox3.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.groupBox3.Location = new System.Drawing.Point(861, 16); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(332, 121); this.groupBox3.TabIndex = 5; this.groupBox3.TabStop = false; this.groupBox3.Text = "Staff Actions"; // // button1 // this.button1.Enabled = false; this.button1.ForeColor = System.Drawing.SystemColors.ControlText; this.button1.Location = new System.Drawing.Point(180, 48); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(100, 30); this.button1.TabIndex = 2; this.button1.Text = "Delete Staff"; this.button1.UseVisualStyleBackColor = true; this.button1.Visible = false; // // btnEditStaff // this.btnEditStaff.Enabled = false; this.btnEditStaff.ForeColor = System.Drawing.SystemColors.ControlText; this.btnEditStaff.Location = new System.Drawing.Point(74, 64); this.btnEditStaff.Name = "btnEditStaff"; this.btnEditStaff.Size = new System.Drawing.Size(100, 30); this.btnEditStaff.TabIndex = 1; this.btnEditStaff.Text = "Edit Staff"; this.btnEditStaff.UseVisualStyleBackColor = true; this.btnEditStaff.Click += new System.EventHandler(this.btnEditStaff_Click); // // btnAddStaff // this.btnAddStaff.ForeColor = System.Drawing.SystemColors.ControlText; this.btnAddStaff.Location = new System.Drawing.Point(74, 28); this.btnAddStaff.Name = "btnAddStaff"; this.btnAddStaff.Size = new System.Drawing.Size(100, 30); this.btnAddStaff.TabIndex = 0; this.btnAddStaff.Text = "Add Staff"; this.btnAddStaff.UseVisualStyleBackColor = true; this.btnAddStaff.Click += new System.EventHandler(this.btnAddStaff_Click); // // groupBox4 // this.groupBox4.Controls.Add(this.picStaffPic); this.groupBox4.Controls.Add(this.lblStaffType); this.groupBox4.Controls.Add(this.label30); this.groupBox4.Controls.Add(this.lblStaffPosition); this.groupBox4.Controls.Add(this.label14); this.groupBox4.Controls.Add(this.lblStaffName); this.groupBox4.Controls.Add(this.label19); this.groupBox4.Controls.Add(this.lblStaffNumber); this.groupBox4.Controls.Add(this.label25); this.groupBox4.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.groupBox4.Location = new System.Drawing.Point(15, 16); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(840, 121); this.groupBox4.TabIndex = 4; this.groupBox4.TabStop = false; this.groupBox4.Text = "Staff Details"; // // picStaffPic // this.picStaffPic.Location = new System.Drawing.Point(729, 9); this.picStaffPic.Name = "picStaffPic"; this.picStaffPic.Size = new System.Drawing.Size(111, 111); this.picStaffPic.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.picStaffPic.TabIndex = 10; this.picStaffPic.TabStop = false; // // lblStaffType // this.lblStaffType.AutoSize = true; this.lblStaffType.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblStaffType.Location = new System.Drawing.Point(105, 18); this.lblStaffType.Name = "lblStaffType"; this.lblStaffType.Size = new System.Drawing.Size(154, 21); this.lblStaffType.TabIndex = 9; this.lblStaffType.Text = "(No staff selected.)"; this.lblStaffType.Click += new System.EventHandler(this.label28_Click); // // label30 // this.label30.AutoSize = true; this.label30.Location = new System.Drawing.Point(13, 21); this.label30.Name = "label30"; this.label30.Size = new System.Drawing.Size(65, 17); this.label30.TabIndex = 8; this.label30.Text = "Staff Type"; // // lblStaffPosition // this.lblStaffPosition.AutoSize = true; this.lblStaffPosition.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblStaffPosition.Location = new System.Drawing.Point(215, 92); this.lblStaffPosition.Name = "lblStaffPosition"; this.lblStaffPosition.Size = new System.Drawing.Size(120, 17); this.lblStaffPosition.TabIndex = 7; this.lblStaffPosition.Text = "(No staff selected.)"; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(13, 92); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(84, 17); this.label14.TabIndex = 6; this.label14.Text = "Staff Position"; // // lblStaffName // this.lblStaffName.AutoSize = true; this.lblStaffName.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblStaffName.Location = new System.Drawing.Point(215, 71); this.lblStaffName.Name = "lblStaffName"; this.lblStaffName.Size = new System.Drawing.Size(120, 17); this.lblStaffName.TabIndex = 5; this.lblStaffName.Text = "(No staff selected.)"; // // label19 // this.label19.AutoSize = true; this.label19.Location = new System.Drawing.Point(13, 71); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(73, 17); this.label19.TabIndex = 4; this.label19.Text = "Staff Name"; // // lblStaffNumber // this.lblStaffNumber.AutoSize = true; this.lblStaffNumber.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblStaffNumber.Location = new System.Drawing.Point(215, 48); this.lblStaffNumber.Name = "lblStaffNumber"; this.lblStaffNumber.Size = new System.Drawing.Size(120, 17); this.lblStaffNumber.TabIndex = 3; this.lblStaffNumber.Text = "(No staff selected.)"; // // label25 // this.label25.AutoSize = true; this.label25.Location = new System.Drawing.Point(13, 48); this.label25.Name = "label25"; this.label25.Size = new System.Drawing.Size(86, 17); this.label25.TabIndex = 2; this.label25.Text = "Staff Number"; // // dGridUsers // this.dGridUsers.AllowUserToAddRows = false; this.dGridUsers.AllowUserToDeleteRows = false; this.dGridUsers.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dGridUsers.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.staffNumber, this.staffName, this.staffType, this.staffPosition, this.staffPic}); this.dGridUsers.Location = new System.Drawing.Point(15, 151); this.dGridUsers.MultiSelect = false; this.dGridUsers.Name = "dGridUsers"; this.dGridUsers.ReadOnly = true; this.dGridUsers.RowHeadersWidth = 4; this.dGridUsers.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dGridUsers.Size = new System.Drawing.Size(1187, 300); this.dGridUsers.TabIndex = 3; this.dGridUsers.SelectionChanged += new System.EventHandler(this.dGridUsers_SelectionChanged); // // staffNumber // this.staffNumber.HeaderText = "Staff Number"; this.staffNumber.Name = "staffNumber"; this.staffNumber.ReadOnly = true; this.staffNumber.Visible = false; // // staffName // this.staffName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.staffName.FillWeight = 40F; this.staffName.HeaderText = "Staff Name"; this.staffName.Name = "staffName"; this.staffName.ReadOnly = true; // // staffType // this.staffType.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.staffType.FillWeight = 30F; this.staffType.HeaderText = "Staff Type"; this.staffType.Name = "staffType"; this.staffType.ReadOnly = true; // // staffPosition // this.staffPosition.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.staffPosition.FillWeight = 30F; this.staffPosition.HeaderText = "Position"; this.staffPosition.Name = "staffPosition"; this.staffPosition.ReadOnly = true; // // staffPic // this.staffPic.HeaderText = "Picture URI"; this.staffPic.Name = "staffPic"; this.staffPic.ReadOnly = true; this.staffPic.Visible = false; // // tabOffices // this.tabOffices.BackColor = System.Drawing.Color.DimGray; this.tabOffices.Controls.Add(this.grpOfficeActions); this.tabOffices.Controls.Add(this.grpOfficeDetails); this.tabOffices.Controls.Add(this.dGridOffices); this.tabOffices.Location = new System.Drawing.Point(4, 22); this.tabOffices.Name = "tabOffices"; this.tabOffices.Size = new System.Drawing.Size(1216, 470); this.tabOffices.TabIndex = 3; this.tabOffices.Text = "Offices"; // // grpOfficeActions // this.grpOfficeActions.Controls.Add(this.btnDeleteOffice); this.grpOfficeActions.Controls.Add(this.btnEditOffice); this.grpOfficeActions.Controls.Add(this.btnAddOffice); this.grpOfficeActions.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.grpOfficeActions.Location = new System.Drawing.Point(861, 17); this.grpOfficeActions.Name = "grpOfficeActions"; this.grpOfficeActions.Size = new System.Drawing.Size(332, 121); this.grpOfficeActions.TabIndex = 2; this.grpOfficeActions.TabStop = false; this.grpOfficeActions.Text = "Office Actions"; // // btnDeleteOffice // this.btnDeleteOffice.Enabled = false; this.btnDeleteOffice.ForeColor = System.Drawing.SystemColors.ControlText; this.btnDeleteOffice.Location = new System.Drawing.Point(180, 48); this.btnDeleteOffice.Name = "btnDeleteOffice"; this.btnDeleteOffice.Size = new System.Drawing.Size(100, 30); this.btnDeleteOffice.TabIndex = 2; this.btnDeleteOffice.Text = "Delete Office"; this.btnDeleteOffice.UseVisualStyleBackColor = true; this.btnDeleteOffice.Visible = false; this.btnDeleteOffice.Click += new System.EventHandler(this.btnDeleteOffice_Click); // // btnEditOffice // this.btnEditOffice.Enabled = false; this.btnEditOffice.ForeColor = System.Drawing.SystemColors.ControlText; this.btnEditOffice.Location = new System.Drawing.Point(74, 64); this.btnEditOffice.Name = "btnEditOffice"; this.btnEditOffice.Size = new System.Drawing.Size(100, 30); this.btnEditOffice.TabIndex = 1; this.btnEditOffice.Text = "Edit Office"; this.btnEditOffice.UseVisualStyleBackColor = true; this.btnEditOffice.Click += new System.EventHandler(this.btnEditOffice_Click); // // btnAddOffice // this.btnAddOffice.ForeColor = System.Drawing.SystemColors.ControlText; this.btnAddOffice.Location = new System.Drawing.Point(74, 28); this.btnAddOffice.Name = "btnAddOffice"; this.btnAddOffice.Size = new System.Drawing.Size(100, 30); this.btnAddOffice.TabIndex = 0; this.btnAddOffice.Text = "Add Office"; this.btnAddOffice.UseVisualStyleBackColor = true; this.btnAddOffice.Click += new System.EventHandler(this.btnAddOffice_Click); // // grpOfficeDetails // this.grpOfficeDetails.Controls.Add(this.lblOfficeHeadPos); this.grpOfficeDetails.Controls.Add(this.label26); this.grpOfficeDetails.Controls.Add(this.lblOfficeHead); this.grpOfficeDetails.Controls.Add(this.label24); this.grpOfficeDetails.Controls.Add(this.lblOfficeName); this.grpOfficeDetails.Controls.Add(this.label22); this.grpOfficeDetails.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.grpOfficeDetails.Location = new System.Drawing.Point(15, 17); this.grpOfficeDetails.Name = "grpOfficeDetails"; this.grpOfficeDetails.Size = new System.Drawing.Size(840, 121); this.grpOfficeDetails.TabIndex = 1; this.grpOfficeDetails.TabStop = false; this.grpOfficeDetails.Text = "Office Details"; // // lblOfficeHeadPos // this.lblOfficeHeadPos.AutoSize = true; this.lblOfficeHeadPos.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblOfficeHeadPos.Location = new System.Drawing.Point(215, 79); this.lblOfficeHeadPos.Name = "lblOfficeHeadPos"; this.lblOfficeHeadPos.Size = new System.Drawing.Size(126, 17); this.lblOfficeHeadPos.TabIndex = 7; this.lblOfficeHeadPos.Text = "(No office selected.)"; // // label26 // this.label26.AutoSize = true; this.label26.Location = new System.Drawing.Point(13, 79); this.label26.Name = "label26"; this.label26.Size = new System.Drawing.Size(127, 17); this.label26.TabIndex = 6; this.label26.Text = "Office Head Position"; // // lblOfficeHead // this.lblOfficeHead.AutoSize = true; this.lblOfficeHead.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblOfficeHead.Location = new System.Drawing.Point(215, 58); this.lblOfficeHead.Name = "lblOfficeHead"; this.lblOfficeHead.Size = new System.Drawing.Size(126, 17); this.lblOfficeHead.TabIndex = 5; this.lblOfficeHead.Text = "(No office selected.)"; // // label24 // this.label24.AutoSize = true; this.label24.Location = new System.Drawing.Point(13, 58); this.label24.Name = "label24"; this.label24.Size = new System.Drawing.Size(77, 17); this.label24.TabIndex = 4; this.label24.Text = "Office Head"; // // lblOfficeName // this.lblOfficeName.AutoSize = true; this.lblOfficeName.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblOfficeName.Location = new System.Drawing.Point(215, 35); this.lblOfficeName.Name = "lblOfficeName"; this.lblOfficeName.Size = new System.Drawing.Size(126, 17); this.lblOfficeName.TabIndex = 3; this.lblOfficeName.Text = "(No office selected.)"; // // label22 // this.label22.AutoSize = true; this.label22.Location = new System.Drawing.Point(13, 35); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(81, 17); this.label22.TabIndex = 2; this.label22.Text = "Office Name"; // // dGridOffices // this.dGridOffices.AllowUserToAddRows = false; this.dGridOffices.AllowUserToDeleteRows = false; this.dGridOffices.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dGridOffices.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.officeCode, this.officeNameFull, this.officeAbbr, this.officehead, this.officeheadPos}); this.dGridOffices.Location = new System.Drawing.Point(15, 152); this.dGridOffices.MultiSelect = false; this.dGridOffices.Name = "dGridOffices"; this.dGridOffices.ReadOnly = true; this.dGridOffices.RowHeadersWidth = 4; this.dGridOffices.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dGridOffices.Size = new System.Drawing.Size(1187, 300); this.dGridOffices.TabIndex = 0; this.dGridOffices.SelectionChanged += new System.EventHandler(this.dGridOffices_SelectionChanged); // // officeCode // this.officeCode.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.officeCode.FillWeight = 10F; this.officeCode.HeaderText = "Office Code"; this.officeCode.Name = "officeCode"; this.officeCode.ReadOnly = true; // // officeNameFull // this.officeNameFull.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.officeNameFull.FillWeight = 30F; this.officeNameFull.HeaderText = "Office Name"; this.officeNameFull.Name = "officeNameFull"; this.officeNameFull.ReadOnly = true; // // officeAbbr // this.officeAbbr.HeaderText = "Office Name (Short)"; this.officeAbbr.Name = "officeAbbr"; this.officeAbbr.ReadOnly = true; this.officeAbbr.Visible = false; // // officehead // this.officehead.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.officehead.FillWeight = 30F; this.officehead.HeaderText = "Office Head"; this.officehead.Name = "officehead"; this.officehead.ReadOnly = true; // // officeheadPos // this.officeheadPos.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.officeheadPos.FillWeight = 30F; this.officeheadPos.HeaderText = "Office Head Position"; this.officeheadPos.Name = "officeheadPos"; this.officeheadPos.ReadOnly = true; // // tabPayees // this.tabPayees.BackColor = System.Drawing.Color.DimGray; this.tabPayees.Controls.Add(this.groupBox2); this.tabPayees.Controls.Add(this.groupBox1); this.tabPayees.Controls.Add(this.dGridPayee); this.tabPayees.Location = new System.Drawing.Point(4, 22); this.tabPayees.Name = "tabPayees"; this.tabPayees.Size = new System.Drawing.Size(1216, 470); this.tabPayees.TabIndex = 4; this.tabPayees.Text = "Payees"; // // groupBox2 // this.groupBox2.Controls.Add(this.lblPayeeOffice); this.groupBox2.Controls.Add(this.label29); this.groupBox2.Controls.Add(this.lblPayeePos); this.groupBox2.Controls.Add(this.label20); this.groupBox2.Controls.Add(this.lblPayeeName); this.groupBox2.Controls.Add(this.label23); this.groupBox2.Controls.Add(this.lblPayeeNumber); this.groupBox2.Controls.Add(this.label27); this.groupBox2.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.groupBox2.Location = new System.Drawing.Point(15, 17); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(840, 121); this.groupBox2.TabIndex = 5; this.groupBox2.TabStop = false; this.groupBox2.Text = "Payee Details"; // // lblPayeeOffice // this.lblPayeeOffice.AutoSize = true; this.lblPayeeOffice.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblPayeeOffice.Location = new System.Drawing.Point(215, 86); this.lblPayeeOffice.Name = "lblPayeeOffice"; this.lblPayeeOffice.Size = new System.Drawing.Size(131, 17); this.lblPayeeOffice.TabIndex = 9; this.lblPayeeOffice.Text = "(No Payee Selected.)"; // // label29 // this.label29.AutoSize = true; this.label29.Location = new System.Drawing.Point(13, 86); this.label29.Name = "label29"; this.label29.Size = new System.Drawing.Size(42, 17); this.label29.TabIndex = 8; this.label29.Text = "Office"; // // lblPayeePos // this.lblPayeePos.AutoSize = true; this.lblPayeePos.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblPayeePos.Location = new System.Drawing.Point(215, 64); this.lblPayeePos.Name = "lblPayeePos"; this.lblPayeePos.Size = new System.Drawing.Size(131, 17); this.lblPayeePos.TabIndex = 7; this.lblPayeePos.Text = "(No Payee Selected.)"; // // label20 // this.label20.AutoSize = true; this.label20.Location = new System.Drawing.Point(13, 64); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(115, 17); this.label20.TabIndex = 6; this.label20.Text = "Employee Position"; // // lblPayeeName // this.lblPayeeName.AutoSize = true; this.lblPayeeName.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblPayeeName.Location = new System.Drawing.Point(215, 43); this.lblPayeeName.Name = "lblPayeeName"; this.lblPayeeName.Size = new System.Drawing.Size(131, 17); this.lblPayeeName.TabIndex = 5; this.lblPayeeName.Text = "(No Payee Selected.)"; // // label23 // this.label23.AutoSize = true; this.label23.Location = new System.Drawing.Point(13, 43); this.label23.Name = "label23"; this.label23.Size = new System.Drawing.Size(104, 17); this.label23.TabIndex = 4; this.label23.Text = "Employee Name"; // // lblPayeeNumber // this.lblPayeeNumber.AutoSize = true; this.lblPayeeNumber.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblPayeeNumber.Location = new System.Drawing.Point(215, 20); this.lblPayeeNumber.Name = "lblPayeeNumber"; this.lblPayeeNumber.Size = new System.Drawing.Size(131, 17); this.lblPayeeNumber.TabIndex = 3; this.lblPayeeNumber.Text = "(No Payee Selected.)"; // // label27 // this.label27.AutoSize = true; this.label27.Location = new System.Drawing.Point(13, 20); this.label27.Name = "label27"; this.label27.Size = new System.Drawing.Size(117, 17); this.label27.TabIndex = 2; this.label27.Text = "Employee Number"; // // groupBox1 // this.groupBox1.Controls.Add(this.button2); this.groupBox1.Controls.Add(this.btnEditPayee); this.groupBox1.Controls.Add(this.btnAddPayee); this.groupBox1.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.groupBox1.Location = new System.Drawing.Point(861, 16); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(332, 121); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; this.groupBox1.Text = "Payee Actions"; // // button2 // this.button2.Enabled = false; this.button2.ForeColor = System.Drawing.SystemColors.ControlText; this.button2.Location = new System.Drawing.Point(180, 48); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(100, 30); this.button2.TabIndex = 2; this.button2.Text = "Delete Office"; this.button2.UseVisualStyleBackColor = true; this.button2.Visible = false; // // btnEditPayee // this.btnEditPayee.Enabled = false; this.btnEditPayee.ForeColor = System.Drawing.SystemColors.ControlText; this.btnEditPayee.Location = new System.Drawing.Point(74, 64); this.btnEditPayee.Name = "btnEditPayee"; this.btnEditPayee.Size = new System.Drawing.Size(100, 30); this.btnEditPayee.TabIndex = 1; this.btnEditPayee.Text = "Edit Payee"; this.btnEditPayee.UseVisualStyleBackColor = true; this.btnEditPayee.Click += new System.EventHandler(this.btnEditPayee_Click); // // btnAddPayee // this.btnAddPayee.ForeColor = System.Drawing.SystemColors.ControlText; this.btnAddPayee.Location = new System.Drawing.Point(74, 28); this.btnAddPayee.Name = "btnAddPayee"; this.btnAddPayee.Size = new System.Drawing.Size(100, 30); this.btnAddPayee.TabIndex = 0; this.btnAddPayee.Text = "Add Payee"; this.btnAddPayee.UseVisualStyleBackColor = true; this.btnAddPayee.Click += new System.EventHandler(this.btnAddPayee_Click); // // dGridPayee // this.dGridPayee.AllowUserToAddRows = false; this.dGridPayee.AllowUserToDeleteRows = false; this.dGridPayee.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dGridPayee.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewTextBoxColumn2, this.dataGridViewTextBoxColumn3, this.dataGridViewTextBoxColumn4, this.dataGridViewTextBoxColumn5}); this.dGridPayee.Location = new System.Drawing.Point(15, 151); this.dGridPayee.MultiSelect = false; this.dGridPayee.Name = "dGridPayee"; this.dGridPayee.ReadOnly = true; this.dGridPayee.RowHeadersWidth = 4; this.dGridPayee.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dGridPayee.Size = new System.Drawing.Size(1187, 300); this.dGridPayee.TabIndex = 3; this.dGridPayee.SelectionChanged += new System.EventHandler(this.dGridPayee_SelectionChanged); // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn2.FillWeight = 30F; this.dataGridViewTextBoxColumn2.HeaderText = "Employee Number"; this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.ReadOnly = true; // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn3.FillWeight = 40F; this.dataGridViewTextBoxColumn3.HeaderText = "Employee Name"; this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3"; this.dataGridViewTextBoxColumn3.ReadOnly = true; // // dataGridViewTextBoxColumn4 // this.dataGridViewTextBoxColumn4.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn4.FillWeight = 30F; this.dataGridViewTextBoxColumn4.HeaderText = "Position"; this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4"; this.dataGridViewTextBoxColumn4.ReadOnly = true; // // dataGridViewTextBoxColumn5 // this.dataGridViewTextBoxColumn5.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn5.FillWeight = 30F; this.dataGridViewTextBoxColumn5.HeaderText = "Office"; this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5"; this.dataGridViewTextBoxColumn5.ReadOnly = true; this.dataGridViewTextBoxColumn5.Visible = false; // // tabAccounts // this.tabAccounts.BackColor = System.Drawing.SystemColors.ControlDarkDark; this.tabAccounts.Controls.Add(this.grpAcctDetails); this.tabAccounts.Controls.Add(this.dataGridAccounts); this.tabAccounts.Location = new System.Drawing.Point(4, 22); this.tabAccounts.Name = "tabAccounts"; this.tabAccounts.Padding = new System.Windows.Forms.Padding(3); this.tabAccounts.Size = new System.Drawing.Size(1216, 470); this.tabAccounts.TabIndex = 1; this.tabAccounts.Text = "Accounts"; // // grpAcctDetails // this.grpAcctDetails.Controls.Add(this.txtAcctCode); this.grpAcctDetails.Controls.Add(this.btnDeleteAccount); this.grpAcctDetails.Controls.Add(this.btnEditAccount); this.grpAcctDetails.Controls.Add(this.cmbAcctClass); this.grpAcctDetails.Controls.Add(this.label17); this.grpAcctDetails.Controls.Add(this.txtEditAcctName); this.grpAcctDetails.Controls.Add(this.label16); this.grpAcctDetails.Controls.Add(this.numAB); this.grpAcctDetails.Controls.Add(this.label10); this.grpAcctDetails.Controls.Add(this.label12); this.grpAcctDetails.Controls.Add(this.lblAcctClass); this.grpAcctDetails.Controls.Add(this.lblAcctName); this.grpAcctDetails.Controls.Add(this.lblAcctCode); this.grpAcctDetails.ForeColor = System.Drawing.Color.White; this.grpAcctDetails.Location = new System.Drawing.Point(15, 221); this.grpAcctDetails.Name = "grpAcctDetails"; this.grpAcctDetails.Size = new System.Drawing.Size(529, 230); this.grpAcctDetails.TabIndex = 1; this.grpAcctDetails.TabStop = false; this.grpAcctDetails.Text = "Account Details"; // // txtAcctCode // this.txtAcctCode.Location = new System.Drawing.Point(144, 87); this.txtAcctCode.Name = "txtAcctCode"; this.txtAcctCode.ReadOnly = true; this.txtAcctCode.Size = new System.Drawing.Size(120, 25); this.txtAcctCode.TabIndex = 11; // // btnDeleteAccount // this.btnDeleteAccount.ForeColor = System.Drawing.Color.Black; this.btnDeleteAccount.Location = new System.Drawing.Point(407, 200); this.btnDeleteAccount.Name = "btnDeleteAccount"; this.btnDeleteAccount.Size = new System.Drawing.Size(116, 24); this.btnDeleteAccount.TabIndex = 10; this.btnDeleteAccount.Text = "Delete Account"; this.btnDeleteAccount.UseVisualStyleBackColor = true; // // btnEditAccount // this.btnEditAccount.ForeColor = System.Drawing.Color.Black; this.btnEditAccount.Location = new System.Drawing.Point(407, 173); this.btnEditAccount.Name = "btnEditAccount"; this.btnEditAccount.Size = new System.Drawing.Size(116, 24); this.btnEditAccount.TabIndex = 9; this.btnEditAccount.Text = "Edit Account"; this.btnEditAccount.UseVisualStyleBackColor = true; this.btnEditAccount.Click += new System.EventHandler(this.btnEditAccount_Click); // // cmbAcctClass // this.cmbAcctClass.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbAcctClass.Enabled = false; this.cmbAcctClass.FormattingEnabled = true; this.cmbAcctClass.Items.AddRange(new object[] { "PS", "MOOE", "FE", "CO"}); this.cmbAcctClass.Location = new System.Drawing.Point(144, 156); this.cmbAcctClass.Name = "cmbAcctClass"; this.cmbAcctClass.Size = new System.Drawing.Size(120, 25); this.cmbAcctClass.TabIndex = 8; // // label17 // this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(23, 159); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(83, 17); this.label17.TabIndex = 7; this.label17.Text = "Classification"; // // txtEditAcctName // this.txtEditAcctName.Location = new System.Drawing.Point(144, 122); this.txtEditAcctName.Name = "txtEditAcctName"; this.txtEditAcctName.ReadOnly = true; this.txtEditAcctName.Size = new System.Drawing.Size(258, 25); this.txtEditAcctName.TabIndex = 6; // // label16 // this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(22, 125); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(93, 17); this.label16.TabIndex = 5; this.label16.Text = "Account Name"; // // numAB // this.numAB.DecimalPlaces = 2; this.numAB.Enabled = false; this.numAB.Location = new System.Drawing.Point(144, 189); this.numAB.Maximum = new decimal(new int[] { 1569325055, 23283064, 0, 0}); this.numAB.Name = "numAB"; this.numAB.Size = new System.Drawing.Size(120, 25); this.numAB.TabIndex = 4; this.numAB.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(22, 191); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(111, 17); this.label10.TabIndex = 3; this.label10.Text = "Approved Budget"; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(22, 90); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(89, 17); this.label12.TabIndex = 3; this.label12.Text = "Account Code"; // // lblAcctClass // this.lblAcctClass.AutoSize = true; this.lblAcctClass.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblAcctClass.Location = new System.Drawing.Point(172, 55); this.lblAcctClass.Name = "lblAcctClass"; this.lblAcctClass.Size = new System.Drawing.Size(80, 17); this.lblAcctClass.TabIndex = 2; this.lblAcctClass.Text = "Classification"; // // lblAcctName // this.lblAcctName.AutoSize = true; this.lblAcctName.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblAcctName.Location = new System.Drawing.Point(172, 36); this.lblAcctName.Name = "lblAcctName"; this.lblAcctName.Size = new System.Drawing.Size(112, 21); this.lblAcctName.TabIndex = 1; this.lblAcctName.Text = "Account Name"; // // lblAcctCode // this.lblAcctCode.AutoSize = true; this.lblAcctCode.Font = new System.Drawing.Font("Segoe UI", 20.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblAcctCode.Location = new System.Drawing.Point(17, 30); this.lblAcctCode.Name = "lblAcctCode"; this.lblAcctCode.Size = new System.Drawing.Size(65, 37); this.lblAcctCode.TabIndex = 0; this.lblAcctCode.Text = "000"; // // dataGridAccounts // this.dataGridAccounts.AllowUserToAddRows = false; this.dataGridAccounts.AllowUserToDeleteRows = false; this.dataGridAccounts.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridAccounts.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colAcctCode, this.colAcctName, this.colAcctClass, this.colAB}); this.dataGridAccounts.Location = new System.Drawing.Point(15, 15); this.dataGridAccounts.MultiSelect = false; this.dataGridAccounts.Name = "dataGridAccounts"; this.dataGridAccounts.ReadOnly = true; this.dataGridAccounts.RowHeadersWidth = 4; this.dataGridAccounts.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridAccounts.Size = new System.Drawing.Size(1186, 200); this.dataGridAccounts.TabIndex = 0; this.dataGridAccounts.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridAccounts_CellContentClick); this.dataGridAccounts.SelectionChanged += new System.EventHandler(this.dataGridAccounts_SelectionChanged); // // colAcctCode // this.colAcctCode.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colAcctCode.FillWeight = 25F; this.colAcctCode.HeaderText = "Account Code"; this.colAcctCode.Name = "colAcctCode"; this.colAcctCode.ReadOnly = true; // // colAcctName // this.colAcctName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colAcctName.FillWeight = 25F; this.colAcctName.HeaderText = "Account Name"; this.colAcctName.Name = "colAcctName"; this.colAcctName.ReadOnly = true; // // colAcctClass // this.colAcctClass.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colAcctClass.FillWeight = 25F; this.colAcctClass.HeaderText = "Classification"; this.colAcctClass.Name = "colAcctClass"; this.colAcctClass.ReadOnly = true; // // colAB // this.colAB.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colAB.FillWeight = 25F; this.colAB.HeaderText = "Approved Budget"; this.colAB.Name = "colAB"; this.colAB.ReadOnly = true; // // tabLogs // this.tabLogs.BackColor = System.Drawing.Color.DimGray; this.tabLogs.Controls.Add(this.txtLogs); this.tabLogs.Location = new System.Drawing.Point(4, 22); this.tabLogs.Name = "tabLogs"; this.tabLogs.Padding = new System.Windows.Forms.Padding(3); this.tabLogs.Size = new System.Drawing.Size(1216, 470); this.tabLogs.TabIndex = 2; this.tabLogs.Text = "Logs"; // // txtLogs // this.txtLogs.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtLogs.Location = new System.Drawing.Point(15, 17); this.txtLogs.Multiline = true; this.txtLogs.Name = "txtLogs"; this.txtLogs.ReadOnly = true; this.txtLogs.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtLogs.Size = new System.Drawing.Size(1186, 281); this.txtLogs.TabIndex = 0; // // openFileDialog // this.openFileDialog.FileName = "openFileDialog"; this.openFileDialog.Title = "Select image"; // // Form1 // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.BackColor = System.Drawing.Color.White; this.BackgroundImage = global::BUR_UI.Properties.Resources.bg; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(1264, 681); this.Controls.Add(this.pnlAdmin); this.Controls.Add(this.pnlCreate); this.Controls.Add(this.pnlMain); this.Controls.Add(this.picBanner); this.Controls.Add(this.label4); this.Controls.Add(this.grpUser); this.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.MaximizeBox = false; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "PLM Budget Utilization System 7_5_0_128_03_10_2017"; this.Load += new System.EventHandler(this.Form1_Load); this.grpUser.ResumeLayout(false); this.grpUser.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picPic)).EndInit(); this.contextMenuStrip1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.picBanner)).EndInit(); this.pnlMain.ResumeLayout(false); this.pnlMain.PerformLayout(); this.toolStrip.ResumeLayout(false); this.toolStrip.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridMain)).EndInit(); this.pnlCreate.ResumeLayout(false); this.pnlCreate.PerformLayout(); this.grpParticulars.ResumeLayout(false); this.grpParticulars.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numAmount)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridParticulars)).EndInit(); this.pnlAdmin.ResumeLayout(false); this.tabAdmin.ResumeLayout(false); this.tabPageUsers.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picStaffPic)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dGridUsers)).EndInit(); this.tabOffices.ResumeLayout(false); this.grpOfficeActions.ResumeLayout(false); this.grpOfficeDetails.ResumeLayout(false); this.grpOfficeDetails.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dGridOffices)).EndInit(); this.tabPayees.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dGridPayee)).EndInit(); this.tabAccounts.ResumeLayout(false); this.grpAcctDetails.ResumeLayout(false); this.grpAcctDetails.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numAB)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridAccounts)).EndInit(); this.tabLogs.ResumeLayout(false); this.tabLogs.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox picPic; private System.Windows.Forms.Label lblUser; private System.Windows.Forms.Label lblPos; private System.Windows.Forms.GroupBox grpUser; private System.Windows.Forms.Button btnLogOut; private System.Windows.Forms.Label label4; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem createToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem; private System.Windows.Forms.PictureBox picBanner; private System.Windows.Forms.Panel pnlMain; private System.Windows.Forms.ToolStrip toolStrip; private System.Windows.Forms.ToolStripButton toolBtnCreate; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton toolBtnEdit; private System.Windows.Forms.ToolStripLabel toolStripLabel2; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripButton toolBtnPrint; private System.Windows.Forms.ToolStripLabel toolStripLabel3; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripButton toolBtnDelete; private System.Windows.Forms.ToolStripLabel toolStripLabel4; private System.Windows.Forms.DataGridView dataGridMain; private System.Windows.Forms.DataGridViewTextBoxColumn colBURNumber; private System.Windows.Forms.DataGridViewTextBoxColumn colOffice; private System.Windows.Forms.DataGridViewTextBoxColumn colPayee; private System.Windows.Forms.DataGridViewTextBoxColumn colDate; private System.Windows.Forms.DataGridViewTextBoxColumn colStaff; private System.Windows.Forms.TextBox txtSearch; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label2; private System.Windows.Forms.GroupBox grpParticulars; private System.Windows.Forms.Button button5; private System.Windows.Forms.Button button4; private System.Windows.Forms.Button btnEdit; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label9; private System.Windows.Forms.DataGridViewTextBoxColumn colClassification; private System.Windows.Forms.DataGridViewTextBoxColumn colAcct_Code; private System.Windows.Forms.DataGridViewTextBoxColumn colAcct_Name; private System.Windows.Forms.DataGridViewTextBoxColumn colAmount; public System.Windows.Forms.Panel pnlCreate; public System.Windows.Forms.TextBox txtDescription; public System.Windows.Forms.ComboBox cmbPayee; public System.Windows.Forms.ComboBox cmbOffice; public System.Windows.Forms.NumericUpDown numAmount; public System.Windows.Forms.TextBox txtAcctName; public System.Windows.Forms.ComboBox cmbCode; public System.Windows.Forms.ComboBox cmbClass; public System.Windows.Forms.DataGridView dataGridParticulars; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripLabel toolStripLabel5; private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem1; public System.Windows.Forms.TextBox txtPR; private System.Windows.Forms.PrintPreviewDialog dlgPrint; private System.Windows.Forms.Button btnAdmin; private System.Windows.Forms.Panel pnlAdmin; private System.Windows.Forms.TabControl tabAdmin; private System.Windows.Forms.TabPage tabPageUsers; private System.Windows.Forms.TabPage tabAccounts; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.GroupBox grpAcctDetails; private System.Windows.Forms.Label lblAcctCode; private System.Windows.Forms.DataGridView dataGridAccounts; private System.Windows.Forms.Button btnDeleteAccount; private System.Windows.Forms.Button btnEditAccount; private System.Windows.Forms.ComboBox cmbAcctClass; private System.Windows.Forms.Label label17; private System.Windows.Forms.TextBox txtEditAcctName; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label lblAcctClass; private System.Windows.Forms.Label lblAcctName; private System.Windows.Forms.MaskedTextBox txtBURNumber; public System.Windows.Forms.TextBox txtPayee; private System.Windows.Forms.TabPage tabLogs; private System.Windows.Forms.TextBox txtLogs; private System.Windows.Forms.Label label18; private System.Windows.Forms.DataGridViewTextBoxColumn colAcctCode; private System.Windows.Forms.DataGridViewTextBoxColumn colAcctName; private System.Windows.Forms.DataGridViewTextBoxColumn colAcctClass; private System.Windows.Forms.DataGridViewTextBoxColumn colAB; private System.Windows.Forms.Label lblSign; public System.Windows.Forms.ComboBox cmbSign; private System.Windows.Forms.ToolStripMenuItem sAAOToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem monthlyToolStripMenuItem; private System.Windows.Forms.NumericUpDown numAB; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox txtAcctCode; private System.Windows.Forms.TabPage tabOffices; private System.Windows.Forms.TabPage tabPayees; private System.Windows.Forms.GroupBox grpOfficeActions; private System.Windows.Forms.GroupBox grpOfficeDetails; private System.Windows.Forms.Label lblOfficeHeadPos; private System.Windows.Forms.Label label26; private System.Windows.Forms.Label lblOfficeName; private System.Windows.Forms.Label label22; private System.Windows.Forms.DataGridView dGridOffices; private System.Windows.Forms.Button btnDeleteOffice; private System.Windows.Forms.Button btnEditOffice; private System.Windows.Forms.Button btnAddOffice; private System.Windows.Forms.Label lblOfficeHead; private System.Windows.Forms.Label label24; private System.Windows.Forms.DataGridViewTextBoxColumn officeCode; private System.Windows.Forms.DataGridViewTextBoxColumn officeNameFull; private System.Windows.Forms.DataGridViewTextBoxColumn officeAbbr; private System.Windows.Forms.DataGridViewTextBoxColumn officehead; private System.Windows.Forms.DataGridViewTextBoxColumn officeheadPos; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label lblPayeeOffice; private System.Windows.Forms.Label label29; private System.Windows.Forms.Label lblPayeePos; private System.Windows.Forms.Label label20; private System.Windows.Forms.Label lblPayeeName; private System.Windows.Forms.Label label23; private System.Windows.Forms.Label lblPayeeNumber; private System.Windows.Forms.Label label27; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button btnEditPayee; private System.Windows.Forms.Button btnAddPayee; private System.Windows.Forms.DataGridView dGridPayee; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button btnEditStaff; private System.Windows.Forms.Button btnAddStaff; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.Label lblStaffType; private System.Windows.Forms.Label label30; private System.Windows.Forms.Label lblStaffPosition; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label lblStaffName; private System.Windows.Forms.Label label19; private System.Windows.Forms.Label lblStaffNumber; private System.Windows.Forms.Label label25; private System.Windows.Forms.DataGridView dGridUsers; private System.Windows.Forms.DataGridViewTextBoxColumn staffNumber; private System.Windows.Forms.DataGridViewTextBoxColumn staffName; private System.Windows.Forms.DataGridViewTextBoxColumn staffType; private System.Windows.Forms.DataGridViewTextBoxColumn staffPosition; private System.Windows.Forms.DataGridViewTextBoxColumn staffPic; private System.Windows.Forms.PictureBox picStaffPic; } }
53.713015
172
0.621358
[ "MIT" ]
cnswico/PLM-BUS-UI
BUR_UI/Form1.Designer.cs
114,734
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using SecondChanceParts.Web.Data; using SecondChanceParts.Web.Models; namespace SecondChanceParts.Web.Pages.Cart { public class CreateModel : PageModel { private readonly SecondChanceParts.Web.Data.SecondChancePartsContext _context; public CreateModel(SecondChanceParts.Web.Data.SecondChancePartsContext context) { _context = context; } public IActionResult OnGet() { return Page(); } [BindProperty] public SecondChanceParts.Web.Models.ShoppingCart ShoppingCart { get; set; } // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://aka.ms/RazorPagesCRUD. public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.ShoppingCarts.Add(ShoppingCart); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } } }
29.043478
104
0.633982
[ "Apache-2.0" ]
Appdynamics/appd-azure-workshop
labs/app-services/src/SecondChanceParts.Web/Pages/Cart/Create.cshtml.cs
1,336
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Hatfield.EnviroData.Core { using System; using System.Collections.Generic; public partial class TaxonomicClassifierExternalIdentifier { public int BridgeID { get; set; } public int TaxonomicClassifierID { get; set; } public int ExternalIdentifierSystemID { get; set; } public string TaxonomicClassifierExternalIdentifier1 { get; set; } public string TaxonomicClassifierExternalIdentifierURI { get; set; } public virtual ExternalIdentifierSystem ExternalIdentifierSystem { get; set; } public virtual TaxonomicClassifier TaxonomicClassifier { get; set; } } }
40.851852
87
0.590209
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
HatfieldConsultants/Hatfield.EnviroData.Core
Source/Hatfield.EnviroData.Core/TaxonomicClassifierExternalIdentifier.cs
1,103
C#
using Tamir.SharpSsh.java.io; namespace Tamir.Streams { /// <summary> /// Summary description for InputStreamWrapper. /// </summary> public class InputStreamWrapper : InputStream { System.IO.Stream s; public InputStreamWrapper(System.IO.Stream s) { this.s = s; } public override int Read(byte[] buffer, int offset, int count) { return s.Read(buffer, offset, count); } } }
19.136364
65
0.650831
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
linux-distro/package/nuxleus/Source/Vendor/sharpssh/SharpSSH/java/io/InputStreamWrapper.cs
421
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Xml.Schema; using System.Xml.Serialization; namespace ES2.Amplitude.Xml.Serialization { /// <remarks/> [GeneratedCode("xsd", "2.0.50727.3038")] [Serializable] [DebuggerStepThrough] [DesignerCategory("code")] public partial class XmlAttributeOverride : INotifyPropertyChanged { private XmlExtraType[] extraTypeField; private string nameField; private string dataTypeField; /// <remarks/> [XmlElement("ExtraType", Form = XmlSchemaForm.Unqualified)] public XmlExtraType[] ExtraType { get { return this.extraTypeField; } set { this.extraTypeField = value; this.RaisePropertyChanged("ExtraType"); } } /// <remarks/> [XmlAttribute] public string Name { get { return this.nameField; } set { this.nameField = value; this.RaisePropertyChanged("Name"); } } /// <remarks/> [XmlAttribute] public string DataType { get { return this.dataTypeField; } set { this.dataTypeField = value; this.RaisePropertyChanged("DataType"); } } public event PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
19.311688
70
0.70881
[ "MIT" ]
Scrivener07/Endless-Studio
Source/Studio.ES2/Amplitude/Xml/Serialization/XmlAttributeOverride.cs
1,489
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2018-06-18.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.CloudFront.Model { ///<summary> /// CloudFront exception /// </summary> #if !PCL && !CORECLR [Serializable] #endif public class InvalidWebACLIdException : AmazonCloudFrontException { /// <summary> /// Constructs a new InvalidWebACLIdException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public InvalidWebACLIdException(string message) : base(message) {} /// <summary> /// Construct instance of InvalidWebACLIdException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public InvalidWebACLIdException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of InvalidWebACLIdException /// </summary> /// <param name="innerException"></param> public InvalidWebACLIdException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of InvalidWebACLIdException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidWebACLIdException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of InvalidWebACLIdException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidWebACLIdException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !CORECLR /// <summary> /// Constructs a new instance of the InvalidWebACLIdException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected InvalidWebACLIdException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
42.979381
178
0.648837
[ "Apache-2.0" ]
GitGaby/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/InvalidWebACLIdException.cs
4,169
C#
namespace Example { using OpenTK.Input; using System; using Zenseless.ExampleFramework; class Controller { [STAThread] private static void Main() { var window = new ExampleWindow(); var visual = new MainVisual(window.RenderContext.RenderState, window.ContentLoader); window.GameWindow.MouseMove += (s, e) => { if (ButtonState.Pressed == e.Mouse.LeftButton) { visual.CameraAzimuth += 300 * e.XDelta / (float)window.GameWindow.Width; visual.CameraElevation += 300 * e.YDelta / (float)window.GameWindow.Height; } }; window.GameWindow.MouseWheel += (s, e) => visual.CameraDistance *= (float)Math.Pow(1.05, e.DeltaPrecise); window.Update += visual.Update; window.Render += visual.Render; window.Run(); } } }
26.482759
108
0.68099
[ "Apache-2.0" ]
amadron/FinalProject_ShaderProg
examples/SHADER/07 - CameraTransformation/CameraTransformationExample.cs
770
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 WindowsInput.Native; using Xunit; using Xunit.Abstractions; namespace System.Windows.Forms.UITests { public class PrintPreviewDialogTests : ControlTestBase { public PrintPreviewDialogTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } [WinFormsFact] public async Task PrintPreviewDialog_Hotkey_Ctrl_1Async() { await RunTestAsync(async printPreviewDialog => { await InputSimulator.SendAsync( printPreviewDialog, inputSimulator => inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_1)); Assert.Equal(1, printPreviewDialog.PrintPreviewControl.Rows); Assert.Equal(1, printPreviewDialog.PrintPreviewControl.Columns); }); } [WinFormsFact] public async Task PrintPreviewDialog_Hotkey_Ctrl_2Async() { await RunTestAsync(async printPreviewDialog => { await InputSimulator.SendAsync( printPreviewDialog, inputSimulator => inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_2)); Assert.Equal(1, printPreviewDialog.PrintPreviewControl.Rows); Assert.Equal(2, printPreviewDialog.PrintPreviewControl.Columns); }); } [WinFormsFact] public async Task PrintPreviewDialog_Hotkey_Ctrl_3Async() { await RunTestAsync(async printPreviewDialog => { await InputSimulator.SendAsync( printPreviewDialog, inputSimulator => inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_3)); Assert.Equal(1, printPreviewDialog.PrintPreviewControl.Rows); Assert.Equal(3, printPreviewDialog.PrintPreviewControl.Columns); }); } [WinFormsFact] public async Task PrintPreviewDialog_Hotkey_Ctrl_4Async() { await RunTestAsync(async printPreviewDialog => { await InputSimulator.SendAsync( printPreviewDialog, inputSimulator => inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_4)); Assert.Equal(2, printPreviewDialog.PrintPreviewControl.Rows); Assert.Equal(2, printPreviewDialog.PrintPreviewControl.Columns); }); } [WinFormsFact] public async Task PrintPreviewDialog_Hotkey_Ctrl_5Async() { await RunTestAsync(async printPreviewDialog => { await InputSimulator.SendAsync( printPreviewDialog, inputSimulator => inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_5)); Assert.Equal(2, printPreviewDialog.PrintPreviewControl.Rows); Assert.Equal(3, printPreviewDialog.PrintPreviewControl.Columns); }); } private async Task RunTestAsync(Func<PrintPreviewDialog, Task> runTest) { await RunFormWithoutControlAsync( testDriverAsync: runTest, createForm: () => { return new PrintPreviewDialog() { Size = new(500, 300), }; }); } } }
37.176471
126
0.605222
[ "MIT" ]
DmitryGorokhov/winforms
src/System.Windows.Forms/tests/IntegrationTests/UIIntegrationTests/PrintPreviewDialogTests.cs
3,794
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using ScadaIssuesPortal.Core.Entities; using System; namespace ScadaIssuesPortal.Data.Configurations { public class ReportingCaseCommentConfiguration : IEntityTypeConfiguration<ReportingCaseComment> { public void Configure(EntityTypeBuilder<ReportingCaseComment> builder) { // storing enum as string builder .Property(e => e.Tag) .HasConversion( v => v.ToString(), v => (CommentTag)Enum.Parse(typeof(CommentTag), v)); } } }
30.190476
99
0.664038
[ "MIT" ]
nagasudhirpulla/wrldc_scada_issues_portal
src/WrldcScadaIssuesPortal/ScadaIssuesPortal.Data/Configurations/ReportingCaseCommentConfiguration.cs
636
C#
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.App.Share.Rewards.Domain.Enums { /// <summary> /// 产品限制方式 /// </summary> [ClassProperty(Name = "产品限制方式")] public enum ProductLimitType { /// <summary> /// 产品线范围内 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "选择商品范围内")] Allow = 1, /// <summary> /// 非产品线内的 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "选择商品范围外")] Refuse = 2 } }
23.538462
48
0.545752
[ "MIT" ]
tongxin3267/alabo
src/03.app/01-Alabo.App.Share/Rewards/Domain/Enums/ProductLimitType.cs
690
C#
namespace ModelDownloader.Configuration { public class PluginConfig { public virtual bool BlurNSFWImages { get; set; } = true; public virtual bool DisableWarnings { get; set; } = false; public virtual bool AutomaticallyGeneratePreviews { get; set; } = false; public virtual string ShowPopup { get; set; } = "NextStartup"; } }
33.727273
80
0.663073
[ "MIT" ]
ErisApps/ModelDownloader
ModelDownloader/Configuration/PluginConfig.cs
373
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.42 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WrapperTest.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
32.709677
148
0.607495
[ "MIT" ]
retrodump/Wintermute-Engine
src/Tests/WrapperTest/WrapperTest/Properties/Settings.Designer.cs
1,016
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class VectorTest : MonoBehaviour { public GameObject p0; public GameObject p1; public GameObject p2; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { Debug.DrawLine(p1.transform.position, p2.transform.position, Color.green); Debug.DrawRay(p0.transform.position, normalCalcFromJoint(p0.transform.position, p1.transform.position, p2.transform.position) * 100.0f, Color.yellow); } public Vector3 normalCalcFromJoint(Vector3 point, Vector3 joint1, Vector3 joint2) { Vector3 vertNor = point - joint1; vertNor.Normalize(); float aDis = Vector3.Distance(point, joint1); Vector3 jointVector = joint1 - joint2; jointVector.Normalize(); float vectorAngle = 180.0f - Vector3.Angle(-vertNor, -jointVector); Vector3 apointVec = Vector3.zero; Vector3 newPointVec = Vector3.zero; if (vectorAngle == 90.0f) { float bDis = aDis / Mathf.Sin(90.0f / 180.0f * Mathf.PI) * Mathf.Sin((90.0f - vectorAngle) / 180.0f * Mathf.PI); apointVec = joint1 - point; newPointVec = (joint1 + bDis * -jointVector.normalized) - point; newPointVec += apointVec; } else { float bDis = aDis / Mathf.Sin(90.0f / 180.0f * Mathf.PI) * Mathf.Sin((90.0f - vectorAngle) / 180.0f * Mathf.PI); apointVec = joint1 - point; newPointVec = (joint1 + bDis * -jointVector) - point; } newPointVec.Normalize(); // newPointVec *= 2.0f; return newPointVec; } }
28.190476
158
0.610923
[ "MIT" ]
SiTae9317/FittingTest
Assets/Scripts/VectorTest.cs
1,778
C#
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; namespace Bitbird.Core.Tasks { public class AsyncTimer : IDisposable { private readonly TimeSpan initialDelay; private readonly TimeSpan interval; private readonly bool autoReset; private readonly CancellationToken cancellationToken; [NotNull] private readonly SemaphoreSlim runningInstanceSemaphore; [CanBeNull] private AsyncTimerStartedInstance runningInstance; public event AsyncTimerActionDelegate Elapsed; public event AsyncTimerExceptionDelegate ExceptionOccurred; private AsyncTimer( TimeSpan initialDelay, TimeSpan interval, bool autoReset, CancellationToken cancellationToken) { this.initialDelay = initialDelay; this.interval = interval; this.autoReset = autoReset; this.cancellationToken = cancellationToken; runningInstanceSemaphore = new SemaphoreSlim(1, 1); } [NotNull, ItemNotNull, UsedImplicitly] public static async Task<AsyncTimer> CreateAsync( TimeSpan initialDelay, TimeSpan interval, bool autoReset = true, bool enabled = true, CancellationToken? cancellationToken = null, [CanBeNull, ItemNotNull] params AsyncTimerActionDelegate[] elapsedActions) { var timer = new AsyncTimer( initialDelay, interval, autoReset, cancellationToken ?? CancellationToken.None); try { if (elapsedActions != null) foreach (var elapsedAction in elapsedActions) // ReSharper disable once ConstantNullCoalescingCondition timer.Elapsed += elapsedAction ?? throw new ArgumentNullException(nameof(elapsedActions)); if (enabled) { await timer.StartAsync(); } } catch { try { timer.Dispose(); } catch { /* ignored */ } throw; } return timer; } [UsedImplicitly] public bool IsEnabled { get { runningInstanceSemaphore.Wait(); try { return runningInstance != null; } finally { runningInstanceSemaphore.Release(); } } } [UsedImplicitly] public TimeSpan InitialDelay => initialDelay; [UsedImplicitly] public TimeSpan Interval => interval; [UsedImplicitly] public bool AutoReset => autoReset; [NotNull] public async Task StartAsync() { // ReSharper disable once MethodSupportsCancellation await runningInstanceSemaphore.WaitAsync(); try { if (runningInstance != null) return; runningInstance = new AsyncTimerStartedInstance(cancellationToken); #pragma warning disable 4014 // Don't await, just schedule in background // ReSharper disable once MethodSupportsCancellation Task.Run(() => MainLoopAsync(runningInstance)); #pragma warning restore 4014 } finally { runningInstanceSemaphore.Release(); } } [NotNull] public async Task StopAsync() { AsyncTimerStartedInstance currentInstance; // ReSharper disable once MethodSupportsCancellation await runningInstanceSemaphore.WaitAsync(); try { currentInstance = runningInstance; if (currentInstance == null) return; currentInstance.Cancel(); } finally { runningInstanceSemaphore.Release(); } await currentInstance.WaitForEndAsync(); } [NotNull] private async Task MainLoopAsync([NotNull] AsyncTimerStartedInstance currentInstance) { if (currentInstance == null) throw new ArgumentNullException(nameof(currentInstance)); try { currentInstance.CancellationToken.ThrowIfCancellationRequested(); await Task.Delay(initialDelay, currentInstance.CancellationToken); do { currentInstance.CancellationToken.ThrowIfCancellationRequested(); var actions = Elapsed ?.GetInvocationList() .ToArray() .Cast<AsyncTimerActionDelegate>(); if (actions == null) continue; var cancellationTokenCopy = currentInstance.CancellationToken; await Task.WhenAll(actions.Select(async action => { try { await action(cancellationTokenCopy); } catch (Exception exception) { try { var task = ExceptionOccurred?.Invoke(action, exception); if (task != null) await task; } catch { /* ignored */ } } })); currentInstance.CancellationToken.ThrowIfCancellationRequested(); await Task.Delay(interval, currentInstance.CancellationToken); } while (autoReset); } catch (TaskCanceledException) { /* expected */ } finally { // ReSharper disable once MethodSupportsCancellation await runningInstanceSemaphore.WaitAsync(); try { if (runningInstance == currentInstance) runningInstance = null; } finally { runningInstanceSemaphore.Release(); } try { currentInstance.Dispose(); } catch { /* ignored */ } } } public void Dispose() { try { AsyncHelper.RunSync(StopAsync); } catch { /* ignored */ } try { runningInstanceSemaphore.Dispose(); } catch { /* ignored */ } } } }
32.530516
114
0.502814
[ "MIT" ]
bitbird-dev/Bitbird.Core
Bitbird.Core/Tasks/AsyncTimer.cs
6,931
C#
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace EntityFrameworkCore.Jet.IntegrationTests.Model20_HiddenBackingField { public interface IEntity { int Id { get; set; } State State { get; set; } } public abstract class Entity : IEntity { protected int InternalState { get; set; } public int Id { get; set; } [NotMapped] public State State { get { return (State) InternalState; } set { InternalState = (int) value; } } // Entity is not a POCO class because of this :( // If we want to hide InternalState this is the only way to map it public class EntityMap : IEntityTypeConfiguration<Entity> { public void Configure(EntityTypeBuilder<Entity> builder) { // Properties builder.Property(t => t.InternalState) .HasColumnName("State"); } } } public enum State { Inactive = 0, Active = 1 } public class Company : Entity { [NotMapped] public new CompanyState State { get { return (CompanyState)InternalState; } set { InternalState = (int)value; } } [MaxLength(50)] public string SomeOtherProp { get; set; } } public class Employee : Entity { [MaxLength(50)] public string SomeOtherProp { get; set; } } public enum CompanyState { Inactive = 0, Active = 1, Extra = 2 } }
24.450704
77
0.569124
[ "Apache-2.0" ]
MichaelSteinecke/EntityFrameworkCore.Jet
test/EFCore.Jet.IntegrationTests/Model20_HiddenBackingField/Model.cs
1,738
C#
namespace Twitch.Net.Enums { public enum SearchType { suggest } }
10.875
27
0.574713
[ "Apache-2.0" ]
gibletto/twitch.net
Twitch.Net/Enums/SearchType.cs
89
C#
// ----------------------------------------------------------------------- // <copyright file="FunctionAuthCacheRefreshEventHandler.cs" company="OSharp开源团队"> // Copyright (c) 2014-2018 OSharp. All rights reserved. // </copyright> // <site>http://www.osharp.org</site> // <last-editor>郭明锋</last-editor> // <last-date>2018-06-12 22:29</last-date> // ----------------------------------------------------------------------- using System; using Microsoft.Extensions.DependencyInjection; using OSharp.AspNetCore; using OSharp.Dependency; using OSharp.EventBuses; using OSharp.Security; namespace OSharp.Security.Events { /// <summary> /// 功能权限缓存刷新事件处理器 /// </summary> public class FunctionAuthCacheRefreshEventHandler : EventHandlerBase<FunctionAuthCacheRefreshEventData> { private readonly IServiceProvider _provider; /// <summary> /// 初始化一个<see cref="FunctionAuthCacheRefreshEventHandler"/>类型的新实例 /// </summary> public FunctionAuthCacheRefreshEventHandler(IServiceProvider provider) { _provider = provider; } /// <summary> /// 事件处理 /// </summary> /// <param name="eventData">事件源数据</param> public override void Handle(FunctionAuthCacheRefreshEventData eventData) { if (!_provider.InHttpRequest()) { return; } IFunctionAuthCache cache = _provider.GetService<IFunctionAuthCache>(); if (eventData.FunctionIds.Length > 0) { cache.RemoveFunctionCaches(eventData.FunctionIds); foreach (Guid functionId in eventData.FunctionIds) { cache.GetFunctionRoles(functionId); } } if (eventData.UserNames.Length > 0) { cache.RemoveUserCaches(eventData.UserNames); foreach (string userName in eventData.UserNames) { cache.GetUserFunctions(userName); } } } } }
31.909091
107
0.549858
[ "Apache-2.0" ]
2012desuming/osharp
src/OSharp.Permissions/Security/Events/FunctionAuthCacheRefreshEventHandler.cs
2,188
C#
using Chiota.ViewModels.Classes; namespace Chiota.ViewModels { using System; using System.Threading.Tasks; using System.Windows.Input; using Chiota.Models; using Chiota.Views; using Xamarin.Forms; public class CheckSeedStoredViewModel : BaseViewModel { public Action DisplayInvalidSeedPrompt; private readonly User user; private string seedInput; public CheckSeedStoredViewModel(User user) { this.user = user; } public ICommand SubmitCommand => new Command(async () => { await this.SeedCheck(); }); public ICommand BackCommand => new Command(async () => { await this.Back(); }); public string SeedInput { get => this.seedInput; set { this.seedInput = value; this.RaisePropertyChanged(); } } private async Task SeedCheck() { this.SeedInput = this.SeedInput?.Trim(); if (this.user.Seed.ToString() != this.SeedInput) { this.DisplayInvalidSeedPrompt(); } else if (!this.IsBusy) { this.IsBusy = true; await this.Navigation.PushModalAsync(new NavigationPage(new SetupPage(this.user))); this.IsBusy = false; } } private async Task Back() { if (!this.IsBusy) { this.IsBusy = true; await this.Navigation.PopModalAsync(); this.IsBusy = false; } } } }
21.227273
91
0.615275
[ "MIT" ]
Felandil/Chiota
Chiota/Chiota/ViewModels/CheckSeedStoredViewModel.cs
1,403
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("zimuku")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("zimuku")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("121f4b94-f733-4589-b0a5-e1cfc4f366ae")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 //通过使用 "*",如下所示: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.054054
56
0.713053
[ "Apache-2.0" ]
Haku-Men/TPlayer
Plugins/zimuku/Properties/AssemblyInfo.cs
1,268
C#
using System; using System.Collections.Generic; namespace NetOpnApi { /// <summary> /// A common interface for parameter sets. /// </summary> public interface IParameterSet { /// <summary> /// Get a list of parameters to add to the request URL. /// </summary> /// <returns></returns> public IReadOnlyList<string> GetUrlParameters(); /// <summary> /// Get a list of key/value parameters to add to the request URL. /// </summary> /// <returns></returns> public IReadOnlyList<KeyValuePair<string, string>> GetQueryParameters(); /// <summary> /// Get an object to pass as the request payload. /// </summary> /// <returns></returns> public object GetRequestPayload(); /// <summary> /// Get the data type of the object to pass as the request payload (for serialization). /// </summary> /// <returns></returns> public Type GetRequestPayloadDataType(); } }
29.083333
95
0.573066
[ "MIT" ]
barkerest/NetOpnApi
NetOpnApi/IParameterSet.cs
1,049
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using PdfSharp.Drawing; using PdfSharp.Pdf; using Scarif_DS_1.exceptions; namespace Scarif_DS_1.modulos.Create { //Classe da Funcionalidade criar public class CreateMod : IModel { private string _pathDestino; private string _fileDestino; private string _texto; private string _fonte; private string _alinhamento; private string _estilo; private int _tamanho; private bool _resultado; private string _mensagem; private string _erro; //Construtor da Classe internal CreateMod(CreateDados dados) { PathDestino = dados.PathDestino; FileDestino = dados.FileDestino; Texto = dados.Texto; Fonte = dados.Fonte; Alinhamento = dados.Alinhamento; Estilo = dados.Estilo; Tamanho = dados.Tamanho; Resultado = false; _erro = null; _mensagem = null; } //Função que executa funcionalidade public void Criar() { try { //Validar os dados no model if (PathDestino == null || FileDestino == null) { //Cria uma lista com os erros encontrados nos dados List<string> erros = new List<string>(); if (PathDestino == null) erros.Add("Caminho de Destino"); if (FileDestino == null) erros.Add("Ficheiro de Destino"); Erros = string.Join(", ", erros); Mensagem = "Faltam Dados para concluir a tarefa"; throw new ExceptionDadosInvalidos("Faltam Dados para concluir a tarefa", erros); } //Validar os dados no model if (Texto == null) { //Cria uma lista com os erros encontrados nos dados List<string> erros = new List<string>(); if (Texto == null) erros.Add("Texto Inválido"); Erros = string.Join(", ", erros); Mensagem = "Faltam Dados para concluir a tarefa"; throw new ExceptionDadosInvalidos("Faltam Dados para concluir a tarefa", erros); } //Validar os dados no model if (Fonte == null) { //Cria uma lista com os erros encontrados nos dados List<string> erros = new List<string>(); if (Fonte == null) erros.Add("Fonte Inválida"); Erros = string.Join(", ", erros); Mensagem = "Faltam Dados para concluir a tarefa"; throw new ExceptionDadosInvalidos("Faltam Dados para concluir a tarefa", erros); } //Validar os dados no model if (Alinhamento == null) { //Cria uma lista com os erros encontrados nos dados List<string> erros = new List<string>(); if (Alinhamento == null || (Alinhamento != "Left" && Alinhamento != "Center" && Alinhamento != "Right")) erros.Add("Alinhamento Inválido"); Erros = string.Join(", ", erros); Mensagem = "Faltam Dados para concluir a tarefa"; throw new ExceptionDadosInvalidos("Faltam Dados para concluir a tarefa", erros); } //Validar os dados no model if (Tamanho == 0) { //Cria uma lista com os erros encontrados nos dados List<string> erros = new List<string>(); if (Tamanho == 0) erros.Add("Tamanho Inválido"); Erros = string.Join(", ", erros); Mensagem = "Faltam Dados para concluir a tarefa"; throw new ExceptionDadosInvalidos("Faltam Dados para concluir a tarefa", erros); } //Validar os dados no model if (Estilo == null) { //Cria uma lista com os erros encontrados nos dados List<string> erros = new List<string>(); if (Estilo == null || (Estilo != "Regular" && Estilo != "Bold" && Estilo != "BoldItalic" && Estilo != "Italic" && Estilo != "Strikeout" && Estilo != "Underline")) erros.Add("Estilo Inválido"); Erros = string.Join(", ", erros); Mensagem = "Faltam Dados para concluir a tarefa"; throw new ExceptionDadosInvalidos("Faltam Dados para concluir a tarefa", erros); } //Cria o caminho para o endereço string caminhoDestino = Path.Combine(PathDestino, FileDestino); //Criar o output PdfDocument outputDocument = new PdfDocument(); //Cria uma página vazia PdfPage page = outputDocument.AddPage(); var gfx = XGraphics.FromPdfPage(page); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); XFont font = new XFont(Fonte, Tamanho, XFontStyle.Regular); // Cria a fonte if (Estilo == "Bold") { font = new XFont(Fonte, Tamanho, XFontStyle.Bold); } else if (Estilo == "BoldItalic") { font = new XFont(Fonte, Tamanho, XFontStyle.BoldItalic); } else if (Estilo == "Italic") { font = new XFont(Fonte, Tamanho, XFontStyle.Italic); } else if (Estilo == "Strikeout") { font = new XFont(Fonte, Tamanho, XFontStyle.Strikeout); } else if (Estilo == "Underline") { font = new XFont(Fonte, Tamanho, XFontStyle.Underline); } //Cria alinhamento if (Alinhamento == "Left") { gfx.DrawString(Texto, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.TopLeft); } else if (Alinhamento == "Center") { gfx.DrawString(Texto, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.TopCenter); } else if (Alinhamento == "Right") { gfx.DrawString(Texto, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.TopRight); } //salvar documento outputDocument.Save(caminhoDestino); Resultado = true; } //Verifica as Excepções apanhadas catch (ExceptionDadosInvalidos erro) { throw new ExceptionDadosInvalidos(erro); } catch (ExceptionFileNotFound erro) { throw new ExceptionFileNotFound(erro); } catch (DllNotFoundException erro) { Mensagem = erro.Message; throw new DllNotFoundException(erro.Message); } } //Propriedade do atributo public string FileOrigem2 { get; set; } //Propriedade do atributo public string PathDestino { get => _pathDestino; set => _pathDestino = value; } //Propriedade do atributo public string FileDestino { get => _fileDestino; set => _fileDestino = value; } //Propriedade do atributo public string PathDestino2 { get; set; } //Propriedade do atributo public string FileDestino2 { get; set; } //Propriedade do atributo public int NumPages { get; set; } //Propriedade do atributo public int Page { get; set; } //Propriedade do atributo public string Texto { get => _texto; set => _texto = value; } //Propriedade do atributo public int AddPosition { get; set; } //Propriedade do atributo public string Fonte { get => _fonte; set => _fonte = value; } //Propriedade do atributo public string Alinhamento { get => _alinhamento; set => _alinhamento = value; } //Propriedade do atributo public string Estilo { get => _estilo; set => _estilo = value; } //Propriedade do atributo public int Tamanho { get => _tamanho; set => _tamanho = value; } //Propriedade do atributo public string PathOrigem { get; set; } //Propriedade do atributo public string FileOrigem { get; set; } //Propriedade do atributo public string PathOrigem2 { get; set; } //Propriedade do atributo public bool Resultado { get => _resultado; set => _resultado = value; } //Propriedade do atributo public string Mensagem { get=> _mensagem; set => _mensagem = value; } //Propriedade do atributo public string Erros { get => _erro; set=> _erro = value; } } }
34.787671
125
0.478047
[ "MIT" ]
Cheebaccas-Team/scarif-ds-1
Scarif DS-1/modulos/Create/CreateMod.cs
10,169
C#