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 Microsoft.Identity.Client; using System; using System.Collections.Generic; using System.Linq; using System.Security; namespace Liberator.RESTore.Access { /// <summary> /// Base class for retrieving access tokens /// </summary> public class AzureToken : IToken { /// <summary> /// The name of the user for the access token. /// </summary> public string UserName { get; set; } /// <summary> /// The password for the user /// </summary> public string Password { get; set; } /// <summary> /// The collection of scopes to be used /// </summary> public List<string> Scopes { get; set; } /// <summary> /// The ID for the client making the request. /// </summary> public string ClientId { get; set; } /// <summary> /// Authority of the security token service (STS). /// </summary> public string Authority { get; set; } /// <summary> /// The result of ther authentication call /// </summary> public AuthenticationResult AuthenticationResult { get; set; } /// <summary> /// The auth token returned /// </summary> public string AuthToken { get; set; } /// <summary> /// Default constructor /// </summary> public AzureToken() { Scopes = new List<string>(); } /// <summary> /// Adds a scope to the object. /// </summary> /// <param name="scope">The scope strinf to add.</param> public void AddScope(string scope) { Scopes.Add(scope); } /// <summary> /// Adds a range of scopes to the object. /// </summary> /// <param name="scopes">The collection of scope strings.</param> public void AddScopes(IEnumerable<string> scopes) { Scopes.AddRange(scopes); } /// <summary> /// Gets the access token for an endpoint using Azure STS /// </summary> /// <param name="userName">Name of the user requesting the token.</param> /// <param name="password">Password of the user requesting the token.</param> /// <param name="scopes">Scopes requested to access a protected API.</param> /// <param name="clientId">The ID for the client making the request.</param> /// <param name="authority">Authority of the security token service (STS).</param> /// <returns>The auth token as a string</returns> public string GetAccessToken(string userName, string password, string[] scopes, string clientId, string authority) { UserName = userName; Password = password; Scopes = scopes.ToList(); AuthToken = RetrieveToken(clientId, authority); return AuthToken; } /// <summary> /// Retrieves a token from Azure /// </summary> /// <param name="clientId">The ID for the client making the request.</param> /// <param name="authority">Authority of the security token service (STS).</param> /// <returns>The access token as a string.</returns> private string RetrieveToken(string clientId, string authority) { try { PublicClientApplication publicClientApplication = new PublicClientApplication(clientId, authority); var securePassword = new SecureString(); foreach (char c in Password) { securePassword.AppendChar(c); } AuthenticationResult = publicClientApplication.AcquireTokenByUsernamePasswordAsync(Scopes.ToArray(), UserName, securePassword).Result; return AuthenticationResult.AccessToken; } catch (Exception ex) { throw new RESToreException("Could not retrieve the tokemn as requested", ex); } } } }
34.042373
150
0.568086
[ "MIT" ]
LiberatorTestTools/RESTore
RESTore/Access/AzureToken.cs
4,019
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("dizileri")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("dizileri")] [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("8b6f22d5-a78a-42cd-a69f-d83828760cee")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.540541
84
0.743701
[ "MIT" ]
coshkun/ISMK.91114.Programming-Techniques
shares/shared-projects/dizileri/dizileri/Properties/AssemblyInfo.cs
1,392
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { Rigidbody m_Rigidbody; public float m_Thrust = 10f; public float speed = 1; bool isOnGround; bool jump_pressedLastFrame; // Start is called before the first frame update void Start() { m_Rigidbody = GetComponent<Rigidbody>(); isOnGround = true; jump_pressedLastFrame = false; } private void UpdateMovement() { if(Input.GetKey("d")){ print("D is held down"); gameObject.transform.position = gameObject.transform.position + new Vector3(speed *Time.deltaTime,0,0); } if(Input.GetKey("a")){ print("A is held down"); gameObject.transform.position = gameObject.transform.position + new Vector3(-speed *Time.deltaTime,0,0); } if(isOnGround == true) { if(!jump_pressedLastFrame && Input.GetKey("w")) { //isOnGround = false; m_Rigidbody.AddForce(new Vector3(0,1,0) * m_Thrust, ForceMode.Impulse); } } else { //print("Not on ground!"); } jump_pressedLastFrame = Input.GetKey("w"); } private void UpdateSound() { AudioSource sound = gameObject.GetComponent(typeof(AudioSource)) as AudioSource; bool right = Input.GetKey("d"); bool left = Input.GetKey("a"); bool movement = (right || left) && !(right && left); if(movement && isOnGround) { if(!sound.isPlaying) sound.Play(); } else { if(sound.isPlaying) sound.Stop(); } } // Update is called once per frame void Update() { UpdateMovement(); UpdateSound(); } private void OnTriggerEnter(Collider other) { print("enter"); isOnGround = true; } private void OnTriggerExit(Collider other) { print("exit"); isOnGround = false; } }
25.317647
121
0.539498
[ "MIT" ]
Intreix/P-SeminarSG
Assets/Player.cs
2,152
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YourNameHere { public class Definitions { public class Lettere { public string Letters { get; set; } public string Color { get; set; } public bool NumPad { get; set; } } public class AllLetters { public List<Lettere> Text = new List<Lettere>(); } } }
20.333333
60
0.577869
[ "MIT" ]
bonny1992/YourNameHere
YourNameHere/Definitions.cs
490
C#
using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Xunit; namespace NLog.Extensions.Logging.Tests { public class CustomBeginScopeTest : NLogTestBase { [Fact] public void TestNonSerializableSayHello() { var runner = GetRunner<CustomBeginScopeTestRunner>(); var target = new Targets.MemoryTarget { Layout = "${message} ${mdlc:World}. Welcome ${ndlc}" }; ConfigureNLog(target); runner.SayHello().Wait(); Assert.Single(target.Logs); Assert.Equal("Hello Earth. Welcome Earth People", target.Logs[0]); } [Fact] public void TestNonSerializableSayHelloWithScope() { var runner = GetRunner<CustomBeginScopeTestRunner>(new NLogProviderOptions { IncludeScopes = false }); var target = new Targets.MemoryTarget { Layout = "${message} ${mdlc:World}. Welcome ${ndlc}" }; ConfigureNLog(target); runner.SayHello().Wait(); Assert.Single(target.Logs); Assert.Equal("Hello . Welcome ", target.Logs[0]); } [Fact] public void TestNonSerializableSayHi() { var runner = GetRunner<CustomBeginScopeTestRunner>(); var target = new Targets.MemoryTarget { Layout = "${message} ${mdlc:World}. Welcome ${ndlc}" }; ConfigureNLog(target); var scopeString = runner.SayHi().Result; Assert.Single(target.Logs); Assert.Equal("Hi Earth. Welcome Earth People", target.Logs[0]); // Assert.Equal("Earth People", scopeString); <-- Bug https://github.com/aspnet/Logging/issues/893 } [Fact] public void TestNonSerializableSayHiToEarth() { var runner = GetRunner<CustomBeginScopeTestRunner>(); var target = new Targets.MemoryTarget { Layout = "${message} ${mdlc:Planet}. Welcome to the ${mdlc:Galaxy}" }; ConfigureNLog(target); var scopeString = runner.SayHiToEarth().Result; Assert.Single(target.Logs); Assert.Equal("Hi Earth. Welcome to the Milky Way", target.Logs[0]); } [Fact] public void TestNonSerializableSayNothing() { var runner = GetRunner<CustomBeginScopeTestRunner>(); var target = new Targets.MemoryTarget { Layout = "${message}" }; ConfigureNLog(target); runner.SayNothing().Wait(); Assert.Single(target.Logs); Assert.Equal("Nothing", target.Logs[0]); } public class CustomBeginScopeTestRunner { private readonly ILogger<CustomBeginScopeTestRunner> _logger; public CustomBeginScopeTestRunner(ILogger<CustomBeginScopeTestRunner> logger) { _logger = logger; } public async Task SayHello() { using (_logger.BeginScope(new ActionLogScope("Earth"))) { await Task.Yield(); _logger.LogInformation("Hello"); } } public async Task<string> SayHi() { using (var scopeState = _logger.BeginScope("{World} People", "Earth")) { await Task.Yield(); _logger.LogInformation("Hi"); return scopeState.ToString(); } } public async Task<string> SayHiToEarth() { using (var scopeState = _logger.BeginScope("{Planet} in {Galaxy}", "Earth", "Milky Way")) { await Task.Yield(); _logger.LogInformation("Hi"); return scopeState.ToString(); } } public async Task SayNothing() { using (var scopeState = _logger.BeginScope(new Dictionary<string,string>())) { await Task.Yield(); _logger.LogInformation("Nothing"); } } } private class ActionLogScope : IReadOnlyList<KeyValuePair<string, object>> { private readonly string _world; public ActionLogScope(string world) { if (world == null) { throw new ArgumentNullException(nameof(world)); } _world = world; } public KeyValuePair<string, object> this[int index] { get { if (index == 0) { return new KeyValuePair<string, object>("World", _world); } throw new IndexOutOfRangeException(nameof(index)); } } public int Count => 1; public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { for (var i = 0; i < Count; ++i) { yield return this[i]; } } public override string ToString() { // We don't include the _action.Id here because it's just an opaque guid, and if // you have text logging, you can already use the requestId for correlation. return string.Concat(_world, " People"); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
34.506024
122
0.517633
[ "BSD-2-Clause" ]
GitHubPang/NLog.Extensions.Logging
test/NLog.Extensions.Logging.Tests/CustomBeginScopeTest.cs
5,730
C#
// <auto-generated /> // Copyright (c) Six Labors and contributors. // See LICENSE for more details. #if !SUPPORTS_SERIALIZATION namespace System { /// <summary> /// Indicates that a class can be serialized. This class cannot be inherited. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)] internal sealed class SerializableAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="SerializableAttribute"/> class. /// </summary> public SerializableAttribute() { } } } #endif
30.409091
141
0.68012
[ "Apache-2.0" ]
SixLabors/ZlibStream
src/ZlibStream/SerializableAttribute.cs
669
C#
namespace Microsoft.BotBuilderSamples { public class UserProfile { public string Name { get; set; } public int? Age { get; set; } public string Date { get; set; } } }
17.166667
40
0.57767
[ "MIT" ]
AdsTable/BotBuilder-Samples
samples/csharp_dotnetcore/44.prompt-users-for-input/UserProfile.cs
208
C#
using Ryujinx.Common.Logging; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.Gpu; using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvMap; using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger { class SurfaceFlinger : IConsumerListener, IDisposable { private const int TargetFps = 60; private Switch _device; private Dictionary<long, Layer> _layers; private bool _isRunning; private Thread _composerThread; private Stopwatch _chrono; private long _ticks; private long _ticksPerFrame; private int _swapInterval; private readonly object Lock = new object(); public long LastId { get; private set; } private class Layer { public int ProducerBinderId; public IGraphicBufferProducer Producer; public BufferItemConsumer Consumer; public BufferQueueCore Core; public long Owner; } private class TextureCallbackInformation { public Layer Layer; public BufferItem Item; } public SurfaceFlinger(Switch device) { _device = device; _layers = new Dictionary<long, Layer>(); LastId = 0; _composerThread = new Thread(HandleComposition) { Name = "SurfaceFlinger.Composer" }; _chrono = new Stopwatch(); _ticks = 0; UpdateSwapInterval(1); _composerThread.Start(); } private void UpdateSwapInterval(int swapInterval) { _swapInterval = swapInterval; // If the swap interval is 0, Game VSync is disabled. if (_swapInterval == 0) { _ticksPerFrame = 1; } else { _ticksPerFrame = Stopwatch.Frequency / (TargetFps / _swapInterval); } } public IGraphicBufferProducer OpenLayer(long pid, long layerId) { bool needCreate; lock (Lock) { needCreate = GetLayerByIdLocked(layerId) == null; } if (needCreate) { CreateLayerFromId(pid, layerId); } return GetProducerByLayerId(layerId); } public IGraphicBufferProducer CreateLayer(long pid, out long layerId) { layerId = 1; lock (Lock) { foreach (KeyValuePair<long, Layer> pair in _layers) { if (pair.Key >= layerId) { layerId = pair.Key + 1; } } } CreateLayerFromId(pid, layerId); return GetProducerByLayerId(layerId); } private void CreateLayerFromId(long pid, long layerId) { lock (Lock) { Logger.Info?.Print(LogClass.SurfaceFlinger, $"Creating layer {layerId}"); BufferQueueCore core = BufferQueue.CreateBufferQueue(_device, pid, out BufferQueueProducer producer, out BufferQueueConsumer consumer); _layers.Add(layerId, new Layer { ProducerBinderId = HOSBinderDriverServer.RegisterBinderObject(producer), Producer = producer, Consumer = new BufferItemConsumer(_device, consumer, 0, -1, false, this), Core = core, Owner = pid }); LastId = layerId; } } public bool CloseLayer(long layerId) { lock (Lock) { Layer layer = GetLayerByIdLocked(layerId); if (layer != null) { HOSBinderDriverServer.UnregisterBinderObject(layer.ProducerBinderId); } return _layers.Remove(layerId); } } private Layer GetLayerByIdLocked(long layerId) { foreach (KeyValuePair<long, Layer> pair in _layers) { if (pair.Key == layerId) { return pair.Value; } } return null; } public IGraphicBufferProducer GetProducerByLayerId(long layerId) { lock (Lock) { Layer layer = GetLayerByIdLocked(layerId); if (layer != null) { return layer.Producer; } } return null; } private void HandleComposition() { _isRunning = true; while (_isRunning) { _ticks += _chrono.ElapsedTicks; _chrono.Restart(); if (_ticks >= _ticksPerFrame) { Compose(); _device.System?.SignalVsync(); _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame); } // Sleep the minimal amount of time to avoid being too expensive. Thread.Sleep(1); } } public void Compose() { lock (Lock) { // TODO: support multilayers (& multidisplay ?) if (_layers.Count == 0) { return; } Layer layer = GetLayerByIdLocked(LastId); Status acquireStatus = layer.Consumer.AcquireBuffer(out BufferItem item, 0); if (acquireStatus == Status.Success) { // If device vsync is disabled, reflect the change. if (!_device.EnableDeviceVsync) { if (_swapInterval != 0) { UpdateSwapInterval(0); } } else if (item.SwapInterval != _swapInterval) { UpdateSwapInterval(item.SwapInterval); } PostFrameBuffer(layer, item); } else if (acquireStatus != Status.NoBufferAvailaible && acquireStatus != Status.InvalidOperation) { throw new InvalidOperationException(); } } } private void PostFrameBuffer(Layer layer, BufferItem item) { int frameBufferWidth = item.GraphicBuffer.Object.Width; int frameBufferHeight = item.GraphicBuffer.Object.Height; int nvMapHandle = item.GraphicBuffer.Object.Buffer.Surfaces[0].NvMapHandle; if (nvMapHandle == 0) { nvMapHandle = item.GraphicBuffer.Object.Buffer.NvMapId; } int bufferOffset = item.GraphicBuffer.Object.Buffer.Surfaces[0].Offset; NvMapHandle map = NvMapDeviceFile.GetMapFromHandle(layer.Owner, nvMapHandle); ulong frameBufferAddress = (ulong)(map.Address + bufferOffset); Format format = ConvertColorFormat(item.GraphicBuffer.Object.Buffer.Surfaces[0].ColorFormat); int bytesPerPixel = format == Format.B5G6R5Unorm || format == Format.R4G4B4A4Unorm ? 2 : 4; int gobBlocksInY = 1 << item.GraphicBuffer.Object.Buffer.Surfaces[0].BlockHeightLog2; // Note: Rotation is being ignored. Rect cropRect = item.Crop; bool flipX = item.Transform.HasFlag(NativeWindowTransform.FlipX); bool flipY = item.Transform.HasFlag(NativeWindowTransform.FlipY); ImageCrop crop = new ImageCrop( cropRect.Left, cropRect.Right, cropRect.Top, cropRect.Bottom, flipX, flipY); TextureCallbackInformation textureCallbackInformation = new TextureCallbackInformation { Layer = layer, Item = item, }; _device.Gpu.Window.EnqueueFrameThreadSafe( frameBufferAddress, frameBufferWidth, frameBufferHeight, 0, false, gobBlocksInY, format, bytesPerPixel, crop, AcquireBuffer, ReleaseBuffer, textureCallbackInformation); } private void ReleaseBuffer(object obj) { ReleaseBuffer((TextureCallbackInformation)obj); } private void ReleaseBuffer(TextureCallbackInformation information) { AndroidFence fence = AndroidFence.NoFence; information.Layer.Consumer.ReleaseBuffer(information.Item, ref fence); } private void AcquireBuffer(GpuContext ignored, object obj) { AcquireBuffer((TextureCallbackInformation)obj); } private void AcquireBuffer(TextureCallbackInformation information) { information.Item.Fence.WaitForever(_device.Gpu); } public static Format ConvertColorFormat(ColorFormat colorFormat) { return colorFormat switch { ColorFormat.A8B8G8R8 => Format.R8G8B8A8Unorm, ColorFormat.X8B8G8R8 => Format.R8G8B8A8Unorm, ColorFormat.R5G6B5 => Format.B5G6R5Unorm, ColorFormat.A8R8G8B8 => Format.B8G8R8A8Unorm, ColorFormat.A4B4G4R4 => Format.R4G4B4A4Unorm, _ => throw new NotImplementedException($"Color Format \"{colorFormat}\" not implemented!"), }; } public void Dispose() { _isRunning = false; foreach (Layer layer in _layers.Values) { layer.Core.PrepareForExit(); } } public void OnFrameAvailable(ref BufferItem item) { _device.Statistics.RecordGameFrameTime(); } public void OnFrameReplaced(ref BufferItem item) { _device.Statistics.RecordGameFrameTime(); } public void OnBuffersReleased() {} } }
29.059946
151
0.509892
[ "MIT" ]
derparb/h
Ryujinx.HLE/HOS/Services/SurfaceFlinger/SurfaceFlinger.cs
10,667
C#
using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; namespace FoxTool.Fox.Types.Structs { public class FoxMatrix4 : FoxStruct { public float Row1Value1 { get; set; } public float Row1Value2 { get; set; } public float Row1Value3 { get; set; } public float Row1Value4 { get; set; } public float Row2Value1 { get; set; } public float Row2Value2 { get; set; } public float Row2Value3 { get; set; } public float Row2Value4 { get; set; } public float Row3Value1 { get; set; } public float Row3Value2 { get; set; } public float Row3Value3 { get; set; } public float Row3Value4 { get; set; } public float Row4Value1 { get; set; } public float Row4Value2 { get; set; } public float Row4Value3 { get; set; } public float Row4Value4 { get; set; } public override void Read(Stream input) { BinaryReader reader = new BinaryReader(input, Encoding.Default, true); Row1Value1 = reader.ReadSingle(); Row1Value2 = reader.ReadSingle(); Row1Value3 = reader.ReadSingle(); Row1Value4 = reader.ReadSingle(); Row2Value1 = reader.ReadSingle(); Row2Value2 = reader.ReadSingle(); Row2Value3 = reader.ReadSingle(); Row2Value4 = reader.ReadSingle(); Row3Value1 = reader.ReadSingle(); Row3Value2 = reader.ReadSingle(); Row3Value3 = reader.ReadSingle(); Row3Value4 = reader.ReadSingle(); Row4Value1 = reader.ReadSingle(); Row4Value2 = reader.ReadSingle(); Row4Value3 = reader.ReadSingle(); Row4Value4 = reader.ReadSingle(); } public override void Write(Stream output) { BinaryWriter writer = new BinaryWriter(output, Encoding.Default, true); writer.Write(Row1Value1); writer.Write(Row1Value2); writer.Write(Row1Value3); writer.Write(Row1Value4); writer.Write(Row2Value1); writer.Write(Row2Value2); writer.Write(Row2Value3); writer.Write(Row2Value4); writer.Write(Row3Value1); writer.Write(Row3Value2); writer.Write(Row3Value3); writer.Write(Row3Value4); writer.Write(Row4Value1); writer.Write(Row4Value2); writer.Write(Row4Value3); writer.Write(Row4Value4); } public override int Size() { return 16*sizeof (float); } public override void ResolveStringLiterals(FoxLookupTable lookupTable) { } public override void CalculateHashes() { } public override void CollectStringLookupLiterals(List<FoxStringLookupLiteral> literals) { } public override void ReadXml(XmlReader reader) { var isEmptyElement = reader.IsEmptyElement; reader.ReadStartElement("value"); if (isEmptyElement == false) { Row1Value1 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column1")); Row1Value2 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column2")); Row1Value3 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column3")); Row1Value4 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column4")); reader.ReadStartElement("Row1"); Row2Value1 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column1")); Row2Value2 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column2")); Row2Value3 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column3")); Row2Value4 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column4")); reader.ReadStartElement("Row2"); Row3Value1 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column1")); Row3Value2 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column2")); Row3Value3 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column3")); Row3Value4 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column4")); reader.ReadStartElement("Row3"); Row4Value1 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column1")); Row4Value2 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column2")); Row4Value3 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column3")); Row4Value4 = ExtensionMethods.ParseFloatRoundtrip(reader.GetAttribute("Column4")); reader.ReadStartElement("Row4"); reader.ReadEndElement(); } } public override void WriteXml(XmlWriter writer) { writer.WriteStartElement("Row1"); writer.WriteAttributeString("Column1", Row1Value1.ToStringRoundtrip()); writer.WriteAttributeString("Column2", Row1Value2.ToStringRoundtrip()); writer.WriteAttributeString("Column3", Row1Value3.ToStringRoundtrip()); writer.WriteAttributeString("Column4", Row1Value4.ToStringRoundtrip()); writer.WriteEndElement(); writer.WriteStartElement("Row2"); writer.WriteAttributeString("Column1", Row2Value1.ToStringRoundtrip()); writer.WriteAttributeString("Column2", Row2Value2.ToStringRoundtrip()); writer.WriteAttributeString("Column3", Row2Value3.ToStringRoundtrip()); writer.WriteAttributeString("Column4", Row2Value4.ToStringRoundtrip()); writer.WriteEndElement(); writer.WriteStartElement("Row3"); writer.WriteAttributeString("Column1", Row3Value1.ToStringRoundtrip()); writer.WriteAttributeString("Column2", Row3Value2.ToStringRoundtrip()); writer.WriteAttributeString("Column3", Row3Value3.ToStringRoundtrip()); writer.WriteAttributeString("Column4", Row3Value4.ToStringRoundtrip()); writer.WriteEndElement(); writer.WriteStartElement("Row4"); writer.WriteAttributeString("Column1", Row4Value1.ToStringRoundtrip()); writer.WriteAttributeString("Column2", Row4Value2.ToStringRoundtrip()); writer.WriteAttributeString("Column3", Row4Value3.ToStringRoundtrip()); writer.WriteAttributeString("Column4", Row4Value4.ToStringRoundtrip()); writer.WriteEndElement(); } public override string ToString() { return string.Format( "Row1Value1: {0}, Row1Value2: {1}, Row1Value3: {2}, Row1Value4: {3}, Row2Value1: {4}, Row2Value2: {5}, Row2Value3: {6}, Row2Value4: {7}, Row3Value1: {8}, Row3Value3: {9}, Row3Value2: {10}, Row3Value4: {11}, Row4Value1: {12}, Row4Value2: {13}, Row4Value3: {14}, Row4Value4: {15}", Row1Value1, Row1Value2, Row1Value3, Row1Value4, Row2Value1, Row2Value2, Row2Value3, Row2Value4, Row3Value1, Row3Value3, Row3Value2, Row3Value4, Row4Value1, Row4Value2, Row4Value3, Row4Value4); } } }
49.168831
300
0.616086
[ "MIT" ]
Atvaark/FoxTool
FoxTool/Fox/Types/Structs/FoxMatrix4.cs
7,574
C#
using System.Collections.Generic; using Leak.Bencoding; using Leak.Common; using Leak.Events; using Leak.Extensions; using Leak.Peer.Coordinator.Core; namespace Leak.Peer.Coordinator { public class CoordinatorFacts { private readonly MoreContainer more; private MetafileVerified metadata; private Bitfield mine; public CoordinatorFacts() { more = new MoreContainer(); } public Bitfield Bitfield { get { return mine; } } public void Install(IReadOnlyCollection<MorePlugin> plugins) { foreach (MorePlugin plugin in plugins) { plugin.Install(more); } } public void Handle(MetafileVerified data) { metadata = data; } public void Handle(DataVerified data) { mine = data.Bitfield; } public Bitfield ApplyHave(Bitfield other, int piece) { if (other == null && metadata?.Metainfo != null) { other = new Bitfield(metadata.Metainfo.Pieces.Length); } if (other != null && other.Length > piece) { other[piece] = true; } return other; } public Bitfield ApplyBitfield(Bitfield other, Bitfield received) { if (metadata?.Metainfo != null) { received = new Bitfield(metadata.Metainfo.Pieces.Length, received); } return received; } public Extended GetHandshake() { BencodedValue encoded = more.Encode(metadata?.Size); byte[] binary = Bencoder.Encode(encoded); return new Extended(0, binary); } public string[] GetExtensions() { return more.ToArray(); } public string Translate(byte id, out MoreHandler handler) { string code = more.Translate(id); handler = more.GetHandler(code); return code; } public MoreHandler GetHandler(string code) { return more.GetHandler(code); } public IEnumerable<MoreHandler> AllHandlers() { return more.AllHandlers(); } } }
23.65
83
0.527696
[ "MIT" ]
amacal/leak
sources/Leak.Glue/CoordinatorFacts.cs
2,367
C#
using Abp.Application.Services.Dto; using Abp.AutoMapper; using Abp.Authorization; namespace Jewellery.Roles.Dto { [AutoMapFrom(typeof(Permission))] public class PermissionDto : EntityDto<long> { public string Name { get; set; } public string DisplayName { get; set; } public string Description { get; set; } } }
20.941176
48
0.671348
[ "MIT" ]
dedavidsilwal/JewelleryAbp
aspnet-core/src/Jewellery.Application/Roles/Dto/PermissionDto.cs
356
C#
// -------------------------------------------------------------------------------------------------- // <copyright file = "AssemblyInfo.cs" company="Nino Crudele"> // Copyright (c) 2013 - 2015 Nino Crudele. All Rights Reserved. // </copyright> // <summary> // The MIT License (MIT) // // Copyright (c) 2013 - 2015 Nino Crudele // Blog: http://ninocrudele.me // // 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. // </summary> // -------------------------------------------------------------------------------------------------- using System.Reflection; 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("EventHubsTrigger")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EventHubsTrigger")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1c25fa46-e6cc-4d58-a89c-221c7185ee65")] // 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")]
43.014706
102
0.69094
[ "MIT" ]
HydAu/GrabCasterSDKTriggers
EventHubsTrigger/Properties/AssemblyInfo.cs
2,928
C#
// <auto-generated /> // Built from: hl7.fhir.r5.core version: 4.6.0 // Option: "NAMESPACE" = "fhirCsR5" using fhirCsR5.Models; namespace fhirCsR5.ValueSets { /// <summary> /// This value set is suitable for use with the provenance resource. It is derived from, but not compatible with, the HL7 v3 Purpose of use Code system. /// </summary> public static class NhinPurposeofuseCodes { /// <summary> /// Disclosures about victims of abuse, neglect or domestic violence. /// </summary> public static readonly Coding Abuse = new Coding { Code = "ABUSE", Display = "Abuse", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Disclosures for insurance or disability coverage determination /// </summary> public static readonly Coding Coverage = new Coding { Code = "COVERAGE", Display = "Coverage", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Uses and disclosures about decedents. /// </summary> public static readonly Coding Deceased = new Coding { Code = "DECEASED", Display = "Deceased", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Use and disclosure for facility directories /// </summary> public static readonly Coding Directory = new Coding { Code = "DIRECTORY", Display = "Directory", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Use and disclosures for disaster relief purposes. /// </summary> public static readonly Coding Disaster = new Coding { Code = "DISASTER", Display = "Disaster", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Uses and disclosures for cadaveric organ, eye or tissue donation purposes /// </summary> public static readonly Coding Donation = new Coding { Code = "DONATION", Display = "Donation", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Permission cannot practicably be provided because of the individual's incapacity or an emergency. /// </summary> public static readonly Coding Emergency = new Coding { Code = "EMERGENCY", Display = "Emergency", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Disclose to a family member, other relative, or a close personal friend of the individual /// </summary> public static readonly Coding Family = new Coding { Code = "FAMILY", Display = "Family", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Fraud detection /// </summary> public static readonly Coding Fraud = new Coding { Code = "FRAUD", Display = "Fraud", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Uses and disclosures for specialized government functions. /// </summary> public static readonly Coding Government = new Coding { Code = "GOVERNMENT", Display = "Government", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Disclosures for judicial and administrative proceedings. /// </summary> public static readonly Coding Judicial = new Coding { Code = "JUDICIAL", Display = "Judicial", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Disclosures for law enforcement purposes. /// </summary> public static readonly Coding LawEnforcement = new Coding { Code = "LAW", Display = "Law Enforcement", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Use or disclosure by the covered entity to defend itself in a legal action /// </summary> public static readonly Coding Legal = new Coding { Code = "LEGAL", Display = "Legal", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Marketing /// </summary> public static readonly Coding Marketing = new Coding { Code = "MARKETING", Display = "Marketing", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Healthcare Operations /// </summary> public static readonly Coding Operations = new Coding { Code = "OPERATIONS", Display = "Operations", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Uses and disclosures for health oversight activities. /// </summary> public static readonly Coding Oversight = new Coding { Code = "OVERSIGHT", Display = "Oversight", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Payment /// </summary> public static readonly Coding Payment = new Coding { Code = "PAYMENT", Display = "Payment", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Uses and disclosures with the individual present. /// </summary> public static readonly Coding Present = new Coding { Code = "PRESENT", Display = "Present", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Use or disclosure of Psychotherapy Notes /// </summary> public static readonly Coding Psychotherapy = new Coding { Code = "PSYCHOTHERAPY", Display = "Psychotherapy", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Uses and disclosures for public health activities. /// </summary> public static readonly Coding PublicHealth = new Coding { Code = "PUBLICHEALTH", Display = "Public Health", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Request of the Individual /// </summary> public static readonly Coding Request = new Coding { Code = "REQUEST", Display = "Request", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Uses and disclosures for research purposes. /// </summary> public static readonly Coding Research = new Coding { Code = "RESEARCH", Display = "Research", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// System Administration /// </summary> public static readonly Coding Sysadmin = new Coding { Code = "SYSADMIN", Display = "Sysadmin", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Uses and disclosures to avert a serious threat to health or safety. /// </summary> public static readonly Coding Threat = new Coding { Code = "THREAT", Display = "Threat", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Use or disclosure by the covered entity for its own training programs /// </summary> public static readonly Coding Training = new Coding { Code = "TRAINING", Display = "Training", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Treatment /// </summary> public static readonly Coding Treatment = new Coding { Code = "TREATMENT", Display = "Treatment", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Disclosures for workers' compensation. /// </summary> public static readonly Coding WorkerQuoteSComp = new Coding { Code = "WORKERSCOMP", Display = "Worker's Comp", System = "http://healthit.gov/nhin/purposeofuse" }; /// <summary> /// Literal for code: Abuse /// </summary> public const string LiteralAbuse = "ABUSE"; /// <summary> /// Literal for code: Coverage /// </summary> public const string LiteralCoverage = "COVERAGE"; /// <summary> /// Literal for code: Deceased /// </summary> public const string LiteralDeceased = "DECEASED"; /// <summary> /// Literal for code: Directory /// </summary> public const string LiteralDirectory = "DIRECTORY"; /// <summary> /// Literal for code: Disaster /// </summary> public const string LiteralDisaster = "DISASTER"; /// <summary> /// Literal for code: Donation /// </summary> public const string LiteralDonation = "DONATION"; /// <summary> /// Literal for code: Emergency /// </summary> public const string LiteralEmergency = "EMERGENCY"; /// <summary> /// Literal for code: Family /// </summary> public const string LiteralFamily = "FAMILY"; /// <summary> /// Literal for code: Fraud /// </summary> public const string LiteralFraud = "FRAUD"; /// <summary> /// Literal for code: Government /// </summary> public const string LiteralGovernment = "GOVERNMENT"; /// <summary> /// Literal for code: Judicial /// </summary> public const string LiteralJudicial = "JUDICIAL"; /// <summary> /// Literal for code: LawEnforcement /// </summary> public const string LiteralLawEnforcement = "LAW"; /// <summary> /// Literal for code: Legal /// </summary> public const string LiteralLegal = "LEGAL"; /// <summary> /// Literal for code: Marketing /// </summary> public const string LiteralMarketing = "MARKETING"; /// <summary> /// Literal for code: Operations /// </summary> public const string LiteralOperations = "OPERATIONS"; /// <summary> /// Literal for code: Oversight /// </summary> public const string LiteralOversight = "OVERSIGHT"; /// <summary> /// Literal for code: Payment /// </summary> public const string LiteralPayment = "PAYMENT"; /// <summary> /// Literal for code: Present /// </summary> public const string LiteralPresent = "PRESENT"; /// <summary> /// Literal for code: Psychotherapy /// </summary> public const string LiteralPsychotherapy = "PSYCHOTHERAPY"; /// <summary> /// Literal for code: PublicHealth /// </summary> public const string LiteralPublicHealth = "PUBLICHEALTH"; /// <summary> /// Literal for code: Request /// </summary> public const string LiteralRequest = "REQUEST"; /// <summary> /// Literal for code: Research /// </summary> public const string LiteralResearch = "RESEARCH"; /// <summary> /// Literal for code: Sysadmin /// </summary> public const string LiteralSysadmin = "SYSADMIN"; /// <summary> /// Literal for code: Threat /// </summary> public const string LiteralThreat = "THREAT"; /// <summary> /// Literal for code: Training /// </summary> public const string LiteralTraining = "TRAINING"; /// <summary> /// Literal for code: Treatment /// </summary> public const string LiteralTreatment = "TREATMENT"; /// <summary> /// Literal for code: WorkerQuoteSComp /// </summary> public const string LiteralWorkerQuoteSComp = "WORKERSCOMP"; }; }
28.375635
154
0.603757
[ "MIT" ]
microsoft-healthcare-madison/argonaut-subscription-server-proxy
argonaut-subscription-server-proxy/Fhir/R5/ValueSets/NhinPurposeofuse.cs
11,180
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.Tye.Hosting.Diagnostics { public class ReplicaInfo { public ReplicaInfo( Func<IReadOnlyList<Process>, Process?> selector, string assemblyName, string service, string replica, ConcurrentDictionary<string, string> metrics) { Selector = selector; AssemblyName = assemblyName; Service = service; Replica = replica; Metrics = metrics; } public Func<IReadOnlyList<Process>, Process?> Selector { get; } public string AssemblyName { get; } public string Service { get; } public string Replica { get; } // TODO - this isn't a great way to pass metrics around. public ConcurrentDictionary<string, string> Metrics { get; } } }
29.05
71
0.635972
[ "MIT" ]
AlecPapierniak/tye
src/Microsoft.Tye.Hosting.Diagnostics/ReplicaInfo.cs
1,164
C#
namespace BuckarooSdk.Services.Sofort { public class SofortPayRemainderResponse { /// <summary> /// IBAN bank account number of the customer. /// </summary> public string CustomerIBAN { get; set; } } }
19.363636
47
0.699531
[ "MIT" ]
buckaroo-it/BuckarooSdk_DotNet
BuckarooSdk/Services/Sofort/SofortPayRemainderResponse.cs
213
C#
 namespace RohBot.Rooms.Script.Commands { public class Default : Command { public override string Type => "script_"; public override string Format(CommandTarget target, string type) { if (!target.IsRoom || !(target.Room is ScriptRoom)) return ""; var scriptRoom = (ScriptRoom)target.Room; ScriptRoom.CommandHandler command; return scriptRoom.Commands.TryGetValue(type, out command) ? command.Format : null; } public override void Handle(CommandTarget target, string type, string[] parameters) { if (!target.IsRoom || !(target.Room is ScriptRoom)) return; var scriptRoom = (ScriptRoom)target.Room; ScriptRoom.CommandHandler command; if (scriptRoom.Commands.TryGetValue(type, out command)) { scriptRoom.SafeInvoke(() => command.Handler(target, parameters)); return; } target.Send("Unknown command."); } } }
29.108108
94
0.572888
[ "MIT" ]
shadobaker/RohBot
RohBot/Rooms/Script/Commands/Default.cs
1,079
C#
namespace Parz.LambdaExpressions { public static class LambdaTokenType { /// <summary> /// A C# lambda expression type string. /// </summary> public static readonly TokenType LambdaExpression = nameof(LambdaExpression); } }
24.454545
85
0.635688
[ "MIT" ]
sj-freitas/parz
Parz.LambdaExpressions/LambdaTokenType.cs
271
C#
// // System.Data.OleDb.OleDbInfoMessageEventHandler // // Author: // Rodrigo Moya (rodrigo@ximian.com) // // Copyright (C) Rodrigo Moya, 2002 // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Data; using System.Data.Common; namespace System.Data.OleDb { #if !NET_2_0 [Serializable] #endif public delegate void OleDbInfoMessageEventHandler (object sender, OleDbInfoMessageEventArgs e); }
35.976744
97
0.734324
[ "MIT" ]
GrapeCity/pagefx
mono/mcs/class/System.Data/System.Data.OleDb/OleDbInfoMessageEventHandler.cs
1,547
C#
using System; namespace GiGraph.Dot.Output.Metadata { /// <summary> /// Assigns a DOT attribute value to an enumeration value. /// </summary> [AttributeUsage(AttributeTargets.Field)] public class DotAttributeValueAttribute : Attribute, IDotAttributeValueAttribute { /// <summary> /// Creates a new attribute instance. /// </summary> /// <param name="value"> /// The value of the DOT attribute. /// </param> public DotAttributeValueAttribute(string value) { Value = value; } /// <inheritdoc cref="IDotAttributeValueAttribute.Value" /> public string Value { get; } } }
28.32
84
0.587571
[ "MIT" ]
mariusz-schimke/GiGraph
src/GiGraph.Dot.Output/Metadata/DotAttributeValueAttribute.cs
708
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Nsxt.Inputs { public sealed class PolicyContextProfileUrlCategoryGetArgs : Pulumi.ResourceArgs { [Input("description")] public Input<string>? Description { get; set; } [Input("values", required: true)] private InputList<string>? _values; public InputList<string> Values { get => _values ?? (_values = new InputList<string>()); set => _values = value; } public PolicyContextProfileUrlCategoryGetArgs() { } } }
27.741935
88
0.648837
[ "ECL-2.0", "Apache-2.0" ]
nvpnathan/pulumi-nsxt
sdk/dotnet/Inputs/PolicyContextProfileUrlCategoryGetArgs.cs
860
C#
using System; using System.Threading.Tasks; using NServiceBus; using ServiceControl.TransportAdapter; class Program { static async Task Main() { Console.Title = "Samples.ServiceControl.RabbitMQAdapter.Adapter"; #region AdapterTransport var transportAdapter = new TransportAdapterConfig<RabbitMQTransport, RabbitMQTransport>("ServiceControl.RabbitMQ.Adapter"); transportAdapter.CustomizeServiceControlTransport( customization: transport => { transport.ConnectionString("host=localhost"); var delayedDelivery = transport.DelayedDelivery(); transport.UseConventionalRoutingTopology(); }); #endregion #pragma warning disable 618 #region EndpointSideConfig transportAdapter.CustomizeEndpointTransport( customization: transport => { transport.ConnectionString("host=localhost"); var delayedDelivery = transport.DelayedDelivery(); transport.UseDirectRoutingTopology(); }); #endregion #pragma warning restore 618 #region AdapterQueueConfiguration transportAdapter.EndpointSideErrorQueue = "adapter_error"; transportAdapter.EndpointSideAuditQueue = "adapter_audit"; transportAdapter.EndpointSideControlQueue = "adapter_Particular.ServiceControl"; transportAdapter.ServiceControlSideErrorQueue = "error"; transportAdapter.ServiceControlSideAuditQueue = "audit"; transportAdapter.ServiceControlSideControlQueue = "Particular.ServiceControl"; #endregion var adapter = TransportAdapter.Create(transportAdapter); await adapter.Start() .ConfigureAwait(false); Console.WriteLine("Press <enter> to shutdown adapter."); Console.ReadLine(); await adapter.Stop() .ConfigureAwait(false); } }
30.447761
113
0.644608
[ "Apache-2.0" ]
fourpastmidnight/docs.particular.net
samples/servicecontrol/adapter-rabbitmq-different-topologies/SCTransportAdapter_2/Adapter/Program.cs
1,976
C#
namespace MassTransit.Topology { using GreenPipes; /// <summary> /// A pipe builder used by topologies, which indicates whether the message type /// is either delegated (called from a sub-specification) or implemented (being called /// when the actual type is a subtype and this is an implemented type). /// </summary> /// <typeparam name="T">The pipe context type</typeparam> public interface ITopologyPipeBuilder<T> : IPipeBuilder<T> where T : class, PipeContext { /// <summary> /// If true, this is a delegated builder, and implemented message types /// and/or topology items should not be applied /// </summary> bool IsDelegated { get; } /// <summary> /// If true, this is a builder for implemented types, so don't go down /// the rabbit hole twice. /// </summary> bool IsImplemented { get; } /// <summary> /// Creates a new builder where the Delegated flag is true /// </summary> /// <returns></returns> ITopologyPipeBuilder<T> CreateDelegatedBuilder(); } }
32.685714
90
0.607517
[ "ECL-2.0", "Apache-2.0" ]
MathiasZander/ServiceFabricPerfomanceTest
src/MassTransit/Topology/ITopologyPipeBuilder.cs
1,146
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.dcdn.Transform; using Aliyun.Acs.dcdn.Transform.V20180115; using System.Collections.Generic; namespace Aliyun.Acs.dcdn.Model.V20180115 { public class BatchDeleteDcdnDomainConfigsRequest : RpcAcsRequest<BatchDeleteDcdnDomainConfigsResponse> { public BatchDeleteDcdnDomainConfigsRequest() : base("dcdn", "2018-01-15", "BatchDeleteDcdnDomainConfigs", "dcdn", "openAPI") { } private string functionNames; private string securityToken; private string domainNames; private string ownerAccount; private string action; private long? ownerId; private string accessKeyId; public string FunctionNames { get { return functionNames; } set { functionNames = value; DictionaryUtil.Add(QueryParameters, "FunctionNames", value); } } public string SecurityToken { get { return securityToken; } set { securityToken = value; DictionaryUtil.Add(QueryParameters, "SecurityToken", value); } } public string DomainNames { get { return domainNames; } set { domainNames = value; DictionaryUtil.Add(QueryParameters, "DomainNames", value); } } public string OwnerAccount { get { return ownerAccount; } set { ownerAccount = value; DictionaryUtil.Add(QueryParameters, "OwnerAccount", value); } } public string Action { get { return action; } set { action = value; DictionaryUtil.Add(QueryParameters, "Action", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public string AccessKeyId { get { return accessKeyId; } set { accessKeyId = value; DictionaryUtil.Add(QueryParameters, "AccessKeyId", value); } } public override BatchDeleteDcdnDomainConfigsResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext) { return BatchDeleteDcdnDomainConfigsResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
22.006849
128
0.663866
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-dcdn/Dcdn/Model/V20180115/BatchDeleteDcdnDomainConfigsRequest.cs
3,213
C#
using EV2.CodeAnalysis.Syntax; namespace EV2.CodeAnalysis.Binding { internal sealed class BoundIfStatement : BoundStatement { public BoundIfStatement(SyntaxNode syntax, BoundExpression condition, BoundStatement thenStatement, BoundStatement? elseStatement) : base(syntax) { Condition = condition; ThenStatement = thenStatement; ElseStatement = elseStatement; } public override BoundNodeKind Kind => BoundNodeKind.IfStatement; public BoundExpression Condition { get; } public BoundStatement ThenStatement { get; } public BoundStatement? ElseStatement { get; } } }
32.428571
138
0.678414
[ "MIT" ]
avishnyak/ev2
src/EV2/CodeAnalysis/Binding/BoundIfStatement.cs
681
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 devicefarm-2015-06-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DeviceFarm.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DeviceFarm.Model.Internal.MarshallTransformations { /// <summary> /// GetTestGridProject Request Marshaller /// </summary> public class GetTestGridProjectRequestMarshaller : IMarshaller<IRequest, GetTestGridProjectRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetTestGridProjectRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetTestGridProjectRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DeviceFarm"); string target = "DeviceFarm_20150623.GetTestGridProject"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-06-23"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetProjectArn()) { context.Writer.WritePropertyName("projectArn"); context.Writer.Write(publicRequest.ProjectArn); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static GetTestGridProjectRequestMarshaller _instance = new GetTestGridProjectRequestMarshaller(); internal static GetTestGridProjectRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetTestGridProjectRequestMarshaller Instance { get { return _instance; } } } }
35.485714
151
0.633655
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/DeviceFarm/Generated/Model/Internal/MarshallTransformations/GetTestGridProjectRequestMarshaller.cs
3,726
C#
// *********************************************************************** // Copyright (c) 2009 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using NUnit.Framework.Interfaces; using NUnit.TestData; using NUnit.TestUtilities; namespace NUnit.Framework.Assertions { [TestFixture] public class AssertWarnTests { [Test] public void AssertWarnWorksWithMessage() { ITestResult result = TestBuilder.RunTestCase( typeof(WarningFixture), "CallAssertWarnWithMessage"); Assert.AreEqual(ResultState.Warning, result.ResultState); Assert.AreEqual("MESSAGE", result.Message); } [Test] public void AssertWarnWorksWithMessageAndArgs() { ITestResult result = TestBuilder.RunTestCase( typeof(WarningFixture), "CallAssertWarnWithMessageAndArgs"); Assert.AreEqual(ResultState.Warning, result.ResultState); Assert.AreEqual("MESSAGE: 2+2=4", result.Message); } } }
39.071429
75
0.650366
[ "MIT" ]
jnm2/nunit
src/NUnitFramework/tests/Assertions/AssertWarnTests.cs
2,190
C#
using System; using Microsoft.Extensions.CommandLineUtils; using Paradigm.Services.CLI; namespace Paradigm.Services.Tests.Fixtures.Tests.CLI { public class NullableArguments { [ArgumentOption("-byte", "--long-byte", "", CommandOptionType.SingleValue, 1)] public byte? Byte { get; set; } [ArgumentOption("-ushort", "--long-ushort", "", CommandOptionType.SingleValue, 2)] public ushort? UShort { get; set; } [ArgumentOption("-uint", "--long-uint", "", CommandOptionType.SingleValue, 3)] public uint? UInt { get; set; } [ArgumentOption("-ulong", "--long-ulong", "", CommandOptionType.SingleValue, 4)] public ulong? ULong { get; set; } [ArgumentOption("-sbyte", "--long-sbyte", "", CommandOptionType.SingleValue,5)] public sbyte? SByte { get; set; } [ArgumentOption("-short", "--long-short", "", CommandOptionType.SingleValue, 6)] public ushort? Short { get; set; } [ArgumentOption("-int", "--long-int", "", CommandOptionType.SingleValue, 7)] public int? Int { get; set; } [ArgumentOption("-long", "--long-long", "", CommandOptionType.SingleValue, 8)] public long? Long { get; set; } [ArgumentOption("-float", "--long-float", "", CommandOptionType.SingleValue, 9)] public float? Float { get; set; } [ArgumentOption("-double", "--long-double", "", CommandOptionType.SingleValue, 10)] public double? Double { get; set; } [ArgumentOption("-decimal", "--long-decimal", "", CommandOptionType.SingleValue, 11)] public decimal? Decimal { get; set; } [ArgumentOption("-datetime", "--long-datetime", "", CommandOptionType.SingleValue)] public DateTime? DateTime { get; set; } [ArgumentOption("-timespan", "--long-timespan", "", CommandOptionType.SingleValue)] public TimeSpan? TimeSpan { get; set; } [ArgumentOption("-dtoffset", "--long-dtoffset", "", CommandOptionType.SingleValue)] public DateTimeOffset? DateTimeOffset { get; set; } [ArgumentOption("-guid", "--long-guid", "", CommandOptionType.SingleValue)] public Guid? Guid { get; set; } [ArgumentOption("-string", "--long-string", "", CommandOptionType.SingleValue)] public string String { get; set; } [ArgumentOption("-enum", "--long-enum", "", CommandOptionType.SingleValue, CLI.Enumeration.Value1)] public Enumeration? Enumeration { get; set; } } }
41.6
107
0.626202
[ "MIT" ]
MiracleDevs/Paradigm.Services
src/Paradigm.Services.Tests.Fixtures/Tests/CLI/NullableArguments.cs
2,496
C#
//----------------------------------------------------------------------- // <copyright company="Sherlock"> // Copyright 2013 Sherlock. Licensed under the Apache License, Version 2.0. // </copyright> //----------------------------------------------------------------------- using System; using Sherlock.Shared.Core; using Sherlock.Shared.Core.Reporting; namespace Sherlock.Service.Master { /// <summary> /// Defines a base for classes that provide a method of notifying the test requestor that their test has completed. /// </summary> [Serializable] internal abstract class TestCompletedNotification { /// <summary> /// Stores the given file in the location where the test report will be stored. /// </summary> /// <param name="filePath">The full path to the file that should be included in the report.</param> /// <param name="relativeReportPath">The relative 'path' which should be used to store the file data.</param> public abstract void StoreReportFile(string filePath, string relativeReportPath); /// <summary> /// Sends out a notification indicating that the test has completed. /// </summary> /// <param name="result">The test result.</param> /// <param name="report">The report describing the results of the test.</param> public abstract void OnTestCompleted(TestExecutionResult result, IReport report); } }
43.588235
120
0.595816
[ "Apache-2.0" ]
pvandervelde/Sherlock
src/service.master/TestCompletedNotification.cs
1,484
C#
using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia.Interactivity; using ReactiveUI; using Avalonia.ReactiveUI; using VMGuide; using System; using Avalonia.VisualTree; namespace app { public class ConfigView : ReactiveUserControl<ConfigViewModel> { public ConfigView() { this.WhenActivated(disposables => {}); AvaloniaXamlLoader.Load(this); this.AttachedToVisualTree += (s, e) => { this.Focus(); }; this.DetachedFromVisualTree += (s, e) => { Console.WriteLine("DetachedFromVisualTree"); }; this.DetachedFromLogicalTree += (s, e) => { Console.WriteLine("DetachedFromLogicalTree"); }; } } }
25.454545
67
0.563095
[ "BSD-3-Clause" ]
driver1998/VMGuide.NetCore
app/ConfigView.xaml.cs
840
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using NFluent; using NUnit.Framework; using ZeroLog.Appenders; using ZeroLog.Config; using ZeroLog.ConfigResolvers; namespace ZeroLog.Tests { [TestFixture] public class LogManagerTests { private TestAppender _testAppender; [SetUp] public void SetUpFixture() { _testAppender = new TestAppender(true); BasicConfigurator.Configure(new List<IAppender> { _testAppender }, 10); } [TearDown] public void Teardown() { LogManager.Shutdown(); } [Test] public void should_create_log() { var log = LogManager.GetLogger(typeof(LogManagerTests)); Check.That(log).IsNotNull(); } [Test] public void should_prevent_initializing_already_initialized_log_manager() { Assert.Throws<ApplicationException>(() => BasicConfigurator.Configure(new IAppender[0])); } [Test] public void should_return_special_log_event_when_no_more_log_event_are_available() { var log = LogManager.GetLogger(typeof(LogManagerTests)); var actualLogEvents = new List<ILogEvent>(); for (var i = 0; i < 10; i++) { actualLogEvents.Add(log.Debug()); } var unavailableEvent = log.Debug(); Check.That(actualLogEvents.OfType<LogEvent>().Count()).Equals(actualLogEvents.Count); Check.That(unavailableEvent).IsInstanceOf<ForwardingLogEvent>(); var signal = _testAppender.SetMessageCountTarget(actualLogEvents.Count); for (var i = 0; i < actualLogEvents.Count; i++) { var actualLogEvent = actualLogEvents[i]; actualLogEvent.Append(i).Log(); } signal.Wait(TimeSpan.FromMilliseconds(100)); Check.That(log.Debug()).IsInstanceOf<LogEvent>(); } [Test] public void should_log_special_message_when_log_event_pool_is_exhausted() { LogManager.Shutdown(); BasicConfigurator.Configure(new[] { _testAppender }, 10, 128, Level.Finest, LogEventPoolExhaustionStrategy.DropLogMessageAndNotifyAppenders); var log = LogManager.GetLogger(typeof(LogManagerTests)); var actualLogEvents = new List<ILogEvent>(); for (var i = 0; i < 10; i++) { actualLogEvents.Add(log.Debug()); } var signal = _testAppender.SetMessageCountTarget(1); log.Debug().Append("this is not going to happen").Log(); Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsTrue(); Check.That(_testAppender.LoggedMessages.Last()).Contains("Log message skipped due to LogEvent pool exhaustion."); } [Test] public void should_completely_drop_log_event_when_log_event_pool_is_exhausted() { LogManager.Shutdown(); BasicConfigurator.Configure(new[] { _testAppender }, 10, 128, Level.Finest, LogEventPoolExhaustionStrategy.DropLogMessage); var log = LogManager.GetLogger(typeof(LogManagerTests)); var actualLogEvents = new List<ILogEvent>(); for (var i = 0; i < 10; i++) { actualLogEvents.Add(log.Debug()); } var signal = _testAppender.SetMessageCountTarget(1); log.Debug().Append("this is not going to happen").Log(); Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsFalse(); } [Test] public void should_wait_for_event_when_log_event_pool_is_exhausted() { LogManager.Shutdown(); BasicConfigurator.Configure(new[] { _testAppender }, 10, 128, Level.Finest, LogEventPoolExhaustionStrategy.WaitForLogEvent); var log = LogManager.GetLogger(typeof(LogManagerTests)); var actualLogEvents = new List<ILogEvent>(); for (var i = 0; i < 10; i++) { actualLogEvents.Add(log.Debug()); } var signal = _testAppender.SetMessageCountTarget(2); var logCompletedSignal = new ManualResetEvent(false); Task.Run(() => { log.Debug().Append("this is not going to happen").Log(); logCompletedSignal.Set(); }); Check.That(logCompletedSignal.WaitOne(TimeSpan.FromMilliseconds(100))).IsFalse(); actualLogEvents[0].Log(); Check.That(logCompletedSignal.WaitOne(TimeSpan.FromMilliseconds(100))).IsTrue(); Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsTrue(); } [Test] public void should_not_throw_if_formatting_fails_when_using_format_string() { var log = LogManager.GetLogger(typeof(LogManagerTests)); var signal = _testAppender.SetMessageCountTarget(1); var guid = Guid.NewGuid(); log.InfoFormat("A good format: {0:X4}, A bad format: {1:lol}, Another good format: {2}", (short)-23805, guid, true); signal.Wait(TimeSpan.FromMilliseconds(100)); var logMessage = _testAppender.LoggedMessages.Single(); Check.That(logMessage).Equals("An error occured during formatting: \"A good format: {0:X4}, A bad format: {1:lol}, Another good format: {2}\", -23805, " + guid + ", True"); } [Test] public unsafe void should_not_throw_if_formatting_fails_when_appending_formatted_arguments() { var log = LogManager.GetLogger(typeof(LogManagerTests)); var signal = _testAppender.SetMessageCountTarget(1); var guid = Guid.NewGuid(); var date = new DateTime(2017, 02, 24, 16, 51, 51); var timespan = date.TimeOfDay; var asciiString = new[] { (byte)'a', (byte)'b', (byte)'c' }; fixed (byte* pAsciiString = asciiString) { log.Info().Append("Hello") .Append(false) .Append((byte)1) .Append('a') .Append((short)2) .Append(3) .Append((long)4) .Append(5f) .Append(6d) .Append(7m) .Append(guid, "meh, this is going to break formatting") .Append(date) .Append(timespan) .AppendAsciiString(asciiString, asciiString.Length) .AppendAsciiString(pAsciiString, asciiString.Length) .Log(); } signal.Wait(TimeSpan.FromMilliseconds(100)); var logMessage = _testAppender.LoggedMessages.Single(); Check.That(logMessage).Equals("An error occured during formatting: \"Hello\", False, 1, 'a', 2, 3, 4, 5, 6, 7, " + guid + ", 2017-02-24 16:51:51.000, 16:51:51.000, \"abc\", \"abc\""); } } }
35.136585
195
0.578925
[ "MIT" ]
y-skindersky/ZeroLog
src/ZeroLog.Tests/LogManagerTests.cs
7,205
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Storage { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public enum StorageLibraryChangeType { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ Created, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ Deleted, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ MovedOrRenamed, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ ContentsChanged, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ MovedOutOfLibrary, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ MovedIntoLibrary, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ ContentsReplaced, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ IndexingStatusChanged, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ EncryptionChanged, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ ChangeTrackingLost, #endif } #endif }
28.795455
63
0.696133
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Storage/StorageLibraryChangeType.cs
1,267
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using RestWithASP_NET5Udemy.Model.Context; using RestWithASP_NET5Udemy.Business; using RestWithASP_NET5Udemy.Business.Implementations; using RestWithASP_NET5Udemy.Repository; using RestWithASP_NET5Udemy.Repository.Implementations; using Serilog; using System; using System.Collections.Generic; namespace RestWithASP_NET5Udemy { public class Startup { public IConfiguration Configuration { get; } public IWebHostEnvironment Environment { get; } public Startup(IConfiguration configuration, IWebHostEnvironment environment) { Configuration = configuration; Environment = environment; Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); var connection = Configuration["MySQLConnection:MySQLConnectionString"]; services.AddDbContext<MySQLContext>(options => options.UseMySql(connection)); if (Environment.IsDevelopment()) { MigrateDatabase(connection); } //Versioning API services.AddApiVersioning(); //Dependency Injection services.AddScoped<IPersonBusiness, PersonBusinessImplementation>(); services.AddScoped<IPersonRepository, PersonRepositoryImplementation>(); } private void MigrateDatabase(string connection) { try{ var evolveConnection = new MySql.Data.MySqlClient.MySqlConnection(connection); var evolve = new Evolve.Evolve(evolveConnection, msg => Log.Information(msg)) { Locations = new List<string> { "db/migrations", "db/dataset" }, IsEraseDisabled = true }; evolve.Migrate(); }catch(Exception ex) { Log.Error("Database migration failed", ex); throw; } } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
31.578947
106
0.619
[ "Apache-2.0" ]
celsoliveira/RestWithASP-NET5Udemy
01_RestWithASP-NET5Udemy/RestWithASP-NET5Udemy/RestWithASP-NET5Udemy/Startup.cs
3,000
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MentorBot.Functions.Abstract.Services; using MentorBot.Functions.Models.Business; using MentorBot.Functions.Models.Domains; using MentorBot.Functions.Services; using MentorBot.Tests._Base; using MentorBot.Tests.Base; using Microsoft.Azure.Functions.Worker.Http; using Microsoft.Extensions.Caching.Memory; using Microsoft.VisualStudio.TestTools.UnitTesting; using NSubstitute; namespace MentorBot.Tests.Business.Services { [TestClass] [TestCategory("Business.Services")] public sealed class GoogleAccessTokenServiceTests { private IStorageService _storageService; private IMemoryCache _cache; private MockHttpMessageHandler _messageHandler; private GoogleAccessTokenService _service; [TestInitialize] public void TestInitialize() { _storageService = Substitute.For<IStorageService>(); _cache = Substitute.For<IMemoryCache>(); _messageHandler = new MockHttpMessageHandler(); _service = new GoogleAccessTokenService(_cache, _storageService, () => _messageHandler); } [TestMethod] public async Task ValidateTokenShouldCheckTokenSchema() { var req = GetRequestWithAuthHeader("Basic ABC123"); var result = await _service.ValidateTokenAsync(req); Assert.IsFalse(result.IsValid); } [TestMethod] public async Task ValidateTokenShouldGetUserFromStore() { var usr = new User { GoogleUserId = "123", Role = 2 }; var req = GetRequestWithAuthHeader("Bearer ABC123"); _messageHandler.Set("{ \"user_id\": \"123\", \"expires_in\":60, \"access_type\":\"online\", \"email\":\"test@domain.com\" }", "application/json"); _storageService.GetUserByEmailAsync("test@domain.com").Returns(usr); var result = await _service.ValidateTokenAsync(req); Assert.AreEqual("administrator", result.Role); Assert.IsTrue(result.IsValid); } [TestMethod] public async Task ValidateTokenShouldSaveUserWithoutGoogleId() { var usr = new User { Id = "U1", Role = 1 }; var req = GetRequestWithAuthHeader("Bearer ABC123"); _messageHandler.Set("{ \"user_id\": \"123\", \"expires_in\":60, \"access_type\":\"online\", \"email\":\"test@domain.com\" }", "application/json"); _storageService.GetUserByEmailAsync("test@domain.com").Returns(usr); var result = await _service.ValidateTokenAsync(req); await _storageService.Received() .UpdateUsersAsync( Arg.Is<IReadOnlyList<User>>(it => it.First().Id == "U1" && it.First().GoogleUserId == "123")); } [TestMethod] public async Task ValidateTokenShouldInvalidateBasedOnTokenInfo() { var req = GetRequestWithAuthHeader("Bearer ABC123"); _messageHandler.Set("{ \"user_id\": \"123\", \"expires_in\":60, \"access_type\":\"offline\", \"email\":\"test@domain.com\" }", "application/json"); var result = await _service.ValidateTokenAsync(req); Assert.IsFalse(result.IsValid); } [TestMethod] public async Task ValidateTokenShouldGetFromCache() { var req = GetRequestWithAuthHeader("Bearer ABC123"); _cache.TryGetValue("UserAccessToken_ABC123", out Arg.Any<object>()) .Returns(x => { x[1] = new GoogleAccessTokenInfo { UserId = "345", Type = "online", Email = "abc@def.go", DueDate = DateTime.UtcNow.AddMinutes(1) }; return true; }); _cache.TryGetValue("UserRole_abc@def.go", out Arg.Any<object>()) .Returns(x => { x[1] = UserRoles.User; return true; }); var result = await _service.ValidateTokenAsync(req); Assert.AreEqual(result.Role, "user"); Assert.IsTrue(result.IsValid); } private static HttpRequestData GetRequestWithAuthHeader(string value) { var ctx = MockFunction.GetContext(); var req = MockFunction.GetRequest(null, ctx); var headers = new HttpHeadersCollection(); headers.Add("Authorization", value); req.Headers.Returns(headers); return req; } } }
34.594203
159
0.587977
[ "MIT" ]
MentorSource/mentorbot
tests/MentorBot.Tests/Business/Services/GoogleAccessTokenServiceTests.cs
4,776
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.Web.V20181101 { public static class GetWebAppHostNameBindingSlot { public static Task<GetWebAppHostNameBindingSlotResult> InvokeAsync(GetWebAppHostNameBindingSlotArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetWebAppHostNameBindingSlotResult>("azure-nextgen:web/v20181101:getWebAppHostNameBindingSlot", args ?? new GetWebAppHostNameBindingSlotArgs(), options.WithVersion()); } public sealed class GetWebAppHostNameBindingSlotArgs : Pulumi.InvokeArgs { /// <summary> /// Hostname in the hostname binding. /// </summary> [Input("hostName", required: true)] public string HostName { get; set; } = null!; /// <summary> /// Name of the app. /// </summary> [Input("name", required: true)] public string Name { get; set; } = null!; /// <summary> /// Name of the resource group to which the resource belongs. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// Name of the deployment slot. If a slot is not specified, the API the named binding for the production slot. /// </summary> [Input("slot", required: true)] public string Slot { get; set; } = null!; public GetWebAppHostNameBindingSlotArgs() { } } [OutputType] public sealed class GetWebAppHostNameBindingSlotResult { /// <summary> /// Azure resource name. /// </summary> public readonly string? AzureResourceName; /// <summary> /// Azure resource type. /// </summary> public readonly string? AzureResourceType; /// <summary> /// Custom DNS record type. /// </summary> public readonly string? CustomHostNameDnsRecordType; /// <summary> /// Fully qualified ARM domain resource URI. /// </summary> public readonly string? DomainId; /// <summary> /// Hostname type. /// </summary> public readonly string? HostNameType; /// <summary> /// Kind of resource. /// </summary> public readonly string? Kind; /// <summary> /// Resource Name. /// </summary> public readonly string Name; /// <summary> /// App Service app name. /// </summary> public readonly string? SiteName; /// <summary> /// SSL type /// </summary> public readonly string? SslState; /// <summary> /// SSL certificate thumbprint /// </summary> public readonly string? Thumbprint; /// <summary> /// Resource type. /// </summary> public readonly string Type; /// <summary> /// Virtual IP address assigned to the hostname if IP based SSL is enabled. /// </summary> public readonly string VirtualIP; [OutputConstructor] private GetWebAppHostNameBindingSlotResult( string? azureResourceName, string? azureResourceType, string? customHostNameDnsRecordType, string? domainId, string? hostNameType, string? kind, string name, string? siteName, string? sslState, string? thumbprint, string type, string virtualIP) { AzureResourceName = azureResourceName; AzureResourceType = azureResourceType; CustomHostNameDnsRecordType = customHostNameDnsRecordType; DomainId = domainId; HostNameType = hostNameType; Kind = kind; Name = name; SiteName = siteName; SslState = sslState; Thumbprint = thumbprint; Type = type; VirtualIP = virtualIP; } } }
30.215278
221
0.578028
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Web/V20181101/GetWebAppHostNameBindingSlot.cs
4,351
C#
// -------------------------------------------------------------------------------------------------------------------- // Copyright (c) Lead Pipe Software. All rights reserved. // Licensed under the MIT License. Please see the LICENSE file in the project root for full license information. // -------------------------------------------------------------------------------------------------------------------- namespace LeadPipe.Net.Domain.Tests.DomainEventingTests { /// <summary> /// A test domain event class. /// </summary> public class TestDomainEvent : IDomainEvent { /// <summary> /// Gets or sets the new name. /// </summary> /// <value>The new name.</value> public string NewName { get; set; } } }
40.684211
120
0.433376
[ "MIT" ]
LeadPipeSoftware/LeadPipe.Net
src/LeadPipe.Net.Domain.Tests/DomainEventingTests/TestDomainEvent.cs
775
C#
using System; using System.Drawing; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Windows.Forms; using System.Threading; using System.IO; using System.Text; using Microsoft.Win32; using System.Data; using System.Drawing.Imaging; using System.ComponentModel; using System.Runtime.InteropServices; //using AForge.Video; //using AForge.Video.DirectShow; /* namespace Remote_Control_Tools_ProcWindow { class WebCamLayer { private bool bool_IsDeviceExist = false; private FilterInfoCollection filterInfoCollection_Devices; private VideoCaptureDevice videoCaptureDevice_VideoSource = null; private FilterInfoCollection AquireWebCamDevice() { try { filterInfoCollection_Devices = new FilterInfoCollection(FilterCategory.VideoInputDevice); if (filterInfoCollection_Devices.Count == 0) { throw new ApplicationException(); } bool_IsDeviceExist = true; foreach (FilterInfo filterInfo_CurrentDevice in filterInfoCollection_Devices) { } return filterInfoCollection_Devices; } catch (ApplicationException) { bool_IsDeviceExist = false; return null; } } private void StartWebCamCapture(int int_CaptureDeviceIndex) { if (bool_IsDeviceExist) { videoCaptureDevice_VideoSource = new VideoCaptureDevice(filterInfoCollection_Devices[int_CaptureDeviceIndex].MonikerString); //!! 0 is a default device index CloseVideoSourceIfBusy(); videoCaptureDevice_VideoSource.DesiredFrameSize = new Size(320, 240); videoCaptureDevice_VideoSource.DesiredFrameRate = 1; videoCaptureDevice_VideoSource.Start(); videoCaptureDevice_VideoSource.NewFrame += new NewFrameEventHandler(NewVideoFrameEvent); } else { } } private void CloseVideoSourceIfBusy() { if (videoCaptureDevice_VideoSource != null) { if (videoCaptureDevice_VideoSource.IsRunning == true) { videoCaptureDevice_VideoSource.SignalToStop(); videoCaptureDevice_VideoSource = null; } } } private void NewVideoFrameEvent(object sender, NewFrameEventArgs eventArgs) { if(LocalObjCopy.obj_WebCamContainer.RemotingWrapper_NeedToStopWebCam == true) { videoCaptureDevice_VideoSource.Stop(); videoCaptureDevice_VideoSource.NewFrame -= new NewFrameEventHandler(NewVideoFrameEvent); return; } LocalObjCopy.obj_WebCamContainer.RemotingWrapper_ScreenHeightSize = (short)((Bitmap)eventArgs.Frame).Height; LocalObjCopy.obj_WebCamContainer.RemotingWrapper_ScreenWidthSize = (short)((Bitmap)eventArgs.Frame).Width; LocalObjCopy.obj_WebCamContainer.SetScreenBytes(GetBytesFromBitmap((Bitmap)eventArgs.Frame.Clone())); LocalObjCopy.obj_WebCamContainer.RemotingWrapper_RefreshCompleteFlag = true; eventArgs.Frame.Dispose(); } public void StartCapture() { AquireWebCamDevice(); StartWebCamCapture(0); } public byte[] GetBytesFromBitmap(Bitmap bitmap_Image) { try { MemoryStream memoryStream_Image = new MemoryStream(); memoryStream_Image.Position = 0; bitmap_Image.Save(memoryStream_Image, ImageFormat.Png); memoryStream_Image.SetLength(memoryStream_Image.Length); return memoryStream_Image.ToArray(); } catch { return null; } } } } */
29.751773
173
0.597139
[ "Apache-2.0" ]
yaksys/Remote-Control-Tools-YakSys-
Remote Control Tools ProcWindow/Remote Control Tools ProcWindow/WebCamLayer.cs
4,197
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ResetPosition : MonoBehaviour { private Vector3 savedPosition; private void Awake() { savedPosition = transform.position; } public void RestoreInitialPosition() { transform.position = savedPosition; } }
19
43
0.69883
[ "MIT" ]
Vildanix/Ludum-dare-47
Assets/Scripts/Support/ResetPosition.cs
344
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LoadStore : MonoBehaviour { public GameObject RestartButton; public GameObject LojaButton; public GameObject ImgMenu; public GameObject CarregarMenuLoja; }
20.307692
39
0.795455
[ "MIT" ]
geeox96/TheCosmos
Assets/Scripts/LoadStore.cs
266
C#
// <copyright file="GPGSIds.cs" company="Google Inc."> // Copyright (C) 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> /// /// This file is automatically generated DO NOT EDIT! /// /// These are the constants defined in the Play Games Console for Game Services /// Resources. /// public static class GooglePlayIds { public const string leaderboard_high_scores = "CgkI19aihIAQEAIQAA"; // <GPGSID> }
37.384615
81
0.730453
[ "Apache-2.0" ]
paidgeek/SimpleGameTemplate
Assets/Scripts/Social/GooglePlayIds.cs
972
C#
using System.Security.Claims; using System.Text; using HRM.Infra.CrossCutting.Identity.Interfaces; using HRM.Infra.CrossCutting.Identity.Interfaces.Services; using Microsoft.IdentityModel.Tokens; namespace HRM.Infra.CrossCutting.Identity.Auth { public class JwtTokenValidator : IJwtTokenValidator { private readonly IJwtTokenHandler _jwtTokenHandler; internal JwtTokenValidator(IJwtTokenHandler jwtTokenHandler) { _jwtTokenHandler = jwtTokenHandler; } public ClaimsPrincipal GetPrincipalFromToken(string token, string signingKey) { return _jwtTokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey)), ValidateLifetime = false // we check expired tokens here }); } } }
33.548387
96
0.679808
[ "MIT" ]
Andyhacool/HRM
src/HRM.Infra.CrossCutting.Identity/Auth/JwtTokenValidator.cs
1,042
C#
namespace Blog.Services.Data { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AngleSharp.Css.Values; using Blog.Data.Common.Repositories; using Blog.Data.Models; using Blog.Services.Data.Common; using Blog.Services.Data.Contracts; using Blog.Services.Mapping; using Blog.Web.ViewModels.Administration.Posts.InputModels; using CloudinaryDotNet; using Microsoft.EntityFrameworkCore; public class PostsService : IPostsService { private readonly IDeletableEntityRepository<Post> postRepository; private readonly IDeletableEntityRepository<Tag> tagRepository; private readonly Cloudinary cloudinary; public PostsService( IDeletableEntityRepository<Post> postRepository, IDeletableEntityRepository<Category> categoryRepository, IDeletableEntityRepository<Tag> tagRepository, Cloudinary cloudinary) { this.postRepository = postRepository; this.tagRepository = tagRepository; this.cloudinary = cloudinary; } public int TotalPosts => this.postRepository.AllAsNoTracking().Count(); public async Task<int> CreateAsync(string userId, CreatePostInputModel inputModel) { var imageUrl = await ApplicationCloudinary .UploadViaFromFile(this.cloudinary, inputModel.Image, inputModel.Title); var newUrls = await ApplicationCloudinary .GetImageUrlsAsync(this.cloudinary, inputModel.Description); var updatedContent = await AngleSharpExtension .UpdateImageSourceAsync(newUrls.ToList(), inputModel.Description); var post = new Post { Title = inputModel.Title, Description = updatedContent, ShortDescription = inputModel.ShortDescription, ImageUrl = imageUrl, ApplicationUserId = userId, }; post.PostCategories.Add(new PostCategory { CategoryId = inputModel.CategoryId, }); var tags = inputModel.Tags .Split(separator: new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries) .Distinct() .ToArray(); foreach (var tagName in tags) { var currentTag = this.tagRepository .AllAsNoTracking() .FirstOrDefault(x => x.Name == tagName); if (currentTag == null) { currentTag = new Tag { Name = tagName, }; } if (post.TagPosts.All(x => x.Tag.Name != tagName)) { post.TagPosts.Add(new TagPost { TagId = currentTag.Id, }); } } await this.postRepository.AddAsync(post); await this.postRepository.SaveChangesAsync(); return post.Id; } public TModel GetById<TModel>(int id) => this.postRepository .AllAsNoTracking() .Include(x => x.TagPosts) .ThenInclude(x => x.Tag) .Include(x => x.PostCategories) .ThenInclude(x => x.Category) .Where(x => x.Id == id) .To<TModel>() .FirstOrDefault(); public IEnumerable<TModel> GetLastCreatedPosts<TModel>(int defaultCount = 3) => this.postRepository .AllAsNoTracking() .OrderByDescending(x => x.CreatedOn) .To<TModel>() .Take(defaultCount) .ToList(); public async Task RemoveAsync(int id) { var post = await this.postRepository.GetByIdWithDeletedAsync(id); this.postRepository.Delete(post); await this.postRepository.SaveChangesAsync(); } public IEnumerable<TModel> GetByPage<TModel>(int take, int skip) => this.postRepository .AllAsNoTracking() .Include(x => x.ApplicationUser) .Include(x => x.TagPosts) .ThenInclude(t => t.Tag) .OrderByDescending(x => x.CreatedOn) .Skip(skip * (take - 1)) .Take(skip) .To<TModel>() .ToList(); public IEnumerable<TModel> GetByTagPage<TModel>(int tagId, int take, int skip) => this.postRepository .AllAsNoTracking() .Include(x => x.ApplicationUser) .Include(x => x.TagPosts) .ThenInclude(t => t.Tag) .Where(t => t.TagPosts.Any(i => i.TagId == tagId)) .OrderByDescending(x => x.CreatedOn) .Skip(skip * (take - 1)) .Take(skip) .To<TModel>() .ToList(); public async Task<int> EditAsync(EditPostInputModel inputModel) { var post = this.postRepository .All() .Include(t => t.TagPosts) .ThenInclude(x => x.Tag) .FirstOrDefault(x => x.Id == inputModel.Id); post.Title = inputModel.Title; post.Description = inputModel.Description; post.ShortDescription = inputModel.ShortDescription; if (post.PostCategories.Any(x => x.CategoryId == inputModel.CategoryId)) { post.PostCategories.Add(new PostCategory { CategoryId = inputModel.CategoryId, }); } if (inputModel.Image != null) { var imageUrl = await ApplicationCloudinary .UploadViaFromFile(this.cloudinary, inputModel.Image, inputModel.Title); post.ImageUrl = imageUrl; } var tags = inputModel.Tags .Split(separator: new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries) .Distinct() .ToArray(); foreach (var tagName in tags) { var currentTag = this.GetOrCreateTag(tagName); if (post.TagPosts.All(x => x.Tag.Name != tagName)) { post.TagPosts.Add(new TagPost { TagId = currentTag.Id, }); } } await this.postRepository.SaveChangesAsync(); return post.Id; } private Tag GetOrCreateTag(string tagName) { var tag = this.tagRepository .AllAsNoTracking() .FirstOrDefault(x => x.Name == tagName) ?? new Tag { Name = tagName, }; return tag; } } }
33.378505
92
0.51351
[ "MIT" ]
StoyanShopov/MyBlog
Blog/Services/Blog.Services.Data/PostsService.cs
7,145
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/ShObjIdl.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace TerraFX.Interop.Windows; /// <include file='IAccessibilityDockingService.xml' path='doc/member[@name="IAccessibilityDockingService"]/*' /> [Guid("8849DC22-CEDF-4C95-998D-051419DD3F76")] [NativeTypeName("struct IAccessibilityDockingService : IUnknown")] [NativeInheritance("IUnknown")] [SupportedOSPlatform("windows8.0")] public unsafe partial struct IAccessibilityDockingService : IAccessibilityDockingService.Interface { public void** lpVtbl; /// <inheritdoc cref="IUnknown.QueryInterface" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(0)] public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged<IAccessibilityDockingService*, Guid*, void**, int>)(lpVtbl[0]))((IAccessibilityDockingService*)Unsafe.AsPointer(ref this), riid, ppvObject); } /// <inheritdoc cref="IUnknown.AddRef" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(1)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<IAccessibilityDockingService*, uint>)(lpVtbl[1]))((IAccessibilityDockingService*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IUnknown.Release" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(2)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<IAccessibilityDockingService*, uint>)(lpVtbl[2]))((IAccessibilityDockingService*)Unsafe.AsPointer(ref this)); } /// <include file='IAccessibilityDockingService.xml' path='doc/member[@name="IAccessibilityDockingService.GetAvailableSize"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] public HRESULT GetAvailableSize(HMONITOR hMonitor, uint* pcxFixed, uint* pcyMax) { return ((delegate* unmanaged<IAccessibilityDockingService*, HMONITOR, uint*, uint*, int>)(lpVtbl[3]))((IAccessibilityDockingService*)Unsafe.AsPointer(ref this), hMonitor, pcxFixed, pcyMax); } /// <include file='IAccessibilityDockingService.xml' path='doc/member[@name="IAccessibilityDockingService.DockWindow"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(4)] public HRESULT DockWindow(HWND hwnd, HMONITOR hMonitor, uint cyRequested, IAccessibilityDockingServiceCallback* pCallback) { return ((delegate* unmanaged<IAccessibilityDockingService*, HWND, HMONITOR, uint, IAccessibilityDockingServiceCallback*, int>)(lpVtbl[4]))((IAccessibilityDockingService*)Unsafe.AsPointer(ref this), hwnd, hMonitor, cyRequested, pCallback); } /// <include file='IAccessibilityDockingService.xml' path='doc/member[@name="IAccessibilityDockingService.UndockWindow"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(5)] public HRESULT UndockWindow(HWND hwnd) { return ((delegate* unmanaged<IAccessibilityDockingService*, HWND, int>)(lpVtbl[5]))((IAccessibilityDockingService*)Unsafe.AsPointer(ref this), hwnd); } public interface Interface : IUnknown.Interface { [VtblIndex(3)] HRESULT GetAvailableSize(HMONITOR hMonitor, uint* pcxFixed, uint* pcyMax); [VtblIndex(4)] HRESULT DockWindow(HWND hwnd, HMONITOR hMonitor, uint cyRequested, IAccessibilityDockingServiceCallback* pCallback); [VtblIndex(5)] HRESULT UndockWindow(HWND hwnd); } public partial struct Vtbl<TSelf> where TSelf : unmanaged, Interface { [NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> AddRef; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> Release; [NativeTypeName("HRESULT (HMONITOR, UINT *, UINT *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, HMONITOR, uint*, uint*, int> GetAvailableSize; [NativeTypeName("HRESULT (HWND, HMONITOR, UINT, IAccessibilityDockingServiceCallback *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, HWND, HMONITOR, uint, IAccessibilityDockingServiceCallback*, int> DockWindow; [NativeTypeName("HRESULT (HWND) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, HWND, int> UndockWindow; } }
46.556604
246
0.723607
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/um/ShObjIdl/IAccessibilityDockingService.cs
4,937
C#
using Wollo.Base.Entity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Wollo.Base.LocalResource; namespace Wollo.Entities.Models { [DataContract] public class Market_Rate_Details : AuditableEntity { [DataMember] [Required(ErrorMessage = "Rate is required.")] public float rate { get; set; } } }
23.619048
54
0.731855
[ "MIT" ]
umangsunarc/OTH
Wollo.Entities/Models/Market_Rate_Details.cs
498
C#
using EddiEvents; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EddiShipMonitor { public class ShipShutdownEvent : Event { public const string NAME = "Ship shutdown"; public const string DESCRIPTION = "Triggered when your ship's system are shutdown"; public const string SAMPLE = @"{ ""timestamp"":""2017-01-05T23:15:06Z"", ""event"":""SystemsShutdown"" }"; public static Dictionary<string, string> VARIABLES = new Dictionary<string, string>(); static ShipShutdownEvent() { } public ShipShutdownEvent(DateTime timestamp) : base(timestamp, NAME) { } } }
26.892857
114
0.666667
[ "Apache-2.0" ]
cmdrmcdonald/EliteDangerousDataProvider
ShipMonitor/ShipShutdownEvent.cs
755
C#
using System; using System.Collections.Generic; using System.Linq; using Mono.Cecil; using NUnit.Framework; namespace NRoles.Engine.Test.Composition.SelfType { [TestFixture] public class Retrieve_Self_Types_From_Roles_Fixture : AssemblyReadonlyFixture { private IEnumerable<RoleSelfType> GetRolesAndSelfTypes<C>() { var source = GetType<C>(); var extractor = new SelfTypeExtractor(); return extractor.RetrieveRolesSelfTypes(source); } [Test] public void Test_No_Self_Types_For_Role_Without_Self_Type() { var rolesAndSelfTypes = GetRolesAndSelfTypes<NoSelfType>(); Assert.AreEqual(0, rolesAndSelfTypes.Count()); } class RNoSelfType : Role { } class NoSelfType : Does<RNoSelfType> { } private void AssertRoleSelfType(RoleSelfType roleSelfType, Type roleType, Type sourceType) { var role = GetType(roleType); var source = GetType(sourceType); Assert.AreEqual(role.ToString(), roleSelfType.Role.Resolve().ToString()); Assert.AreEqual(source.ToString(), ((GenericInstanceType)roleSelfType.Role).GenericArguments[0].FullName); Assert.AreEqual(source.ToString(), roleSelfType.SelfType.ToString()); } [Test] public void Test_Self_Type_For_Composition_With_One_Role() { var rolesAndSelfTypes = GetRolesAndSelfTypes<SelfType>(); Assert.AreEqual(1, rolesAndSelfTypes.Count()); AssertRoleSelfType(rolesAndSelfTypes.First(), typeof(RSelfType<>), typeof(SelfType)); } class RSelfType<TSelf> : Role { } class SelfType : Does<RSelfType<SelfType>> { } [Test] public void Test_Self_Types_For_Composition_With_Two_Roles() { var rolesAndSelfTypes = GetRolesAndSelfTypes<TwoSelfTypes>(); Assert.AreEqual(2, rolesAndSelfTypes.Count()); AssertRoleSelfType(rolesAndSelfTypes.First(), typeof(RSelfType<>), typeof(TwoSelfTypes)); AssertRoleSelfType(rolesAndSelfTypes.Last(), typeof(RAnotherSelfType<>), typeof(TwoSelfTypes)); } class RAnotherSelfType<TSelf> : Role { } class TwoSelfTypes : Does<RSelfType<TwoSelfTypes>>, Does<RAnotherSelfType<TwoSelfTypes>> { } } }
39.107143
113
0.710502
[ "MIT" ]
jordao76/nroles
src/NRoles.Engine.Test/Composition/SelfType/Retrieve_Self_Types_From_Roles_Fixture.cs
2,192
C#
namespace Escolas.Dominio.Shared { public struct Endereco { public Endereco(string rua, string numero, string complemento, string bairro, string cidade, string estado) : this() { Rua = rua; Numero = numero; Complemento = complemento; Bairro = bairro; Cidade = cidade; Estado = estado; } public string Rua { get; } public string Numero { get; } public string Complemento { get; } public string Bairro { get; } public string Cidade { get; } public string Estado { get; } } }
26.333333
124
0.545886
[ "MIT" ]
gabriel-society/RegrasNegocioTalk
Demos/Ex01.Escolas/Escolas.Dominio/Shared/Endereco.cs
634
C#
/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace CubicPilot.UtilCode { public class Countdown { private bool mActive = false; private float mInitial = 1.0f; private float mRemaining = 1.0f; public Countdown(float initial) : this(true, initial) { } public Countdown(bool active) : this(active, 1.0f) { } public Countdown() : this(false, 1.0f) { } public Countdown(bool active, float initial) { mActive = active; mInitial = mRemaining = initial; } public void Update(float deltaT, bool autoStopOnExpired) { if (mActive) { mRemaining = Util.Clamp(mRemaining - deltaT, 0, mInitial); } if (autoStopOnExpired && Expired) { Stop(); } } public void Update(float deltaT) { Update(deltaT, false); } public void Start() { mRemaining = mInitial; mActive = true; } public void Start(float initial) { mRemaining = mInitial = initial; mActive = true; } public void Stop() { mRemaining = mInitial; mActive = false; } public void Pause() { mActive = false; } public void Resume() { mActive = true; } public bool Expired { get { return mActive && mRemaining <= 0; } } public float Initial { get { return mInitial; } } public float Remaining { get { return mRemaining; } } public float Elapsed { get { return mInitial - mRemaining; } } public float NormalizedElapsed { get { return Elapsed / mInitial; } } public float NormalizedRemaining { get { return Remaining / mInitial; } } public bool Active { get { return mActive; } } public override string ToString() { return string.Format("[Countdown: active={0}, initial={1}, remaining={2}]", mActive, mInitial, mRemaining); } } }
22.669173
96
0.506468
[ "Apache-2.0" ]
2035themes/play-games-plugin-for-unity
samples/CubicPilot/Source/Assets/CubicPilot/UtilCode/Countdown.cs
3,015
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 personalize-2018-05-22.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.Personalize.Model { /// <summary> /// Container for the parameters to the DeleteSolution operation. /// Deletes all versions of a solution and the <code>Solution</code> object itself. Before /// deleting a solution, you must delete all campaigns based on the solution. To determine /// what campaigns are using the solution, call <a>ListCampaigns</a> and supply the Amazon /// Resource Name (ARN) of the solution. You can't delete a solution if an associated /// <code>SolutionVersion</code> is in the CREATE PENDING or IN PROGRESS state. For more /// information on solutions, see <a>CreateSolution</a>. /// </summary> public partial class DeleteSolutionRequest : AmazonPersonalizeRequest { private string _solutionArn; /// <summary> /// Gets and sets the property SolutionArn. /// <para> /// The ARN of the solution to delete. /// </para> /// </summary> [AWSProperty(Required=true, Max=256)] public string SolutionArn { get { return this._solutionArn; } set { this._solutionArn = value; } } // Check to see if SolutionArn property is set internal bool IsSetSolutionArn() { return this._solutionArn != null; } } }
34.90625
109
0.675022
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Personalize/Generated/Model/DeleteSolutionRequest.cs
2,234
C#
using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using KS.Fiks.IO.Client.Amqp; using KS.Fiks.IO.Client.Catalog; using KS.Fiks.IO.Client.Configuration; using KS.Fiks.IO.Client.Dokumentlager; using KS.Fiks.IO.Client.Models; using KS.Fiks.IO.Client.Send; using KS.Fiks.IO.Send.Client; using Ks.Fiks.Maskinporten.Client; using Moq; using RabbitMQ.Client.Events; namespace KS.Fiks.IO.Client.Tests { public class FiksIOClientFixture { private FiksIOConfiguration _configuration; private Konto _lookupReturn = null; private SendtMelding _sendtMeldingReturn = null; private string _scheme = "http"; private string _host = "api.fiks.dev.ks"; private int _port = 80; private string _path; private string _integrasjonPassword = "default"; private Guid _integrasjonId = Guid.NewGuid(); private Guid _accountId = Guid.NewGuid(); private KatalogConfiguration _katalogConfiguration; public FiksIOClientFixture() { CatalogHandlerMock = new Mock<ICatalogHandler>(); MaskinportenClientMock = new Mock<IMaskinportenClient>(); FiksIOSenderMock = new Mock<IFiksIOSender>(); SendHandlerMock = new Mock<ISendHandler>(); DokumentlagerHandlerMock = new Mock<IDokumentlagerHandler>(); AmqpHandlerMock = new Mock<IAmqpHandler>(); } public Mock<IMaskinportenClient> MaskinportenClientMock { get; } public Mock<IFiksIOSender> FiksIOSenderMock { get; } public Mock<ISendHandler> SendHandlerMock { get; } public MeldingRequest DefaultRequest => new MeldingRequest( Guid.NewGuid(), Guid.NewGuid(), "defaultType"); public FiksIOClient CreateSut() { SetupConfiguration(); SetupMocks(); return new FiksIOClient( _configuration, CatalogHandlerMock.Object, MaskinportenClientMock.Object, SendHandlerMock.Object, DokumentlagerHandlerMock.Object, AmqpHandlerMock.Object); } public FiksIOClientFixture WithAccountId(Guid id) { _accountId = id; return this; } public FiksIOClientFixture WithLookupAccount(Konto konto) { _lookupReturn = konto; return this; } public FiksIOClientFixture WithScheme(string scheme) { _scheme = scheme; return this; } public FiksIOClientFixture WithHost(string host) { _host = host; return this; } public FiksIOClientFixture WithPort(int port) { _port = port; return this; } public FiksIOClientFixture WithPath(string path) { _path = path; return this; } public FiksIOClientFixture WithSentMessageReturned(SendtMelding message) { _sendtMeldingReturn = message; return this; } public FiksIOClientFixture WithCatalogConfiguration(KatalogConfiguration configuration) { _katalogConfiguration = configuration; return this; } internal Mock<ICatalogHandler> CatalogHandlerMock { get; } internal Mock<IDokumentlagerHandler> DokumentlagerHandlerMock { get; } internal Mock<IAmqpHandler> AmqpHandlerMock { get; } private void SetupMocks() { CatalogHandlerMock.Setup(_ => _.Lookup(It.IsAny<LookupRequest>())).ReturnsAsync(_lookupReturn); SendHandlerMock.Setup(_ => _.Send(It.IsAny<MeldingRequest>(), It.IsAny<IList<IPayload>>())) .ReturnsAsync(_sendtMeldingReturn); AmqpHandlerMock.Setup(_ => _.AddMessageReceivedHandler( It.IsAny<EventHandler<MottattMeldingArgs>>(), It.IsAny<EventHandler<ConsumerEventArgs>>())); } private void SetupConfiguration() { var apiConfiguration = new ApiConfiguration(_scheme, _host, _port); var accountConfiguration = new KontoConfiguration(_accountId, "dummyKey"); _configuration = new FiksIOConfiguration( accountConfiguration, new IntegrasjonConfiguration(_integrasjonId, _integrasjonPassword), new MaskinportenClientConfiguration("audience", "token", "issuer", 1, new X509Certificate2()), apiConfiguration: apiConfiguration, katalogConfiguration: _katalogConfiguration); } } }
32.972222
110
0.621735
[ "MIT" ]
jarped/fiks-io-client-dotnet
KS.Fiks.IO.Client.Tests/FiksIOClientFixture.cs
4,748
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Subjects; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using System.Xml.XPath; using Buildalyzer; using Buildalyzer.Workspaces; using Clockwise; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; using MLS.Agent.Tools; using System.Reactive.Linq; using System.Runtime.CompilerServices; using System.Threading; using Pocket; using WorkspaceServer.Servers.Roslyn; using static Pocket.Logger<WorkspaceServer.Packaging.Package>; using Disposable = System.Reactive.Disposables.Disposable; namespace WorkspaceServer.Packaging { public abstract class Package : PackageBase, ICreateWorkspaceForLanguageServices, ICreateWorkspaceForRun { internal const string DesignTimeBuildBinlogFileName = "package_designTimeBuild.binlog"; private static readonly ConcurrentDictionary<string, SemaphoreSlim> _packageBuildSemaphores = new ConcurrentDictionary<string, SemaphoreSlim>(); private static readonly ConcurrentDictionary<string, SemaphoreSlim> _packagePublishSemaphores = new ConcurrentDictionary<string, SemaphoreSlim>(); static Package() { const string workspacesPathEnvironmentVariableName = "TRYDOTNET_PACKAGES_PATH"; var environmentVariable = Environment.GetEnvironmentVariable(workspacesPathEnvironmentVariableName); DefaultPackagesDirectory = environmentVariable != null ? new DirectoryInfo(environmentVariable) : new DirectoryInfo( Path.Combine( Paths.UserProfile, ".trydotnet", "packages")); if (!DefaultPackagesDirectory.Exists) { DefaultPackagesDirectory.Create(); } Log.Info("Packages path is {DefaultWorkspacesDirectory}", DefaultPackagesDirectory); } private int buildCount = 0; private int publishCount = 0; private bool? _isWebProject; private bool? _isUnitTestProject; private FileInfo _entryPointAssemblyPath; private static string _targetFramework; private readonly Logger _log; private readonly Subject<Budget> _fullBuildRequestChannel; private readonly IScheduler _buildThrottleScheduler; private readonly SerialDisposable _fullBuildThrottlerSubscription; private readonly SemaphoreSlim _buildSemaphore; private readonly SemaphoreSlim _publishSemaphore; private readonly Subject<Budget> _designTimeBuildRequestChannel; private readonly SerialDisposable _designTimeBuildThrottlerSubscription; private TaskCompletionSource<Workspace> _fullBuildCompletionSource = new TaskCompletionSource<Workspace>(); private TaskCompletionSource<Workspace> _designTimeBuildCompletionSource = new TaskCompletionSource<Workspace>(); private readonly object _fullBuildCompletionSourceLock = new object(); private readonly object _designTimeBuildCompletionSourceLock = new object(); protected Package( string name = null, IPackageInitializer initializer = null, DirectoryInfo directory = null, IScheduler buildThrottleScheduler = null) : base(name, initializer, directory) { Initializer = initializer ?? new PackageInitializer("console", Name); _log = new Logger($"{nameof(Package)}:{Name}"); _buildThrottleScheduler = buildThrottleScheduler ?? TaskPoolScheduler.Default; _fullBuildRequestChannel = new Subject<Budget>(); _fullBuildThrottlerSubscription = new SerialDisposable(); _designTimeBuildRequestChannel = new Subject<Budget>(); _designTimeBuildThrottlerSubscription = new SerialDisposable(); SetupWorkspaceCreationFromBuildChannel(); SetupWorkspaceCreationFromDesignTimeBuildChannel(); TryLoadDesignTimeBuildFromBuildLog(); _buildSemaphore = _packageBuildSemaphores.GetOrAdd(Name, _ => new SemaphoreSlim(1, 1)); _publishSemaphore = _packagePublishSemaphores.GetOrAdd(Name, _ => new SemaphoreSlim(1, 1)); RoslynWorkspace = null; } private void TryLoadDesignTimeBuildFromBuildLog() { if (Directory.Exists) { var binLog = this.FindLatestBinLog(); if (binLog != null) { LoadDesignTimeBuildFromBuildLogFile(this, binLog).Wait(); } } } private static async Task LoadDesignTimeBuildFromBuildLogFile(Package package, FileSystemInfo binLog) { var projectFile = package.GetProjectFile(); if (projectFile != null && binLog.LastWriteTimeUtc >= projectFile.LastWriteTimeUtc) { AnalyzerResults results; using (await FileLock.TryCreateAsync(package.Directory)) { var manager = new AnalyzerManager(); results = manager.Analyze(binLog.FullName); } if (results.Count == 0) { throw new InvalidOperationException("The build log seems to contain no solutions or projects"); } var result = results.FirstOrDefault(p => p.ProjectFilePath == projectFile.FullName); if (result != null) { package.RoslynWorkspace = null; package.DesignTimeBuildResult = result; package.LastDesignTimeBuild = binLog.LastWriteTimeUtc; if (result.Succeeded && !binLog.Name.EndsWith(DesignTimeBuildBinlogFileName)) { package.LastSuccessfulBuildTime = binLog.LastWriteTimeUtc; if (package.DesignTimeBuildResult.TryGetWorkspace(out var ws)) { package.RoslynWorkspace = ws; } } } } } private DateTimeOffset? LastDesignTimeBuild { get; set; } private DateTimeOffset? LastSuccessfulBuildTime { get; set; } public DateTimeOffset? PublicationTime { get; private set; } public bool IsUnitTestProject => _isUnitTestProject ?? (_isUnitTestProject = Directory.GetFiles("*.testadapter.dll", SearchOption.AllDirectories).Any()).Value; public bool IsWebProject { get { if (_isWebProject == null && this.GetProjectFile() is FileInfo csproj) { var csprojXml = File.ReadAllText(csproj.FullName); var xml = XElement.Parse(csprojXml); var isAspNetCore2 = xml.XPathSelectElement("//ItemGroup/PackageReference[@Include='Microsoft.AspNetCore.App']") != null; var isAspNetCore3 = xml.DescendantsAndSelf() .FirstOrDefault(n => n.Name == "Project") ?.Attribute("Sdk") ?.Value == "Microsoft.NET.Sdk.Web"; _isWebProject = isAspNetCore2 || isAspNetCore3; } return _isWebProject ?? false; } } public static DirectoryInfo DefaultPackagesDirectory { get; } public FileInfo EntryPointAssemblyPath => _entryPointAssemblyPath ?? (_entryPointAssemblyPath = this.GetEntryPointAssemblyPath(IsWebProject)); public string TargetFramework => _targetFramework ?? (_targetFramework = this.GetTargetFramework()); public Task<Workspace> CreateRoslynWorkspaceForRunAsync(Budget budget) { var shouldBuild = ShouldDoFullBuild(); if (!shouldBuild) { var ws = RoslynWorkspace ?? CreateRoslynWorkspace(); if (ws != null) { return Task.FromResult(ws); } } CreateCompletionSourceIfNeeded(ref _fullBuildCompletionSource, _fullBuildCompletionSourceLock); _fullBuildRequestChannel.OnNext(budget); return _fullBuildCompletionSource.Task; } public Task<Workspace> CreateRoslynWorkspaceForLanguageServicesAsync(Budget budget) { var shouldBuild = ShouldDoDesignTimeBuild(); if (!shouldBuild) { var ws = RoslynWorkspace ?? CreateRoslynWorkspace(); if (ws != null) { return Task.FromResult(ws); } } return RequestDesignTimeBuild(budget); } private void CreateCompletionSourceIfNeeded(ref TaskCompletionSource<Workspace> completionSource, object lockObject) { lock (lockObject) { switch (completionSource.Task.Status) { case TaskStatus.Canceled: case TaskStatus.Faulted: case TaskStatus.RanToCompletion: completionSource = new TaskCompletionSource<Workspace>(); break; } } } private void SetCompletionSourceResult(TaskCompletionSource<Workspace> completionSource, Workspace result, object lockObject) { lock (lockObject) { switch (completionSource.Task.Status) { case TaskStatus.Canceled: case TaskStatus.Faulted: case TaskStatus.RanToCompletion: return; default: completionSource.SetResult(result); break; } } } private void SetCompletionSourceException(TaskCompletionSource<Workspace> completionSource, Exception exception, object lockObject) { lock (lockObject) { switch (completionSource.Task.Status) { case TaskStatus.Canceled: case TaskStatus.Faulted: case TaskStatus.RanToCompletion: return; default: completionSource.SetException(exception); break; } } } private Task<Workspace> RequestDesignTimeBuild(Budget budget) { CreateCompletionSourceIfNeeded(ref _designTimeBuildCompletionSource, _designTimeBuildCompletionSourceLock); _designTimeBuildRequestChannel.OnNext(budget); return _designTimeBuildCompletionSource.Task; } private void SetupWorkspaceCreationFromBuildChannel() { _fullBuildThrottlerSubscription.Disposable = _fullBuildRequestChannel .Throttle(TimeSpan.FromSeconds(0.5), _buildThrottleScheduler) .ObserveOn(TaskPoolScheduler.Default) .Subscribe( async (budget) => { try { await ProcessFullBuildRequest(budget); } catch (Exception e) { SetCompletionSourceException(_fullBuildCompletionSource, e, _fullBuildCompletionSourceLock); } }, error => { SetCompletionSourceException(_fullBuildCompletionSource, error, _fullBuildCompletionSourceLock); SetupWorkspaceCreationFromBuildChannel(); }); } private void SetupWorkspaceCreationFromDesignTimeBuildChannel() { _designTimeBuildThrottlerSubscription.Disposable = _designTimeBuildRequestChannel .Throttle(TimeSpan.FromSeconds(0.5), _buildThrottleScheduler) .ObserveOn(TaskPoolScheduler.Default) .Subscribe( async (budget) => { try { await ProcessDesignTimeBuildRequest(budget); } catch (Exception e) { SetCompletionSourceException(_designTimeBuildCompletionSource, e, _designTimeBuildCompletionSourceLock); } }, error => { SetCompletionSourceException(_designTimeBuildCompletionSource, error, _designTimeBuildCompletionSourceLock); SetupWorkspaceCreationFromDesignTimeBuildChannel(); }); } private async Task ProcessFullBuildRequest(Budget budget) { await EnsureCreated().CancelIfExceeds(budget); await EnsureBuilt().CancelIfExceeds(budget); var ws = CreateRoslynWorkspace(); if (IsWebProject) { await EnsurePublished().CancelIfExceeds(budget); } SetCompletionSourceResult(_fullBuildCompletionSource, ws, _fullBuildCompletionSourceLock); } private async Task ProcessDesignTimeBuildRequest(Budget budget) { await EnsureCreated().CancelIfExceeds(budget); await EnsureDesignTimeBuilt().CancelIfExceeds(budget); var ws = CreateRoslynWorkspace(); SetCompletionSourceResult(_designTimeBuildCompletionSource, ws, _designTimeBuildCompletionSourceLock); } private Workspace CreateRoslynWorkspace() { var build = DesignTimeBuildResult; if (build == null) { throw new InvalidOperationException("No design time or full build available"); } var ws = build.GetWorkspace(); if (!ws.CanBeUsedToGenerateCompilation()) { RoslynWorkspace = null; DesignTimeBuildResult = null; LastDesignTimeBuild = null; throw new InvalidOperationException("The roslyn workspace cannot be used to generate a compilation"); } var projectId = ws.CurrentSolution.ProjectIds.FirstOrDefault(); var references = build.References; var metadataReferences = references.GetMetadataReferences(); var solution = ws.CurrentSolution; solution = solution.WithProjectMetadataReferences(projectId, metadataReferences); ws.TryApplyChanges(solution); RoslynWorkspace = ws; return ws; } protected Workspace RoslynWorkspace { get; set; } public override async Task EnsureReady(Budget budget) { await base.EnsureReady(budget); if (RequiresPublish) { await EnsurePublished().CancelIfExceeds(budget); } budget.RecordEntry(); } protected override async Task EnsureBuilt([CallerMemberName] string caller = null) { using (var operation = _log.OnEnterAndConfirmOnExit()) { await EnsureCreated(); if (ShouldDoFullBuild()) { await FullBuild(); } else { operation.Info("Workspace already built"); } operation.Succeed(); } } protected async Task EnsureDesignTimeBuilt([CallerMemberName] string caller = null) { await EnsureCreated(); using (var operation = _log.OnEnterAndConfirmOnExit()) { if (ShouldDoDesignTimeBuild()) { await DesignTimeBuild(); } else { operation.Info("Workspace already built"); } operation.Succeed(); } } public virtual async Task EnsurePublished() { await EnsureBuilt(); using (var operation = _log.OnEnterAndConfirmOnExit()) { if (PublicationTime == null || PublicationTime < LastSuccessfulBuildTime) { await Publish(); } operation.Succeed(); } } public bool RequiresPublish => IsWebProject; public override async Task FullBuild() { using (var operation = Log.OnEnterAndConfirmOnExit()) { try { operation.Info("Building package {name}", Name); // When a build finishes, buildCount is reset to 0. If, when we increment // the value, we get a value > 1, someone else has already started another // build var buildInProgress = Interlocked.Increment(ref buildCount) > 1; await _buildSemaphore.WaitAsync(); using (Disposable.Create(() => _buildSemaphore.Release())) { if (buildInProgress) { operation.Info("Skipping build for package {name}", Name); return; } using (await FileLock.TryCreateAsync(Directory)) { await DotnetBuild(); } } operation.Info("Workspace built"); operation.Succeed(); } catch (Exception exception) { operation.Error("Exception building workspace", exception); } var binLog = this.FindLatestBinLog(); await binLog.WaitForFileAvailable(); await LoadDesignTimeBuildFromBuildLogFile(this, binLog); Interlocked.Exchange(ref buildCount, 0); } } protected async Task Publish() { using (var operation = _log.OnEnterAndConfirmOnExit()) { operation.Info("Publishing package {name}", Name); var publishInProgress = Interlocked.Increment(ref publishCount) > 1; await _publishSemaphore.WaitAsync(); if (publishInProgress) { operation.Info("Skipping publish for package {name}", Name); return; } CommandLineResult result; using (Disposable.Create(() => _publishSemaphore.Release())) { operation.Info("Publishing workspace in {directory}", Directory); result = await new Dotnet(Directory) .Publish("--no-dependencies --no-restore --no-build"); } result.ThrowOnFailure(); operation.Info("Workspace published"); operation.Succeed(); PublicationTime = Clock.Current.Now(); Interlocked.Exchange(ref publishCount, 0); } } public override string ToString() { return $"{Name} ({Directory.FullName})"; } public Task<Workspace> CreateRoslynWorkspaceAsync(Budget budget) { return CreateRoslynWorkspaceForRunAsync(budget); } protected SyntaxTree CreateInstrumentationEmitterSyntaxTree() { var resourceName = "WorkspaceServer.Servers.Roslyn.Instrumentation.InstrumentationEmitter.cs"; var assembly = typeof(PackageExtensions).Assembly; using (var stream = assembly.GetManifestResourceStream(resourceName)) using (var reader = new StreamReader(stream ?? throw new InvalidOperationException($"Resource \"{resourceName}\" not found"), Encoding.UTF8)) { var source = reader.ReadToEnd(); var parseOptions = DesignTimeBuildResult.GetCSharpParseOptions(); var syntaxTree = CSharpSyntaxTree.ParseText(SourceText.From(source), parseOptions); return syntaxTree; } } protected AnalyzerResult DesignTimeBuildResult { get; set; } protected virtual bool ShouldDoFullBuild() { return LastSuccessfulBuildTime == null || ShouldDoDesignTimeBuild() || (LastDesignTimeBuild > LastSuccessfulBuildTime); } protected virtual bool ShouldDoDesignTimeBuild() { return DesignTimeBuildResult == null || DesignTimeBuildResult.Succeeded == false; } protected async Task<AnalyzerResult> DesignTimeBuild() { using (var operation = _log.OnEnterAndConfirmOnExit()) { AnalyzerResult result; var csProj = this.GetProjectFile(); var logWriter = new StringWriter(); using (await FileLock.TryCreateAsync(Directory)) { var manager = new AnalyzerManager(new AnalyzerManagerOptions { LogWriter = logWriter }); var analyzer = manager.GetProject(csProj.FullName); analyzer.AddBinaryLogger(Path.Combine(Directory.FullName, DesignTimeBuildBinlogFileName)); var languageVersion = csProj.SuggestedLanguageVersion(); analyzer.SetGlobalProperty("langVersion", languageVersion); result = analyzer.Build().Results.First(); } DesignTimeBuildResult = result; LastDesignTimeBuild = Clock.Current.Now(); if (result.Succeeded == false) { var logData = logWriter.ToString(); File.WriteAllText( LastBuildErrorLogFile.FullName, string.Join(Environment.NewLine, "Design Time Build Error", logData)); } else if (LastBuildErrorLogFile.Exists) { LastBuildErrorLogFile.Delete(); } operation.Succeed(); return result; } } public virtual SyntaxTree GetInstrumentationEmitterSyntaxTree() => CreateInstrumentationEmitterSyntaxTree(); } }
37.557508
154
0.559823
[ "MIT" ]
0xblack/try
WorkspaceServer/Packaging/Package.cs
23,511
C#
// // Copyright 2020 Google LLC // // 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 Google.Solutions.CloudIap; using Google.Solutions.Compute.Auth; using Google.Solutions.Compute.Iap; using Google.Solutions.IapDesktop.Application.ObjectModel; using Google.Solutions.IapDesktop.Application.Services.Windows.ProjectExplorer; using Google.Solutions.IapDesktop.Application.Services.Adapters; using Google.Solutions.IapDesktop.Application.Services.Integration; using Google.Solutions.IapDesktop.Application.Services.Persistence; using Google.Solutions.IapDesktop.Application.Services.Windows; using Google.Solutions.IapDesktop.Application.Services.Windows.RemoteDesktop; using Google.Solutions.IapDesktop.Application.Services.Windows.TunnelsViewer; using Google.Solutions.IapDesktop.Application.Services.Workflows; using Google.Solutions.IapDesktop.Application.Util; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; #pragma warning disable IDE1006 // Naming Styles namespace Google.Solutions.IapDesktop.Windows { public partial class MainForm : Form, IJobHost, IMainForm, IAuthorizationAdapter { private readonly ApplicationSettingsRepository applicationSettings; private readonly AuthSettingsRepository authSettings; private readonly IServiceProvider serviceProvider; private readonly AppProtocolRegistry protocolRegistry; private WaitDialog waitDialog = null; public IapRdpUrl StartupUrl { get; set; } public MainForm(IServiceProvider bootstrappingServiceProvider, IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; this.applicationSettings = bootstrappingServiceProvider.GetService<ApplicationSettingsRepository>(); this.authSettings = bootstrappingServiceProvider.GetService<AuthSettingsRepository>(); this.protocolRegistry = bootstrappingServiceProvider.GetService<AppProtocolRegistry>(); // // Restore window settings. // var windowSettings = this.applicationSettings.GetSettings(); if (windowSettings.IsMainWindowMaximized) { this.WindowState = FormWindowState.Maximized; InitializeComponent(); } else if (windowSettings.MainWindowHeight != 0 && windowSettings.MainWindowWidth != 0) { InitializeComponent(); this.Size = new Size( windowSettings.MainWindowWidth, windowSettings.MainWindowHeight); } else { InitializeComponent(); } // Set fixed size for the left/right panels. this.dockPanel.DockLeftPortion = this.dockPanel.DockRightPortion = (300.0f / this.Width); this.checkForUpdatesOnExitToolStripMenuItem.Checked = this.applicationSettings.GetSettings().IsUpdateCheckEnabled; this.enableAppProtocolToolStripMenuItem.Checked = this.protocolRegistry.IsRegistered(IapRdpUrl.Scheme, GetType().Assembly.Location); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { var settings = this.applicationSettings.GetSettings(); if (settings.IsUpdateCheckEnabled && (DateTime.UtcNow - DateTime.FromBinary(settings.LastUpdateCheck)).Days > 7) { // Time to check for updates again. try { var updateService = this.serviceProvider.GetService<IUpdateService>(); updateService.CheckForUpdates( this, TimeSpan.FromSeconds(5), out bool donotCheckForUpdatesAgain); settings.IsUpdateCheckEnabled = !donotCheckForUpdatesAgain; settings.LastUpdateCheck = DateTime.UtcNow.ToBinary(); } catch (Exception) { // Nevermind. } } // Save window state. settings.IsMainWindowMaximized = this.WindowState == FormWindowState.Maximized; settings.MainWindowHeight = this.Size.Height; settings.MainWindowWidth = this.Size.Width; this.applicationSettings.SetSettings(settings); } private void MainForm_Load(object sender, EventArgs e) { } private void MainForm_Shown(object sender, EventArgs _) { // // Authorize. // try { this.Authorization = AuthorizeDialog.Authorize( this, OAuthClient.Secrets, new[] { IapTunnelingEndpoint.RequiredScope }, this.authSettings); } catch (Exception e) { this.serviceProvider .GetService<IExceptionDialog>() .Show(this, "Authorization failed", e); } if (this.Authorization == null) { // Not authorized -> close. Close(); return; } // // Set up sub-windows. // SuspendLayout(); this.dockPanel.Theme = this.vs2015LightTheme; this.vsToolStripExtender.SetStyle( this.mainMenu, VisualStudioToolStripExtender.VsVersion.Vs2015, this.vs2015LightTheme); this.vsToolStripExtender.SetStyle( this.statusStrip, VisualStudioToolStripExtender.VsVersion.Vs2015, this.vs2015LightTheme); // Show who is signed in. this.toolStripEmail.Text = this.Authorization.Email; ResumeLayout(); if (this.StartupUrl != null) { // Dispatch URL. ConnectToUrl(this.StartupUrl); } else { // No startup URL provided, just show project explorer then. this.serviceProvider.GetService<IProjectExplorer>().ShowWindow(); } #if DEBUG this.serviceProvider.GetService<DebugWindow>().ShowWindow(); #endif } internal void ConnectToUrl(IapRdpUrl url) { var rdcService = this.serviceProvider .GetService<RemoteDesktopConnectionService>(); var vmNode = this.serviceProvider .GetService<IProjectExplorer>() .TryFindNode(url.Instance); if (vmNode != null) { // We have a full set of settings for this VM, so use that. rdcService .ActivateOrConnectInstanceWithCredentialPromptAsync(this, vmNode) .ContinueWith(t => this.serviceProvider .GetService<IExceptionDialog>() .Show(this, "Failed to connect to VM instance", t.Exception), CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext()); } else { // We do not know anything other than what's in the URL. rdcService .ActivateOrConnectInstanceWithCredentialPromptAsync(this, url) .ContinueWith(t => this.serviceProvider .GetService<IExceptionDialog>() .Show(this, "Failed to connect to VM instance", t.Exception), CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext()); } } //--------------------------------------------------------------------- // IMainForm. //--------------------------------------------------------------------- public DockPanel MainPanel => this.dockPanel; //--------------------------------------------------------------------- // Main menu events. //--------------------------------------------------------------------- private void aboutToolStripMenuItem_Click(object sender, EventArgs _) { this.serviceProvider.GetService<AboutWindow>().ShowDialog(this); } private void exitToolStripMenuItem_Click(object sender, EventArgs _) { Close(); } private async void signoutToolStripMenuItem_Click(object sender, EventArgs _) { try { await this.Authorization.RevokeAsync(); MessageBox.Show( this, "The authorization for this application has been revoked.\n\n" + "You will be prompted to sign in again the next time you start the application.", "Signed out", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception e) { this.serviceProvider .GetService<IExceptionDialog>() .Show(this, "Sign out", e); } } private void projectExplorerToolStripMenuItem_Click(object sender, EventArgs _) { this.serviceProvider.GetService<IProjectExplorer>().ShowWindow(); } private void openIapDocsToolStripMenuItem_Click(object sender, EventArgs _) { this.serviceProvider.GetService<CloudConsoleService>().OpenIapOverviewDocs(); } private void openIapAccessDocsToolStripMenuItem_Click(object sender, EventArgs _) { this.serviceProvider.GetService<CloudConsoleService>().OpenIapAccessDocs(); } private void activeTunnelsToolStripMenuItem_Click(object sender, EventArgs e) { this.serviceProvider.GetService<ITunnelsViewer>().ShowWindow(); } private void reportIssueToolStripMenuItem_Click(object sender, EventArgs e) { this.serviceProvider.GetService<GithubAdapter>().ReportIssue(); } private async void addProjectToolStripMenuItem_Click(object sender, EventArgs _) { try { await this.serviceProvider.GetService<IProjectExplorer>().ShowAddProjectDialogAsync(); } catch (TaskCanceledException) { // Ignore. } catch (Exception e) { this.serviceProvider .GetService<IExceptionDialog>() .Show(this, "Adding project failed", e); } } private void enableloggingToolStripMenuItem_Click(object sender, EventArgs _) { var loggingEnabled = this.enableloggingToolStripMenuItem.Checked = !this.enableloggingToolStripMenuItem.Checked; try { Program.IsLoggingEnabled = loggingEnabled; if (loggingEnabled) { this.toolStripStatus.Text = $"Logging to {Program.LogFile}, performance " + "might be degraded while logging is enabled."; this.statusStrip.BackColor = Color.Red; } else { this.toolStripStatus.Text = string.Empty; this.statusStrip.BackColor = this.vs2015LightTheme.ColorPalette.ToolWindowCaptionActive.Background; } } catch (Exception e) { this.serviceProvider .GetService<IExceptionDialog>() .Show(this, "Configuring logging failed", e); } } private void enableAppProtocolToolStripMenuItem_Click(object sender, EventArgs e) { var registerProtocol = this.enableAppProtocolToolStripMenuItem.Checked = !this.enableAppProtocolToolStripMenuItem.Checked; if (registerProtocol) { this.protocolRegistry.Register(IapRdpUrl.Scheme, this.Text, GetType().Assembly.Location); } else { this.protocolRegistry.Unregister(IapRdpUrl.Scheme); } } private void checkForUpdatesOnExitToolStripMenuItem_Click(object sender, EventArgs e) { var updateEnabled = !checkForUpdatesOnExitToolStripMenuItem.Checked; var settings = this.applicationSettings.GetSettings(); settings.IsUpdateCheckEnabled = updateEnabled; this.applicationSettings.SetSettings(settings); // Toggle menu. checkForUpdatesOnExitToolStripMenuItem.Checked = !checkForUpdatesOnExitToolStripMenuItem.Checked; } private void desktopToolStripMenuItem_DropDownOpening(object sender, EventArgs e) { var session = this.serviceProvider.GetService<IRemoteDesktopService>().ActiveSession; foreach (var item in this.desktopToolStripMenuItem.DropDownItems.OfType<ToolStripDropDownItem>()) { item.Enabled = session != null && session.IsConnected; } } private void fullScreenToolStripMenuItem_Click(object sender, EventArgs args) => DoWithActiveSession(session => session.TrySetFullscreen(true)); private void disconnectToolStripMenuItem_Click(object sender, EventArgs args) => DoWithActiveSession(session => session.Close()); private void showSecurityScreenToolStripMenuItem_Click(object sender, EventArgs args) => DoWithActiveSession(session => session.ShowSecurityScreen()); private void showtaskManagerToolStripMenuItem_Click(object sender, EventArgs args) => DoWithActiveSession(session => session.ShowTaskManager()); private void DoWithActiveSession(Action<IRemoteDesktopSession> action) { try { var session = this.serviceProvider.GetService<IRemoteDesktopService>().ActiveSession; if (session != null) { action(session); } } catch (Exception e) { this.serviceProvider .GetService<IExceptionDialog>() .Show(this, "Remote Desktop action failed", e); } } //--------------------------------------------------------------------- // IAuthorizationService. //--------------------------------------------------------------------- public IAuthorization Authorization { get; private set; } public async Task ReauthorizeAsync(CancellationToken token) { await this.Authorization.ReauthorizeAsync(token); // Update status bar in case the user switched identities. this.toolStripEmail.Text = this.Authorization.Email; } //--------------------------------------------------------------------- // IEventRoutingHost. //--------------------------------------------------------------------- public ISynchronizeInvoke Invoker => this; public bool IsWaitDialogShowing { get { // Capture variable in local context first to avoid a race condition. var dialog = this.waitDialog; return dialog != null && dialog.IsShowing; } } public void ShowWaitDialog(JobDescription jobDescription, CancellationTokenSource cts) { Debug.Assert(!this.Invoker.InvokeRequired, "ShowWaitDialog must be called on UI thread"); this.waitDialog = new WaitDialog(jobDescription.StatusMessage, cts); this.waitDialog.ShowDialog(this); } public void CloseWaitDialog() { Debug.Assert(!this.Invoker.InvokeRequired, "CloseWaitDialog must be called on UI thread"); Debug.Assert(this.waitDialog != null); this.waitDialog.Close(); } public bool ConfirmReauthorization() { return MessageBox.Show( this, "Your session has expired or the authorization has been revoked. " + "Do you want to sign in again?", "Authorization required", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes; } } internal abstract class AsyncEvent { public string WaitMessage { get; } protected AsyncEvent(string message) { this.WaitMessage = message; } } }
37.445361
119
0.570343
[ "Apache-2.0" ]
Mdlglobal-atlassian-net/iap-desktop
Google.Solutions.IapDesktop/Windows/MainForm.cs
18,163
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/gdipluseffects.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; namespace TerraFX.Interop.Gdiplus.UnitTests; /// <summary>Provides validation of the <see cref="ColorMatrixEffect" /> struct.</summary> public static unsafe partial class ColorMatrixEffectTests { /// <summary>Validates that the <see cref="ColorMatrixEffect" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<ColorMatrixEffect>(), Is.EqualTo(sizeof(ColorMatrixEffect))); } /// <summary>Validates that the <see cref="ColorMatrixEffect" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(ColorMatrixEffect).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="ColorMatrixEffect" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(ColorMatrixEffect), Is.EqualTo(40)); } else { Assert.That(sizeof(ColorMatrixEffect), Is.EqualTo(20)); } } }
34.906977
145
0.692205
[ "MIT" ]
tannergooding/terrafx.interop.windows
tests/Interop/Windows/Gdiplus/um/gdipluseffects/ColorMatrixEffectTests.cs
1,503
C#
#if LEGACY_NAMESPACE using AutoFilterer.Enums; #endif using AutoFilterer.Abstractions; using AutoFilterer.Attributes; using System.Data; using System.Linq; namespace AutoFilterer.Types; public class OrderableFilterBase : FilterBase, IOrderable { [IgnoreFilter] public virtual Sorting SortBy { get; set; } [IgnoreFilter] public virtual string Sort { get; set; } public override IQueryable<TEntity> ApplyFilterTo<TEntity>(IQueryable<TEntity> query) { if (string.IsNullOrEmpty(Sort)) return base.ApplyFilterTo(query); return this.ApplyOrder(base.ApplyFilterTo(query)); } public virtual IOrderedQueryable<TSource> ApplyOrder<TSource>(IQueryable<TSource> source) => OrderableBase.ApplyOrder(source, this); public virtual IQueryable<TSource> ApplyFilterWithoutOrdering<TSource>(IQueryable<TSource> source) => base.ApplyFilterTo(source); }
29.451613
102
0.743702
[ "MIT" ]
mehmetuken/AutoFilterer
src/AutoFilterer/Types/OrderableFilterBase.cs
915
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Nuget.PackageIndex.Logging { public interface ILogProvider { void WriteVerbose(string format, params object[] args); void WriteInformation(string format, params object[] args); void WriteError(string format, params object[] args); } }
34.615385
111
0.715556
[ "Apache-2.0" ]
ConnectionMaster/NuGet.PackageIndex
src/Nuget.PackageIndex/Logging/ILogProvider.cs
452
C#
using System.Collections.Generic; namespace Phytime.Models.Feed { public class Feed { public int Id { get; set; } public string Title { get; set; } public string Url { get; set; } public int ItemsCount { get; set; } public List<User> Users { get; set; } = new List<User>(); } }
23.714286
65
0.578313
[ "Apache-2.0" ]
ArtemGontar/phytime
src/Models/Feed/Feed.cs
334
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; using Esfa.Recruit.Vacancies.Client.Infrastructure.Mongo; using Esfa.Recruit.Vacancies.Client.Infrastructure.QueryStore.Projections; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MongoDB.Driver; using Polly; namespace Esfa.Recruit.Vacancies.Client.Infrastructure.QueryStore { internal sealed class MongoQueryStore : MongoDbCollectionBase, IQueryStore, IQueryStoreHouseKeepingService { public MongoQueryStore(ILoggerFactory loggerFactory, IOptions<MongoDbConnectionDetails> details) : base(loggerFactory, MongoDbNames.RecruitDb, MongoDbCollectionNames.QueryStore, details) { } Task IQueryStore.DeleteAsync<T>(string typeName, string key) { var collection = GetCollection<T>(); var filterBuilder = Builders<T>.Filter; var filter = filterBuilder.Eq(d => d.ViewType, typeName) & filterBuilder.Eq(d => d.Id, key); return RetryPolicy.Execute(_ => collection.DeleteOneAsync(filter), new Context(nameof(IQueryStore.DeleteAsync))); } public async Task<long> DeleteManyLessThanAsync<T, T1>(string typeName, Expression<Func<T, T1>> property, T1 value) where T : QueryProjectionBase { var filterBuilder = Builders<T>.Filter; var filter = filterBuilder.Eq(d => d.ViewType, typeName) & filterBuilder.Lt(property, value); var collection = GetCollection<T>(); var result = await RetryPolicy.Execute(_ => collection.DeleteManyAsync(filter), new Context(nameof(IQueryStore.DeleteManyLessThanAsync))); return result.DeletedCount; } public async Task<long> DeleteAllAsync<T>(string typeName) where T : QueryProjectionBase { var filterBuilder = Builders<T>.Filter; var filter = filterBuilder.Eq(d => d.ViewType, typeName); var collection = GetCollection<T>(); var result = await RetryPolicy.Execute(_ => collection.DeleteManyAsync(filter), new Context(nameof(IQueryStore.DeleteManyLessThanAsync))); return result.DeletedCount; } async Task<T> IQueryStore.GetAsync<T>(string typeName, string key) { var filterBuilder = Builders<T>.Filter; var filter = filterBuilder.Eq(d => d.ViewType, typeName) & filterBuilder.Eq(d => d.Id, key); var collection = GetCollection<T>(); var result = await RetryPolicy.Execute(_ => collection.Find(filter).FirstOrDefaultAsync(), new Context(nameof(IQueryStore.GetAsync))); return result; } async Task<T> IQueryStore.GetAsync<T>(string key) { var filterBuilder = Builders<T>.Filter; var filter = filterBuilder.Eq(d => d.Id, key); var collection = GetCollection<T>(); var result = await RetryPolicy.Execute(_ => collection.Find(filter).FirstOrDefaultAsync(), new Context(nameof(IQueryStore.GetAsync))); return result; } Task IQueryStore.UpsertAsync<T>(T item) { var collection = GetCollection<T>(); var filterBuilder = Builders<T>.Filter; var filter = filterBuilder.Eq(d => d.ViewType, item.ViewType) & filterBuilder.Eq(d => d.Id, item.Id); return RetryPolicy.Execute(_ => collection.ReplaceOneAsync(filter, item, new UpdateOptions { IsUpsert = true }), new Context(nameof(IQueryStore.UpsertAsync))); } public async Task<List<T>> GetStaleDocumentsAsync<T>(string typeName, DateTime documentsNotAccessedSinceDate) where T : QueryProjectionBase { var filterBuilder = Builders<T>.Filter; var filter = filterBuilder.Eq(d => d.ViewType, typeName) & filterBuilder.Lt(d => d.LastUpdated, documentsNotAccessedSinceDate); var collection = GetCollection<T>(); return await RetryPolicy.Execute(_ => collection.Find(filter).ToListAsync(), new Context(nameof(IQueryStore.UpsertAsync))); } public async Task<long> DeleteStaleDocumentsAsync<T>(string typeName, IEnumerable<string> documentIds) where T : QueryProjectionBase { var filterBuilder = Builders<T>.Filter; var filter = filterBuilder.In(d => d.Id, documentIds) & filterBuilder.Eq(d => d.ViewType, typeName); var collection = GetCollection<T>(); var result = await RetryPolicy.Execute(_ => collection.DeleteManyAsync(filter), new Context(nameof(IQueryStore.UpsertAsync))); return result.DeletedCount; } } }
36.785714
153
0.61068
[ "MIT" ]
SkillsFundingAgency/das-recru
src/Shared/Recruit.Vacancies.Client/Infrastructure/QueryStore/MongoQueryStore.cs
5,150
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using TeleSharp.TL; namespace TeleSharp.TL { [TLObject(1471006352)] public class TLPhoneCallDiscardReasonHangup : TLAbsPhoneCallDiscardReason { public override int Constructor { get { return 1471006352; } } public void ComputeFlags() { } public override void DeserializeBody(BinaryReader br) { } public override void SerializeBody(BinaryWriter bw) { bw.Write(this.Constructor); } } }
17.525
77
0.589158
[ "MIT" ]
slctr/Men.Telegram.ClientApi
Men.Telegram.ClientApi/TL/TL/TLPhoneCallDiscardReasonHangup.cs
701
C#
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; namespace CarDealer.Data.Migrations { public partial class initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Cars", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Make = table.Column<string>(nullable: true), Model = table.Column<string>(nullable: true), TravelledDistance = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Cars", x => x.Id); }); migrationBuilder.CreateTable( name: "Customers", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), BirthDate = table.Column<DateTime>(nullable: false), IsYoungDriver = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Customers", x => x.Id); }); migrationBuilder.CreateTable( name: "Suppliers", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), IsImporter = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Suppliers", x => x.Id); }); migrationBuilder.CreateTable( name: "Sales", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CarId = table.Column<int>(nullable: false), CustomerId = table.Column<int>(nullable: false), Discount = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Sales", x => x.Id); table.ForeignKey( name: "FK_Sales_Cars_CarId", column: x => x.CarId, principalTable: "Cars", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Sales_Customers_CustomerId", column: x => x.CustomerId, principalTable: "Customers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Parts", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), Price = table.Column<decimal>(nullable: false), Qunatity = table.Column<int>(nullable: false), SupplierId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Parts", x => x.Id); table.ForeignKey( name: "FK_Parts_Suppliers_SupplierId", column: x => x.SupplierId, principalTable: "Suppliers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "PartCars", columns: table => new { CarId = table.Column<int>(nullable: false), PartId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_PartCars", x => new { x.CarId, x.PartId }); table.ForeignKey( name: "FK_PartCars_Cars_CarId", column: x => x.CarId, principalTable: "Cars", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_PartCars_Parts_PartId", column: x => x.PartId, principalTable: "Parts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_PartCars_PartId", table: "PartCars", column: "PartId"); migrationBuilder.CreateIndex( name: "IX_Parts_SupplierId", table: "Parts", column: "SupplierId"); migrationBuilder.CreateIndex( name: "IX_Sales_CarId", table: "Sales", column: "CarId"); migrationBuilder.CreateIndex( name: "IX_Sales_CustomerId", table: "Sales", column: "CustomerId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "PartCars"); migrationBuilder.DropTable( name: "Sales"); migrationBuilder.DropTable( name: "Parts"); migrationBuilder.DropTable( name: "Cars"); migrationBuilder.DropTable( name: "Customers"); migrationBuilder.DropTable( name: "Suppliers"); } } }
39.976471
122
0.472042
[ "MIT" ]
mayapeneva/DATABASE-Advanced-Entity-Framework
10.XMLProcessing_CarDealer/CarDealer.Data/Migrations/20180730164323_initial.cs
6,798
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using NSuperTest.Server; using System; using System.Collections.Generic; using System.Text; namespace NSuperTest.Registration.NetCoreServer { public class NetCoreServerBuilder<T> : IServerBuilder where T : class { private static object _outer = new object(); private static IWebHost _host = null; private static IWebHostBuilder _builder = null; private const string _httpUrl = "http://[::1]:0"; public NetCoreServerBuilder() { _builder = AddDefaultHost(new WebHostBuilder()); } public void WithConfig(IConfigurationBuilder configBuilder) { var config = configBuilder.Build(); _builder.UseConfiguration(config); } public void WithBuilder(IWebHostBuilder builder) { _builder = AddDefaultHost(builder); } private IWebHostBuilder AddDefaultHost(IWebHostBuilder builder) { return builder .UseKestrel() .UseUrls(new string[] { _httpUrl }) .UseStartup<T>(); } public IServer Build() { lock(_outer) { if(_host == null) { _host = _builder.Build(); _host.Start(); } } return new NetCoreServer(_host); } } }
26.844828
72
0.538857
[ "MIT" ]
pshort/nsupertest
NSuperTest/Registration/NetCoreServer/NetCoreServerBuilder.cs
1,559
C#
using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Xunit; namespace Meziantou.Framework.Tests { public sealed class StreamExtensionsTests { [Theory] [InlineData(false)] [InlineData(true)] public void ReadToEndTests(bool canSeek) { using var stream = new MemoryStream(); Enumerable.Range(0, 5).ForEach(i => stream.WriteByte((byte)i)); stream.Seek(0, SeekOrigin.Begin); using var byteByByteStream = new CustomStream(stream, canSeek); var result = byteByByteStream.ReadToEnd(); result.Should().Equal(new byte[] { 0, 1, 2, 3, 4 }); } [Theory] [InlineData(false)] [InlineData(true)] public async Task ReadToEndAsyncTests(bool canSeek) { using var stream = new MemoryStream(); Enumerable.Range(0, 5).ForEach(i => stream.WriteByte((byte)i)); stream.Seek(0, SeekOrigin.Begin); using var byteByByteStream = new CustomStream(stream, canSeek); var result = await byteByByteStream.ReadToEndAsync(); result.Should().Equal(new byte[] { 0, 1, 2, 3, 4 }); } [Theory] [InlineData(false)] [InlineData(true)] public void TryReadAllTests(bool canSeek) { using var stream = new MemoryStream(); Enumerable.Range(0, 5).ForEach(i => stream.WriteByte((byte)i)); stream.Seek(0, SeekOrigin.Begin); using var byteByByteStream = new CustomStream(stream, canSeek); var buffer = new byte[5]; byteByByteStream.TryReadAll(buffer, 0, 5); buffer.Should().Equal(new byte[] { 0, 1, 2, 3, 4 }); } [Theory] [InlineData(false)] [InlineData(true)] public async Task TryReadAllAsyncTests(bool canSeek) { using var stream = new MemoryStream(); Enumerable.Range(0, 5).ForEach(i => stream.WriteByte((byte)i)); stream.Seek(0, SeekOrigin.Begin); using var byteByByteStream = new CustomStream(stream, canSeek); var buffer = new byte[5]; await byteByByteStream.TryReadAllAsync(buffer, 0, 5); buffer.Should().Equal(new byte[] { 0, 1, 2, 3, 4 }); } private sealed class CustomStream : Stream { private readonly Stream _stream; private readonly bool _canSeek; public CustomStream(Stream stream, bool canSeek) { _stream = stream; _canSeek = canSeek; } public override bool CanRead => _stream.CanRead; public override bool CanSeek => _canSeek && _stream.CanSeek; public override bool CanWrite => throw new NotSupportedException(); public override long Length => _stream.Length; public override long Position { get => _stream.Position; set => throw new NotSupportedException(); } public override void Flush() => throw new NotSupportedException(); public override int Read(byte[] buffer, int offset, int count) { return _stream.Read(buffer, offset, 1); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _stream.ReadAsync(buffer, offset, 1, cancellationToken); } public override int Read(Span<byte> buffer) { return _stream.Read(buffer[0..1]); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) { return _stream.ReadAsync(buffer[0..1], cancellationToken); } public override long Seek(long offset, SeekOrigin origin) => _stream.Seek(offset, origin); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); } } }
35.272727
122
0.586223
[ "MIT" ]
fasteddys/Meziantou.Framework
tests/Meziantou.Framework.Tests/StreamExtensionsTests.cs
4,270
C#
using System; using System.Buffers.Binary; using System.IO; namespace Subspace.Stun { public class StunRecordWriter { public static void Write(StunRecord record, Stream stream) { var padLen = record.MessageIntegrity is null ? 8 : 32; var bytes = new byte[StunConstants.RecordHeaderLength + record.MessageLength + padLen]; var idx = 0; BinaryPrimitives.WriteInt16BigEndian(bytes.AsSpan(idx), (short)record.MessageType); idx += 2; BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(idx), (ushort)(record.MessageLength + padLen /*size of MessageIntegrity and Fingerprint*/)); idx += 2; BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(idx), StunRecord.MessageCookie); idx += 4; record.MessageTransactionId.CopyTo(bytes.AsSpan(idx)); idx += record.MessageTransactionId.Length; foreach (var attr in record.StunAttributes) { BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(idx), (ushort)attr.Type); idx += 2; BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(idx), attr.Length); idx += 2; if (attr.Value != null) { attr.Value.CopyTo(bytes.AsSpan(idx)); idx += attr.Value.Length; } idx += attr.Padding; } var miRec = record.MessageIntegrity; if (miRec != null) { BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(idx), (ushort)miRec.Type); idx += 2; BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(idx), miRec.Length); idx += 2; miRec.Value.CopyTo(bytes.AsSpan(idx)); idx += miRec.Value.Length; } var fiRec = record.Fingerprint; BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(idx), (ushort)fiRec.Type); idx += 2; BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(idx), fiRec.Length); idx += 2; fiRec.Value.CopyTo(bytes.AsSpan(idx)); stream.Write(bytes); } } }
36.709677
155
0.566344
[ "MIT" ]
ztittle/Subspace
src/Subspace.Stun/StunRecordWriter.cs
2,278
C#
using System.IO; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.SignalRService; namespace ServerlessApp { public static class ChatFunction { [FunctionName("chat")] public static IActionResult Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, [CosmosDB( databaseName: "chat", collectionName: "messages", ConnectionStringSetting = "CosmosDBConnection")]out dynamic document, [SignalR(HubName = "km")] IAsyncCollector<SignalRMessage> signalRMessages, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string requestBody = new StreamReader(req.Body).ReadToEnd(); ChatMessage data = JsonConvert.DeserializeObject<ChatMessage>(requestBody); document = data; signalRMessages.AddAsync(new SignalRMessage() { Target = "chatMessage", Arguments = new object[] { data } }).Wait(); return new OkObjectResult(document); } } }
33.8
94
0.637574
[ "MIT" ]
bibistroc/KMCraiova2018
src/backend/ServerlessApp/ChatFunction.cs
1,352
C#
using Pliant.Utilities; namespace Pliant.Languages.Regex { public abstract class RegexAtom : RegexNode { public override RegexNodeType NodeType { get { return RegexNodeType.RegexAtom; } } } public class RegexAtomAny : RegexAtom { const string Dot = "."; public override RegexNodeType NodeType { get { return RegexNodeType.RegexAtomAny; } } public override string ToString() { return Dot; } public override bool Equals(object obj) { if (obj is null) return false; if (!(obj is RegexAtomAny any)) return false; return true; } public override int GetHashCode() { return Dot.GetHashCode(); } } public class RegexAtomCharacter : RegexAtom { public RegexCharacter Character { get; private set; } public RegexAtomCharacter(RegexCharacter character) { Character = character; _hashCode = ComputeHashCode(); } public override bool Equals(object obj) { if (obj is null) return false; if (!(obj is RegexAtomCharacter atomCharacter)) return false; return Character.Equals(atomCharacter.Character); } private readonly int _hashCode; public override int GetHashCode() { return _hashCode; } private int ComputeHashCode() { return HashCode.Compute(Character.GetHashCode()); } public override RegexNodeType NodeType { get { return RegexNodeType.RegexAtomCharacter; } } public override string ToString() { return Character.ToString(); } } public class RegexAtomExpression : RegexAtom { public RegexExpression Expression { get; private set; } public RegexAtomExpression(RegexExpression expression) { Expression = expression; _hashCode = ComputeHashCode(); } public override bool Equals(object obj) { if (obj is null) return false; if (!(obj is RegexAtomExpression atomExpression)) return false; return Expression.Equals(atomExpression.Expression); } private readonly int _hashCode; int ComputeHashCode() { return HashCode.Compute(Expression.GetHashCode()); } public override int GetHashCode() { return _hashCode; } public override RegexNodeType NodeType { get { return RegexNodeType.RegexAtomExpression; } } public override string ToString() { return $"({Expression})"; } } public class RegexAtomSet : RegexAtom { public RegexSet Set { get; private set; } public RegexAtomSet(RegexSet set) { Set = set; _hashCode = ComputeHashCode(); } public override bool Equals(object obj) { if (obj is null) return false; if (!(obj is RegexAtomSet atomSet)) return false; return Set.Equals(atomSet.Set); } private readonly int _hashCode; private int ComputeHashCode() { return HashCode.Compute(Set.GetHashCode()); } public override int GetHashCode() { return _hashCode; } public override RegexNodeType NodeType { get { return RegexNodeType.RegexAtomSet; } } public override string ToString() { return Set.ToString(); } } }
23.712575
64
0.527525
[ "MIT" ]
patrickhuber/Earley
libraries/Pliant/Languages/Regex/RegexAtom.cs
3,962
C#
using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Json; using System.Reflection; using System.Threading.Tasks; using BlazorShared; using BlazorShared.Attributes; using BlazorShared.Interfaces; using BlazorShared.Models; using Microsoft.Extensions.Logging; namespace BlazorAdmin.Services; public class CatalogLookupDataService<TLookupData, TReponse> : ICatalogLookupDataService<TLookupData> where TLookupData : LookupData where TReponse : ILookupDataResponse<TLookupData> { private readonly HttpClient _httpClient; private readonly ILogger<CatalogLookupDataService<TLookupData, TReponse>> _logger; private readonly string _apiUrl; public CatalogLookupDataService(HttpClient httpClient, BaseUrlConfiguration baseUrlConfiguration, ILogger<CatalogLookupDataService<TLookupData, TReponse>> logger) { _httpClient = httpClient; _logger = logger; _apiUrl = baseUrlConfiguration.ApiBase; } public async Task<List<TLookupData>> List() { var endpointName = typeof(TLookupData).GetCustomAttribute<EndpointAttribute>().Name; _logger.LogInformation($"Fetching {typeof(TLookupData).Name} from API. Enpoint : {endpointName}"); var response = await _httpClient.GetFromJsonAsync<TReponse>($"{_apiUrl}{endpointName}"); return response.List; } }
32.581395
106
0.757316
[ "MIT" ]
ASauchanka/eShopOnWeb
src/BlazorAdmin/Services/CatalogLookupDataService.cs
1,403
C#
using System; using System.Collections.Generic; using System.Text; using SharpMedia.Components.TextConsole; using System.Reflection; using SharpMedia.Database; namespace SharpMedia.Tools.Parameters { /// <summary> /// Extracts parameters from tool. /// </summary> public static class ParameterProcessor { /// <summary> /// Extracts parameters from tool. /// </summary> /// <param name="type">The tool type.</param> /// <returns>The tool parameters.</returns> public static IToolParameter[] Extract(Type type, DatabaseManager manager) { List<IToolParameter> parameters = new List<IToolParameter>(); foreach (PropertyInfo info in type.GetProperties()) { if (!info.CanWrite) continue; object[] attrs = info.GetCustomAttributes(typeof(UIAttribute), true); if (attrs.Length == 0) continue; // We extract attribute. UIAttribute attribute = attrs[0] as UIAttribute; Type propertyType = info.PropertyType; if (attribute is NodeUIAttribute) { parameters.Add(new Node(attribute as NodeUIAttribute, propertyType, info.Name, manager)); } else if (attribute is TypedStreamUIAttribute) { parameters.Add(new TypedStream(attribute as TypedStreamUIAttribute, propertyType, info.Name, manager)); } else { if (Common.IsTypeSameOrDerived(typeof(Enum), propertyType)) { parameters.Add(new Enumerator(attribute, propertyType, info.Name)); } else { parameters.Add(new Basic(attribute, propertyType, info.Name)); } } } return parameters.ToArray(); } /// <summary> /// Extracts parameters, with already provided existing. /// </summary> /// <param name="type">The tool type.</param> /// <param name="existing">Existing parameters.</param> /// <remarks>If there are existing parameters that are not part of tool, /// errors are written to stream.</remarks> /// <returns></returns> public static string[] Apply(IToolParameter[] parameters, string[] args, ITextConsole console) { List<string> unprocessed = new List<string>(); for (int i = 0; i < args.Length; i++) { string[] data = args[i].Split('='); if (data.Length != 2) { unprocessed.Add(args[i]); continue; } for (int j = 0; j < parameters.Length; j++) { if (data[0] == parameters[j].Name) { try { parameters[j].Parse(data[1]); break; } catch (Exception ex) { unprocessed.Add(args[i]); console.WriteLine(ex.ToString()); } break; } } } return args; } /// <summary> /// Unrolls parameters. /// </summary> /// <param name="parameters"></param> /// <returns></returns> public static string[] Unroll(IToolParameter[] parameters) { List<string> args = new List<string>(); for (int i = 0; i < parameters.Length; i++) { if (parameters[i].IsSet) { args.Add(parameters[i].ToString()); } } return args.ToArray(); } } }
32.031008
102
0.459826
[ "Apache-2.0" ]
zigaosolin/SharpMedia
SharpMedia.Tools/Parameters/ParameterProcessor.cs
4,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("cw_3e5_count")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("cw_3e5_count")] [assembly: System.Reflection.AssemblyTitleAttribute("cw_3e5_count")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.083333
80
0.649087
[ "MIT" ]
viniciuspriori/exercises
code wars/cw_3e5_count/obj/Debug/net5.0/cw_3e5_count.AssemblyInfo.cs
986
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using dotGit.Objects; using dotGit.Exceptions; using dotGit.Generic; namespace dotGit { public static class Extensions { /// <summary> /// Extension method for the String class to use instead of the String.Format method /// </summary> public static string FormatWith(this string input, params object[] parameters) { return String.Format(input, parameters); } /// <summary> /// Returns a hex-string representation of the SHA input /// </summary> /// <param name="input">SHA byte array</param> /// <returns>String</returns> public static string ToSHAString(this byte[] input) { string sha = Sha.Decode(input); if (!Utility.IsValidSHA(sha)) throw new ParseException("Invalid sha: {0}".FormatWith(sha)); return sha; } public static int ToInt(this byte[] input) { return BitConverter.ToInt32(input, 0); } public static long ToLong(this byte[] input) { return BitConverter.ToInt64(input, 0); } public static string GetString(this byte[] input) { return Encoding.ASCII.GetString(input); } public static int GetBits(this byte b, int offset, int count) { byte buffer = b; int result = 0; int pow = 1; buffer >>= offset; for (int i = 0; i < count; ++i) { if (((byte)1 & buffer) == 1) { result += pow; } buffer >>= 1; pow *= 2; } return result; } } }
19.565789
88
0.639543
[ "MIT" ]
henon/dotgit
dotGit/Generic/Extensions.cs
1,489
C#
using Atelie.Cadastro.Materiais.Componentes; using Atelie.Cadastro.Materiais.Fabricantes; using System; using System.Threading.Tasks; using System.Transactions; namespace Atelie.Cadastro.Materiais { public class ServicoDeCadastroDeMateriais : ICadastroDeMateriais { private readonly IUnitOfWork unitOfWork; private readonly IRepositorioDeMateriais repositorioDeMateriais; private readonly IRepositorioDeFabricantes repositorioDeFabricantes; private readonly IRepositorioDeComponentes repositorioDeComponentes; public ServicoDeCadastroDeMateriais( IUnitOfWork unitOfWork, IRepositorioDeMateriais repositorioDeMateriais, IRepositorioDeFabricantes repositorioDeFabricantes, IRepositorioDeComponentes repositorioDeComponentes ) { this.unitOfWork = unitOfWork; this.repositorioDeMateriais = repositorioDeMateriais; this.repositorioDeFabricantes = repositorioDeFabricantes; this.repositorioDeComponentes = repositorioDeComponentes; } public async Task<IRespostaDeCadastroDeMaterial> CadastraMaterial(ISolicitacaoDeCadastroDeMaterial solicitacao) { await unitOfWork.BeginTransaction(); try { var fabricante = await repositorioDeFabricantes.ObtemFabricante(solicitacao.FabricanteId); var componente = await repositorioDeComponentes.ObtemComponente(solicitacao.ComponenteId); var material = new Material( solicitacao.Id, solicitacao.Nome, solicitacao.Descricao, solicitacao.CustoPadrao, fabricante, componente ); // await repositorioDeMateriais.Add(material); // await unitOfWork.Commit(); // return new RespostaDeCadastroDeMaterial { Id = solicitacao.Id, }; } catch (Exception e) { await unitOfWork.Rollback(); throw; } } public async Task<IRespostaDeCadastroDeMaterial> AtualizaMaterial(int materialId, ISolicitacaoDeCadastroDeMaterial solicitacao) { await unitOfWork.BeginTransaction(); try { var material = await repositorioDeMateriais.ObtemMaterial(materialId); // var fabricante = await repositorioDeFabricantes.ObtemFabricante(solicitacao.FabricanteId); var componente = await repositorioDeComponentes.ObtemComponente(solicitacao.ComponenteId); // material.Id = solicitacao.Id; material.Nome = solicitacao.Nome; material.Fabricante = fabricante; material.Componente = componente; // await repositorioDeMateriais.Update(material); // await unitOfWork.Commit(); // return new RespostaDeCadastroDeMaterial { Id = materialId, }; } catch (Exception e) { await unitOfWork.Rollback(); throw; } } public async Task ExcluiMaterial(int materialId) { await unitOfWork.BeginTransaction(); try { var material = await repositorioDeMateriais.ObtemMaterial(materialId); // await repositorioDeMateriais.Remove(material); // await unitOfWork.Commit(); } catch (Exception e) { await unitOfWork.Rollback(); throw; } } } }
27.114094
135
0.559901
[ "MIT" ]
mardsystems/atelie
src/Atelie.ApplicationModel/Cadastro/Materiais/ServicoDeCadastroDeMateriais.cs
4,042
C#
using Harmony; namespace AsLimc.commons { internal class VPatches { [HarmonyPatch(typeof(Db), "Initialize")] internal class Db_Initialize { private static void Postfix(Db __instance) { VLib.OnDbInitializeEnd(__instance); } } } }
25.083333
56
0.591362
[ "MIT" ]
jbboehr/oni-mods
src/commons/VPatches.cs
301
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("1.SquareArea")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("1.SquareArea")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("30a3c626-3fa4-4d6c-b6ae-b89c0bd5562d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.621622
84
0.746408
[ "MIT" ]
BorisLechev/Programming-Basics
2. Simple Calculations/1.SquareArea/Properties/AssemblyInfo.cs
1,395
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LegoSharp { public class BrickColorFilter : PickABrickValuesFilter<BrickColor> { public BrickColorFilter() : base("variants.attributes.exactColour.en-US", "element.facet.colour") { } } public class BrickColor : ValuesFilterValue { public BrickColor(string value, string name) : base(value, name) { } public static readonly BrickColor Aqua = new BrickColor("Aqua", "Aqua"); public static readonly BrickColor Black = new BrickColor("Black", "Black"); public static readonly BrickColor BrickYellow = new BrickColor("Brick Yellow", "Brick Yellow"); public static readonly BrickColor BrightBlue = new BrickColor("Bright Blue", "Bright Blue"); public static readonly BrickColor BrightBluishGreen = new BrickColor("Bright Bluish Green", "Bright Bluish Green"); public static readonly BrickColor BrightGreen = new BrickColor("Bright Green", "Bright Green"); public static readonly BrickColor BrightOrange = new BrickColor("Bright Orange", "Bright Orange"); public static readonly BrickColor BrightPurple = new BrickColor("Bright Purple", "Bright Purple"); public static readonly BrickColor BrightRed = new BrickColor("Bright Red", "Bright Red"); public static readonly BrickColor BrightReddishViolet = new BrickColor("Bright Reddish Violet", "Bright Reddish Violet"); public static readonly BrickColor BrightYellow = new BrickColor("Bright Yellow", "Bright Yellow"); public static readonly BrickColor BrightYellowishGreen = new BrickColor("Bright Yellowish Green", "Bright Yellowish Green"); public static readonly BrickColor CoolYellow = new BrickColor("Cool Yellow", "Cool Yellow"); public static readonly BrickColor DarkAzur = new BrickColor("Dark Azur", "Dark Azur"); public static readonly BrickColor DarkBrown = new BrickColor("Dark Brown", "Dark Brown"); public static readonly BrickColor DarkGreen = new BrickColor("Dark Green", "Dark Green"); public static readonly BrickColor DarkOrange = new BrickColor("Dark Orange", "Dark Orange"); public static readonly BrickColor DarkStoneGrey = new BrickColor("Dark Stone Grey", "Dark Stone Grey"); public static readonly BrickColor EarthBlue = new BrickColor("Earth Blue", "Earth Blue"); public static readonly BrickColor EarthGreen = new BrickColor("Earth Green", "Earth Green"); public static readonly BrickColor FlameYellowishOrange = new BrickColor("Flame Yellowish Orange", "Flame Yellowish Orange"); public static readonly BrickColor Lavender = new BrickColor("Lavender", "Lavender"); public static readonly BrickColor LightPurple = new BrickColor("Light Purple", "Light Purple"); public static readonly BrickColor LightRoyalBlue = new BrickColor("Light Royal Blue", "Light Royal Blue"); public static readonly BrickColor MediumAzur = new BrickColor("Medium Azur", "Medium Azur"); public static readonly BrickColor MediumBlue = new BrickColor("Medium Blue", "Medium Blue"); public static readonly BrickColor MediumLavendel = new BrickColor("Medium Lavender", "Medium Lavender"); public static readonly BrickColor MediumLavendel2 = new BrickColor("Medium Lavendel", "Medium Lavendel"); public static readonly BrickColor MediumLilac = new BrickColor("Medium Lilac", "Medium Lilac"); public static readonly BrickColor MediumNougat = new BrickColor("Medium Nougat", "Medium Nougat"); public static readonly BrickColor MediumStoneGrey = new BrickColor("Medium Stone Grey", "Medium Stone Grey"); public static readonly BrickColor NewDarkRed = new BrickColor("New Dark Red", "New Dark Red"); public static readonly BrickColor OliveGreen = new BrickColor("Olive Green", "Olive Green"); public static readonly BrickColor ReddishBrown = new BrickColor("Reddish Brown", "Reddish Brown"); public static readonly BrickColor SandBlue = new BrickColor("Sand Blue", "Sand Blue"); public static readonly BrickColor SandGreen = new BrickColor("Sand Green", "Sand Green"); public static readonly BrickColor SandYellow = new BrickColor("Sand Yellow", "Sand Yellow"); public static readonly BrickColor SilverMetallic = new BrickColor("Silver Metallic", "Silver Metallic"); public static readonly BrickColor SpringYellowishGreen = new BrickColor("Spring Yellowish Green", "Spring Yellowish Green"); public static readonly BrickColor TitaniumMetallic = new BrickColor("Titanium Metallic", "Titanium Metallic"); public static readonly BrickColor Transparent = new BrickColor("Transparent", "Transparent"); public static readonly BrickColor TrBlue = new BrickColor("Tr. Blue", "Tr. Blue"); public static readonly BrickColor TrBrightGreen = new BrickColor("Tr. Bright Green", "Tr. Bright Green"); public static readonly BrickColor TrBrightOrange = new BrickColor("Tr. Bright Orange", "Tr. Bright Orange"); public static readonly BrickColor TrBrightViolet = new BrickColor("Tr. Bright Violet", "Tr. Bright Violet"); public static readonly BrickColor TrBrown = new BrickColor("Tr. Brown", "Tr. Brown"); public static readonly BrickColor TrFluoreReddOrange = new BrickColor("Tr. Fluore. Redd. Orange", "Tr. Fluore. Redd. Orange"); public static readonly BrickColor TrGreen = new BrickColor("Tr. Green", "Tr. Green"); public static readonly BrickColor TrLightBlue = new BrickColor("Tr. Light Blue", "Tr. Light Blue"); public static readonly BrickColor TrMediumReddishViolet = new BrickColor("Tr. Medium Reddish Violet", "Tr. Medium Reddish Violet"); public static readonly BrickColor TrRed = new BrickColor("Tr. Red", "Tr. Red"); public static readonly BrickColor TrYellow = new BrickColor("Tr. Yellow", "Tr. Yellow"); public static readonly BrickColor VibrantCoral = new BrickColor("Vibrant Coral", "Vibrant Coral"); public static readonly BrickColor WarmGold = new BrickColor("Warm Gold", "Warm Gold"); public static readonly BrickColor White = new BrickColor("White", "White"); } }
79.962025
139
0.722178
[ "MIT" ]
rolledback/LegoSharp
LegoSharp/PickABrick/BrickColorFilter.cs
6,319
C#
using System; namespace UnrealEngine { public partial class UInterface_CollisionDataProvider:UInterface { } }
11.8
65
0.779661
[ "MIT" ]
xiongfang/UnrealCS
Script/UnrealEngine/GeneratedScriptFile/UInterface_CollisionDataProvider.cs
118
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; using Pulumi; namespace Pulumiverse.Unifi.Outputs { [OutputType] public sealed class WlanSchedule { /// <summary> /// Time of day to end the block. /// </summary> public readonly string BlockEnd; /// <summary> /// Time of day to start the block. /// </summary> public readonly string BlockStart; /// <summary> /// Day of week for the block. Valid values are `sun`, `mon`, `tue`, `wed`, `thu`, `fri`, `sat`. /// </summary> public readonly string DayOfWeek; [OutputConstructor] private WlanSchedule( string blockEnd, string blockStart, string dayOfWeek) { BlockEnd = blockEnd; BlockStart = blockStart; DayOfWeek = dayOfWeek; } } }
26.454545
104
0.587629
[ "ECL-2.0", "Apache-2.0" ]
pulumiverse/pulumi-unifi
sdk/dotnet/Outputs/WlanSchedule.cs
1,164
C#
using System; using System.Threading.Tasks; using Commands.CodeBaseSearch; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; namespace BeaverSoft.Text.Client.VisualStudio.Search { public class CurrentSolutionOpenStrategy : ISolutionOpenStrategy { private readonly IComponentModel vsComponentModel; public CurrentSolutionOpenStrategy(IComponentModel vsComponentModel) { this.vsComponentModel = vsComponentModel ?? throw new ArgumentNullException(nameof(vsComponentModel)); } public Task<Workspace> OpenAsync() { var workspace = vsComponentModel.GetService<Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace>(); return Task.FromResult<Workspace>(workspace); } } }
31.153846
121
0.738272
[ "MIT" ]
Mechachleopteryx/texo.ui
BeaverSoft.Text.Client.VisualStudio/Search/CurrentSolutionOpenStrategy.cs
810
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 Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DoNotPassTypesByReference : DiagnosticAnalyzer { internal const string RuleId = "CA1045"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.DoNotPassTypesByReferenceTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.DoNotPassTypesByReferenceMessage), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.DoNotPassTypesByReferenceDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, s_localizableMessage, DiagnosticCategory.Design, RuleLevel.Disabled, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false, isEnabledByDefaultInFxCopAnalyzers: false, isEnabledByDefaultInAggressiveMode: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(context => { var outAttributeType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesOutAttribute); context.RegisterSymbolAction(context => { var methodSymbol = (IMethodSymbol)context.Symbol; // FxCop compat: only analyze externally visible symbols by default. if (!methodSymbol.MatchesConfiguredVisibility(context.Options, Rule, context.Compilation, context.CancellationToken)) { return; } if (methodSymbol.IsOverride || methodSymbol.IsImplementationOfAnyInterfaceMember()) { return; } foreach (var parameterSymbol in methodSymbol.Parameters) { // VB.NET out is a ref parameter with the OutAttribute if (parameterSymbol.RefKind == RefKind.Ref && !parameterSymbol.HasAttribute(outAttributeType)) { context.ReportDiagnostic(parameterSymbol.CreateDiagnostic(Rule, parameterSymbol.Name)); } } }, SymbolKind.Method); }); } } }
51.315068
296
0.682061
[ "Apache-2.0" ]
epananth/roslyn-analyzers
src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/DoNotPassTypesByReference.cs
3,748
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using UnityEngine; using Memoria; using Memoria.Data; using Memoria.Prime; using Memoria.Assets; using Object = System.Object; using System.Net.Mime; using Assets.Sources.Scripts.UI.Common; public static class AssetManager { /* New system for Memoria: 1) Assets can be read from mod folders (defined in Memoria.Configuration.Mod) - They can be either read from bundle archives or as plain non-archived files - Assets in non-bundle archives (typically "resources.assets", but also all the "levelX" and "sharedassetsX.assets") can currently only be read as plain files when they are in a mod's folder - They are read in priority from the first mod's folder up to the last mod's folder, then from the default folder - Bundle archives should be placed directly in the mod's folder - Plain files should be placed in a subfolder of the mod's folder respecting the asset's access path (eg. "EmbeddedAsset/Manifest/Text/Localization.txt") - Only assets of certain types can be read as plain files currently: binary (TextAsset), text (TextAsset), textures (Texture / Texture2D / Sprite / UIAtlas) and animations (AnimationClip) - Texture files that are not in archives should be placed as PNG or JPG files, not DXT-compressed files or using Unity's format - Assets that are not present in the mod folders must be archived as normally in the default folder 2) Any asset that is not archived can use a "Memoria information" file which is a text file placed in the same subfolder as the asset, with the same name and the extension "AssetManager.MemoriaInfoExtension" (".memnfo"); the purpose of these files may vary from type to type - For textures, they can define different properties of the texture that are usually in the Unity-formatted assets, such as the anisotropic level (see "AssetManager.ApplyTextureGenericMemoriaInfo") - For sounds and musics, they can define or change different properties, such as the LoopStart/LoopEnd frame points (see "SoundLoaderResources.Load") - For battle scene binary files (".raw16"), they can give battle properties as textual informations, which can be useful for adding custom properties to Memoria or go beyond binary max limits (see "BTL_SCENE.ReadBattleScene") - Etc... [To be completed] - The idea behind these files is that they should be optional (non-modded assets don't need them) and allow to use asset-specific special features without forcing other mods to take these features into account (for explicitely disabling them for instance) */ static AssetManager() { Array values = Enum.GetValues(typeof(AssetManagerUtil.ModuleBundle)); String[] foldname = new String[Configuration.Mod.FolderNames.Length + 1]; String url; for (Int32 i = 0; i < (Int32)Configuration.Mod.FolderNames.Length; ++i) foldname[i] = Configuration.Mod.FolderNames[i] + "/"; foldname[Configuration.Mod.FolderNames.Length] = ""; Folder = new AssetFolder[foldname.Length]; for (Int32 i = 0; i < (Int32)foldname.Length; ++i) { Folder[i] = new AssetFolder(foldname[i]); foreach (Object obj in values) { AssetManagerUtil.ModuleBundle moduleBundle = (AssetManagerUtil.ModuleBundle)((Int32)obj); if (moduleBundle == AssetManagerUtil.ModuleBundle.FieldMaps) { Array values2 = Enum.GetValues(typeof(AssetManagerUtil.FieldMapBundleId)); foreach (Object obj2 in values2) { AssetManagerUtil.FieldMapBundleId bundleId = (AssetManagerUtil.FieldMapBundleId)((Int32)obj2); url = foldname[i] + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.CreateFieldMapBundleFilename(Application.platform, false, bundleId); if (File.Exists(url)) Folder[i].DictAssetBundleRefs.Add(AssetManagerUtil.GetFieldMapBundleName(bundleId), new AssetBundleRef(url, 0)); } } else if (moduleBundle == AssetManagerUtil.ModuleBundle.Sounds) { Array values3 = Enum.GetValues(typeof(AssetManagerUtil.SoundBundleId)); foreach (Object obj3 in values3) { AssetManagerUtil.SoundBundleId bundleId2 = (AssetManagerUtil.SoundBundleId)((Int32)obj3); url = foldname[i] + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.CreateSoundBundleFilename(Application.platform, false, bundleId2); if (File.Exists(url)) Folder[i].DictAssetBundleRefs.Add(AssetManagerUtil.GetSoundBundleName(bundleId2), new AssetBundleRef(url, 0)); } } else { url = foldname[i] + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.CreateModuleBundleFilename(Application.platform, false, moduleBundle); if (File.Exists(url)) Folder[i].DictAssetBundleRefs.Add(AssetManagerUtil.GetModuleBundleName(moduleBundle), new AssetBundleRef(url, 0)); } } } _LoadAnimationFolderMapping(); } private static void _LoadAnimationFolderMapping() { _animationInFolder = new Dictionary<String, List<String>>(); _animationReverseFolder = new Dictionary<String, String>(); String filestr = LoadString("EmbeddedAsset/Manifest/Animations/AnimationFolderMapping.txt", out _); if (filestr == null) { return; } String[] folderList = filestr.Split(new Char[] { '\n' }); for (Int32 i = 0; i < (Int32)folderList.Length; i++) { String folderFull = folderList[i]; String[] geoAndAnim = folderFull.Split(new Char[] { ':' }); String geoFolder = geoAndAnim[0]; String modelName = Path.GetFileNameWithoutExtension(geoFolder); String[] animList = geoAndAnim[1].Split(new Char[] { ',' }); List<String> animFolderList = new List<String>(); for (Int32 j = 0; j < (Int32)animList.Length; j++) { String animName = animList[j].Trim(); String animFolder = geoFolder + "/" + animName; animFolder = animFolder.Trim(); animFolderList.Add(animFolder); _animationReverseFolder[animName] = modelName; } _animationInFolder.Add(geoFolder, animFolderList); } } public static void ClearCache() { Caching.CleanCache(); foreach (AssetFolder modfold in Folder) foreach (KeyValuePair<String, AssetBundleRef> keyValuePair in modfold.DictAssetBundleRefs) { AssetBundleRef value = keyValuePair.Value; if (value.assetBundle != (UnityEngine.Object)null) { value.assetBundle.Unload(true); value.assetBundle = (AssetBundle)null; } } } /* public static Byte[] LoadBinary(String resourcePath) { // By default, this method is only used for Localization.txt for a subsequent ByteReader.ReadCSV call // We delete it and use LoadBytes instead TextAsset textAsset = Resources.Load<TextAsset>(resourcePath); if (textAsset == null) throw new FileNotFoundException(resourcePath); return textAsset.bytes; } */ public static void ApplyTextureGenericMemoriaInfo<T>(ref T texture, ref String[] memoriaInfo) where T : UnityEngine.Texture { // Maybe remove the successfully parsed lines from the "info" array? foreach (String s in memoriaInfo) { String[] textureCode = s.Split(' '); if (textureCode.Length >= 2 && String.Compare(textureCode[0], "AnisotropicLevel") == 0) { Int32 anisoLevel; if (Int32.TryParse(textureCode[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out anisoLevel) && anisoLevel >= 1 && anisoLevel <= 9) texture.anisoLevel = anisoLevel; } else if (textureCode.Length >= 2 && String.Compare(textureCode[0], "FilterMode") == 0) { foreach (FilterMode m in (FilterMode[]) Enum.GetValues(typeof(FilterMode))) if (String.Compare(textureCode[1], m.ToString()) == 0) texture.filterMode = m; } else if(textureCode.Length >= 2 && String.Compare(textureCode[0], "HideFlags") == 0) { foreach (HideFlags f in (HideFlags[]) Enum.GetValues(typeof(HideFlags))) if (String.Compare(textureCode[1], f.ToString()) == 0) texture.hideFlags = f; } else if(textureCode.Length >= 2 && String.Compare(textureCode[0], "MipMapBias") == 0) { Single mipMapBias; if (Single.TryParse(textureCode[1], out mipMapBias)) texture.mipMapBias = mipMapBias; } else if(textureCode.Length >= 2 && String.Compare(textureCode[0], "WrapMode") == 0) { foreach (TextureWrapMode m in (TextureWrapMode[]) Enum.GetValues(typeof(TextureWrapMode))) if (String.Compare(textureCode[1], m.ToString()) == 0) texture.wrapMode = m; } } } public static Boolean IsTextureFormatReadableFromBytes(TextureFormat format) { // Todo: verify which TextureFormat are compatible with LoadRawTextureData return format == TextureFormat.Alpha8 || format == TextureFormat.RGB24 || format == TextureFormat.RGBA32 || format == TextureFormat.ARGB32 || format == TextureFormat.RGB565 || format == TextureFormat.DXT1 || format == TextureFormat.DXT5; } public static Texture2D LoadTextureGeneric(Byte[] raw) { const UInt32 DDS_HEADER_SIZE = 0x3C; if (raw.Length >= DDS_HEADER_SIZE) { UInt32 w = BitConverter.ToUInt32(raw, 0); UInt32 h = BitConverter.ToUInt32(raw, 4); UInt32 imgSize = BitConverter.ToUInt32(raw, 8); TextureFormat fmt = (TextureFormat)BitConverter.ToUInt32(raw, 12); UInt32 mipCount = BitConverter.ToUInt32(raw, 16); // UInt32 flags = BitConverter.ToUInt32(raw, 20); // 1 = isReadable (for use of GetPixels); 0x100 is usually on // UInt32 imageCount = BitConverter.ToUInt32(raw, 24); // UInt32 dimension = BitConverter.ToUInt32(raw, 28); // UInt32 filterMode = BitConverter.ToUInt32(raw, 32); // UInt32 anisotropic = BitConverter.ToUInt32(raw, 36); // UInt32 mipBias = BitConverter.ToUInt32(raw, 40); // UInt32 wrapMode = BitConverter.ToUInt32(raw, 44); // UInt32 lightmapFormat = BitConverter.ToUInt32(raw, 48); // UInt32 colorSpace = BitConverter.ToUInt32(raw, 52); // UInt32 imgSize = BitConverter.ToUInt32(raw, 56); if (raw.Length == DDS_HEADER_SIZE + imgSize && IsTextureFormatReadableFromBytes(fmt)) { Byte[] imgBytes = new Byte[imgSize]; Buffer.BlockCopy(raw, (Int32)DDS_HEADER_SIZE, imgBytes, 0, (Int32)imgSize); Texture2D ddsTexture = new Texture2D((Int32)w, (Int32)h, fmt, mipCount > 1); ddsTexture.LoadRawTextureData(imgBytes); ddsTexture.Apply(); return ddsTexture; } } Texture2D pngTexture = new Texture2D(1, 1, DefaultTextureFormat, false); if (pngTexture.LoadImage(raw)) return pngTexture; return null; } public static T LoadFromDisc<T>(String name, ref String[] memoriaInfo, String archiveName) { /* Types used by the game by default: * TextAsset (many, both text and binaries, including sounds and musics) - Use LoadString / LoadBytes instead * Texture2D (LoadAsync is used in MBG) - Can be read as PNG/JPG * Texture (only used by ModelFactory for "GEO_MAIN_F3_ZDN", "GEO_MAIN_F4_ZDN" and "GEO_MAIN_F5_ZDN") - Can be read as PNG/JPG as Texture2D * RenderTexture (Usually split into many pieces) - Can't be read from disc currently * Material - Can't be read from disc currently * AnimationClip (LoadAll is used in AnimationFactory) - Can be read as .anim (serialized format, as in the p0data5.bin) or JSON but with simple readers * GameObject (Usually split into many pieces ; LoadAsync is used in WMWorld) - Can't be read from disc currently */ if (typeof(T) == typeof(String)) { return (T)(Object)File.ReadAllText(name); } else if (typeof(T) == typeof(Byte[])) { return (T)(Object)File.ReadAllBytes(name); } else if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Texture)) { Byte[] raw = File.ReadAllBytes(name); Texture2D newTexture = LoadTextureGeneric(raw); if (newTexture == null) newTexture = new Texture2D(1, 1, DefaultTextureFormat, false); ApplyTextureGenericMemoriaInfo<Texture2D>(ref newTexture, ref memoriaInfo); return (T)(Object)newTexture; } else if (typeof(T) == typeof(Sprite)) { Byte[] raw = File.ReadAllBytes(name); Texture2D newTexture = LoadTextureGeneric(raw); if (newTexture == null) newTexture = new Texture2D(1, 1, DefaultTextureFormat, false); ApplyTextureGenericMemoriaInfo<Texture2D>(ref newTexture, ref memoriaInfo); Sprite newSprite = Sprite.Create(newTexture, new Rect(0, 0, newTexture.width, newTexture.height), new Vector2(0.5f, 0.5f)); return (T)(Object)newSprite; } else if (typeof(T) == typeof(UIAtlas)) { // Todo: Maybe avoid the call of Resources.Load<UIAtlas> if a complete .tpsheet is available and it's not necessary to get the original's sprite list UIAtlas newAtlas = Resources.Load<UIAtlas>(archiveName); if (newAtlas != null) newAtlas.ReadFromDisc(name); else Log.Message("[AssetManager] Embeded asset not found: " + archiveName); return (T)(Object)newAtlas; } else if (typeof(T) == typeof(AnimationClip)) { return (T)(Object)AnimationClipReader.ReadAnimationClipFromDisc(name); } Log.Message("[AssetManager] Trying to load from disc the asset " + name + " of type " + typeof(T).ToString() + ", which is not currently possible"); return (T)(Object)null; } public static T Load<T>(String name, out String[] info, Boolean suppressMissingError = false) where T : UnityEngine.Object { String infoFileName = Path.ChangeExtension(name, MemoriaInfoExtension); info = new String[0]; T result; if (AssetManagerForObb.IsUseOBB) return AssetManagerForObb.Load<T>(name, suppressMissingError); if (AssetManagerUtil.IsMemoriaAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + name)) { if (File.Exists(modfold.FolderPath + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + infoFileName); return LoadFromDisc<T>(modfold.FolderPath + name, ref info, name); } if (File.Exists(name)) { if (File.Exists(infoFileName)) info = File.ReadAllLines(infoFileName); return LoadFromDisc<T>(name, ref info, name); } if (!suppressMissingError) Log.Message("[AssetManager] Memoria asset not found: " + name); return null; } if (!UseBundles || AssetManagerUtil.IsEmbededAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<T>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } result = Resources.Load<T>(name); if (result == (UnityEngine.Object)null && !suppressMissingError) Log.Message("[AssetManager] Embeded asset not found: " + name); return result; } String belongingBundleFilename = AssetManagerUtil.GetBelongingBundleFilename(name); if (!String.IsNullOrEmpty(belongingBundleFilename)) { String nameInBundle = AssetManagerUtil.GetResourcesBasePath() + name + AssetManagerUtil.GetAssetExtension<T>(name); foreach (AssetFolder modfold in Folder) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName); return LoadFromDisc<T>(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle, ref info, nameInBundle); } AssetBundleRef assetBundleRef = null; modfold.DictAssetBundleRefs.TryGetValue(belongingBundleFilename, out assetBundleRef); if (assetBundleRef != null && assetBundleRef.assetBundle != (UnityEngine.Object)null) { result = assetBundleRef.assetBundle.LoadAsset<T>(nameInBundle); if (result != (UnityEngine.Object)null) { return result; } } } } if (ForceUseBundles) return (T)((Object)null); foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<T>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } result = Resources.Load<T>(name); if (result == (UnityEngine.Object)null && !suppressMissingError) Log.Message("[AssetManager] Asset not found: " + name); return result; } public static String LoadString(String name, out String[] info, Boolean suppressMissingError = false) { String infoFileName = Path.ChangeExtension(name, MemoriaInfoExtension); TextAsset txt = null; info = new String[0]; if (AssetManagerForObb.IsUseOBB) { txt = AssetManagerForObb.Load<TextAsset>(name, suppressMissingError); if (txt != (UnityEngine.Object)null) return txt.text; return null; } if (AssetManagerUtil.IsMemoriaAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + name)) { if (File.Exists(modfold.FolderPath + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + infoFileName); return LoadFromDisc<String>(modfold.FolderPath + name, ref info, name); } if (File.Exists(name)) { if (File.Exists(infoFileName)) info = File.ReadAllLines(infoFileName); return LoadFromDisc<String>(name, ref info, name); } if (!suppressMissingError) Log.Message("[AssetManager] Memoria asset not found: " + name); return null; } if (!UseBundles || AssetManagerUtil.IsEmbededAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<String>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } txt = Resources.Load<TextAsset>(name); if (txt != (UnityEngine.Object)null) return txt.text; if (!suppressMissingError) Log.Message("[AssetManager] Embeded asset not found: " + name); return null; } String belongingBundleFilename = AssetManagerUtil.GetBelongingBundleFilename(name); if (!String.IsNullOrEmpty(belongingBundleFilename)) { String nameInBundle = AssetManagerUtil.GetResourcesBasePath() + name + AssetManagerUtil.GetAssetExtension<TextAsset>(name); foreach (AssetFolder modfold in Folder) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName); return LoadFromDisc<String>(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle, ref info, nameInBundle); } AssetBundleRef assetBundleRef = null; modfold.DictAssetBundleRefs.TryGetValue(belongingBundleFilename, out assetBundleRef); if (assetBundleRef != null && assetBundleRef.assetBundle != (UnityEngine.Object)null) { txt = assetBundleRef.assetBundle.LoadAsset<TextAsset>(nameInBundle); if (txt != (UnityEngine.Object)null) return txt.text; } } } if (ForceUseBundles) return null; foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<String>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } txt = Resources.Load<TextAsset>(name); if (txt != (UnityEngine.Object)null) return txt.text; if (!suppressMissingError) Log.Message("[AssetManager] Asset not found: " + name); return null; } public static Byte[] LoadBytes(String name, out String[] info, Boolean suppressMissingError = false) { String infoFileName = Path.ChangeExtension(name, MemoriaInfoExtension); TextAsset txt = null; info = new String[0]; if (AssetManagerForObb.IsUseOBB) { txt = AssetManagerForObb.Load<TextAsset>(name, suppressMissingError); if (txt != (UnityEngine.Object)null) return txt.bytes; return null; } if (AssetManagerUtil.IsMemoriaAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + name)) { if (File.Exists(modfold.FolderPath + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + infoFileName); return LoadFromDisc<Byte[]>(modfold.FolderPath + name, ref info, name); } if (File.Exists(name)) { if (File.Exists(infoFileName)) info = File.ReadAllLines(infoFileName); return LoadFromDisc<Byte[]>(name, ref info, name); } if (!suppressMissingError) Log.Message("[AssetManager] Memoria asset not found: " + name); return null; } if (!UseBundles || AssetManagerUtil.IsEmbededAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<Byte[]>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } txt = Resources.Load<TextAsset>(name); if (txt != (UnityEngine.Object)null) return txt.bytes; if (!suppressMissingError) Log.Message("[AssetManager] Embeded asset not found: " + name); return null; } String belongingBundleFilename = AssetManagerUtil.GetBelongingBundleFilename(name); if (!String.IsNullOrEmpty(belongingBundleFilename)) { String nameInBundle = AssetManagerUtil.GetResourcesBasePath() + name + AssetManagerUtil.GetAssetExtension<TextAsset>(name); foreach (AssetFolder modfold in Folder) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName); return LoadFromDisc<Byte[]>(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle, ref info, nameInBundle); } AssetBundleRef assetBundleRef = null; modfold.DictAssetBundleRefs.TryGetValue(belongingBundleFilename, out assetBundleRef); if (assetBundleRef != null && assetBundleRef.assetBundle != (UnityEngine.Object)null) { txt = assetBundleRef.assetBundle.LoadAsset<TextAsset>(nameInBundle); if (txt != (UnityEngine.Object)null) return txt.bytes; } } } if (ForceUseBundles) return null; foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<Byte[]>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } txt = Resources.Load<TextAsset>(name); if (txt != (UnityEngine.Object)null) return txt.bytes; if (!suppressMissingError) Log.Message("[AssetManager] Asset not found: " + name); return null; } public static AssetManagerRequest LoadAsync<T>(String name) where T : UnityEngine.Object { if (AssetManagerForObb.IsUseOBB) return AssetManagerForObb.LoadAsync<T>(name); if (!UseBundles || AssetManagerUtil.IsEmbededAssets(name)) { ResourceRequest resourceRequest = Resources.LoadAsync<T>(name); if (resourceRequest != null) return new AssetManagerRequest(resourceRequest, (AssetBundleRequest)null); } String belongingBundleFilename = AssetManagerUtil.GetBelongingBundleFilename(name); if (!String.IsNullOrEmpty(belongingBundleFilename)) { String nameInBundle = AssetManagerUtil.GetResourcesBasePath() + name + AssetManagerUtil.GetAssetExtension<T>(name); foreach (AssetFolder modfold in Folder) { AssetBundleRef assetBundleRef = null; modfold.DictAssetBundleRefs.TryGetValue(belongingBundleFilename, out assetBundleRef); if (assetBundleRef != null && assetBundleRef.assetBundle != (UnityEngine.Object)null) { AssetBundleRequest assetBundleRequest = assetBundleRef.assetBundle.LoadAssetAsync(nameInBundle); if (assetBundleRequest != null) return new AssetManagerRequest((ResourceRequest)null, assetBundleRequest); } } } if (ForceUseBundles) return (AssetManagerRequest)null; ResourceRequest resourceRequest2 = Resources.LoadAsync<T>(name); if (resourceRequest2 != null) return new AssetManagerRequest(resourceRequest2, (AssetBundleRequest)null); Log.Message("[AssetManager] Asset not found: " + name); return (AssetManagerRequest)null; } public static String SearchAssetOnDisc(String name, Boolean includeAssetPath, Boolean includeAssetExtension) { if (!UseBundles || AssetManagerUtil.IsEmbededAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + (includeAssetPath ? AssetManagerUtil.GetResourcesAssetsPath(true) + "/" : "") + name)) return modfold.FolderPath + (includeAssetPath ? AssetManagerUtil.GetResourcesAssetsPath(true) + "/" : "") + name; return String.Empty; } String belongingBundleFilename = AssetManagerUtil.GetBelongingBundleFilename(name); if (!String.IsNullOrEmpty(belongingBundleFilename)) { String nameInBundle = (includeAssetPath ? AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() : "") + name + (includeAssetExtension ? AssetManagerUtil.GetAssetExtension<TextAsset>(name) : ""); foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + nameInBundle)) return modfold.FolderPath + nameInBundle; } if (ForceUseBundles) return String.Empty; foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + (includeAssetPath ? AssetManagerUtil.GetResourcesAssetsPath(true) : "") + "/" + name)) return modfold.FolderPath + (includeAssetPath ? AssetManagerUtil.GetResourcesAssetsPath(true) : "") + "/" + name; return String.Empty; } public static T[] LoadAll<T>(String name) where T : UnityEngine.Object { if (AssetManagerForObb.IsUseOBB) { return AssetManagerForObb.LoadAll<T>(name); } if (typeof(T) != typeof(AnimationClip)) { return null; } if (!UseBundles) { name = AnimationFactory.GetRenameAnimationDirectory(name); return Resources.LoadAll<T>(name); } if (_animationInFolder.ContainsKey(name)) { List<String> list = _animationInFolder[name]; T[] array = new T[list.Count]; for (Int32 i = 0; i < list.Count; i++) { String renameAnimationPath = AnimationFactory.GetRenameAnimationPath(list[i]); array[i] = Load<T>(renameAnimationPath, out _, false); AnimationClip clip = array[i] as AnimationClip; if (clip != null) { if (String.Compare(clip.name, "CUSTOM_MUST_RENAME") == 0) clip.name = Path.GetFileNameWithoutExtension(list[i]); } } return array; } return null; } public static void PatchDictionaries(String[] patchCode) { // This method might go somewhere else... foreach (String s in patchCode) { String[] entry = s.Split(' '); if (entry.Length < 3) continue; if (String.Compare(entry[0], "MessageFile") == 0) { // eg.: MessageFile 2000 MES_CUSTOM_PLACE if (FF9DBAll.MesDB == null) continue; Int32 ID; if (!Int32.TryParse(entry[1], out ID)) continue; FF9DBAll.MesDB[ID] = entry[2]; } else if (String.Compare(entry[0], "IconSprite") == 0) { // eg.: IconSprite 19 arrow_down if (FF9UIDataTool.IconSpriteName == null) continue; Int32 ID; if (!Int32.TryParse(entry[1], out ID)) continue; FF9UIDataTool.IconSpriteName[ID] = entry[2]; } else if (String.Compare(entry[0], "DebuffIcon") == 0) { // eg.: DebuffIcon 0 188 // or : DebuffIcon 0 ability_stone if (BattleHUD.DebuffIconNames == null) continue; Int32 ID, iconID; if (!Int32.TryParse(entry[1], out ID)) continue; if (Int32.TryParse(entry[2], out iconID)) { if (!FF9UIDataTool.IconSpriteName.ContainsKey(iconID)) { Log.Message("[AssetManager.PatchDictionaries] Trying to use the invalid sprite index " + iconID + " for the icon of status " + ID); continue; } BattleHUD.DebuffIconNames[(BattleStatus)(1 << ID)] = FF9UIDataTool.IconSpriteName[iconID]; if (BattleResultUI.BadIconDict == null || FF9UIDataTool.status_id == null) continue; BattleResultUI.BadIconDict[(UInt32)(1 << ID)] = (Byte)iconID; if (ID < FF9UIDataTool.status_id.Length) FF9UIDataTool.status_id[ID] = iconID; // Todo: debuff icons in the main menus (status menu, items...) are UISprite components of CharacterDetailHUD and are enabled/disabled in FF9UIDataTool.DisplayCharacterDetail // Maybe add UISprite components at runtime? The width of the window may require adjustments then // By design (in FF9UIDataTool.DisplayCharacterDetail for instance), permanent debuffs must be the first ones of the list of statuses } else { BattleHUD.DebuffIconNames[(BattleStatus)(1 << ID)] = entry[2]; // When adding a debuff icon by sprite name, not all the dictionaries are updated } } else if (String.Compare(entry[0], "BuffIcon") == 0) { // eg.: BuffIcon 18 188 // or : BuffIcon 18 ability_stone if (BattleHUD.BuffIconNames == null) continue; Int32 ID, iconID; if (!Int32.TryParse(entry[1], out ID)) continue; if (Int32.TryParse(entry[2], out iconID)) { if (!FF9UIDataTool.IconSpriteName.ContainsKey(iconID)) { Log.Message("[AssetManager.PatchDictionaries] Trying to use the invalid sprite index " + iconID + " for the icon of status " + ID); continue; } BattleHUD.BuffIconNames[(BattleStatus)(1 << ID)] = FF9UIDataTool.IconSpriteName[iconID]; } else { BattleHUD.BuffIconNames[(BattleStatus)(1 << ID)] = entry[2]; } } else if (String.Compare(entry[0], "HalfTranceCommand") == 0) { // eg.: HalfTranceCommand Set DoubleWhiteMagic DoubleBlackMagic HolySword2 if (btl_cmd.half_trance_cmd_list == null) continue; Boolean add = String.Compare(entry[1], "Remove") != 0; if (String.Compare(entry[1], "Set") == 0) btl_cmd.half_trance_cmd_list.Clear(); for (Int32 i = 2; i < entry.Length; i++) foreach (BattleCommandId cmdid in (BattleCommandId[])Enum.GetValues(typeof(BattleCommandId))) if (String.Compare(entry[i], cmdid.ToString()) == 0) { if (add && !btl_cmd.half_trance_cmd_list.Contains(cmdid)) btl_cmd.half_trance_cmd_list.Add(cmdid); else if (!add) btl_cmd.half_trance_cmd_list.Remove(cmdid); break; } } else if (String.Compare(entry[0], "DoubleCastCommand") == 0) { // eg.: DoubleCastCommand Add RedMagic1 Boolean add = String.Compare(entry[1], "Remove") != 0; if (String.Compare(entry[1], "Set") == 0) BattleHUD.DoubleCastSet.Clear(); for (Int32 i = 2; i < entry.Length; i++) foreach (BattleCommandId cmdid in (BattleCommandId[])Enum.GetValues(typeof(BattleCommandId))) if (String.Compare(entry[i], cmdid.ToString()) == 0) { if (add && !btl_cmd.half_trance_cmd_list.Contains(cmdid)) BattleHUD.DoubleCastSet.Add(cmdid); else if (!add) BattleHUD.DoubleCastSet.Remove(cmdid); break; } } else if (String.Compare(entry[0], "BattleMapModel") == 0) { // eg.: BattleMapModel BSC_CUSTOM_FIELD BBG_B065 // Can also be modified using "BattleScene" if (FF9BattleDB.MapModel == null) continue; FF9BattleDB.MapModel[entry[1]] = entry[2]; } else if (String.Compare(entry[0], "FieldScene") == 0 && entry.Length >= 6) { // eg.: FieldScene 4000 57 CUSTOM_FIELD CUSTOM_FIELD 2000 if (FF9DBAll.EventDB == null || EventEngineUtils.eventIDToFBGID == null || EventEngineUtils.eventIDToMESID == null) continue; Int32 ID, mesID, areaID; if (!Int32.TryParse(entry[1], out ID)) continue; if (!Int32.TryParse(entry[2], out areaID)) continue; if (!Int32.TryParse(entry[5], out mesID)) continue; if (!FF9DBAll.MesDB.ContainsKey(mesID)) { Log.Message("[AssetManager.PatchDictionaries] Trying to use the invalid message file ID " + mesID + " for the field map field scene " + entry[3] + " (" + ID + ")"); continue; } String fieldMapName = "FBG_N" + areaID + "_" + entry[3]; EventEngineUtils.eventIDToFBGID[ID] = fieldMapName; FF9DBAll.EventDB[ID] = "EVT_" + entry[4]; EventEngineUtils.eventIDToMESID[ID] = mesID; // p0data1X: // Assets/Resources/FieldMaps/{fieldMapName}/atlas.png // Assets/Resources/FieldMaps/{fieldMapName}/{fieldMapName}.bgi.bytes // Assets/Resources/FieldMaps/{fieldMapName}/{fieldMapName}.bgs.bytes // [Optional] Assets/Resources/FieldMaps/{fieldMapName}/spt.tcb.bytes // [Optional for each sps] Assets/Resources/FieldMaps/{fieldMapName}/{spsID}.sps.bytes // p0data7: // Assets/Resources/CommonAsset/EventEngine/EventBinary/Field/LANG/EVT_{entry[4]}.eb.bytes // [Optional] Assets/Resources/CommonAsset/EventEngine/EventAnimation/EVT_{entry[4]}.txt.bytes // [Optional] Assets/Resources/CommonAsset/MapConfigData/EVT_{entry[4]}.bytes // [Optional] Assets/Resources/CommonAsset/VibrationData/EVT_{entry[4]}.bytes } else if (String.Compare(entry[0], "BattleScene") == 0 && entry.Length >= 4) { // eg.: BattleScene 5000 CUSTOM_BATTLE BBG_B065 if (FF9DBAll.EventDB == null || FF9BattleDB.SceneData == null || FF9BattleDB.MapModel == null) continue; Int32 ID; if (!Int32.TryParse(entry[1], out ID)) continue; FF9DBAll.EventDB[ID] = "EVT_BATTLE_" + entry[2]; FF9BattleDB.SceneData["BSC_" + entry[2]] = ID; FF9BattleDB.MapModel["BSC_" + entry[2]] = entry[3]; // p0data2: // Assets/Resources/BattleMap/BattleScene/EVT_BATTLE_{entry[2]}/{ID}.raw17.bytes // Assets/Resources/BattleMap/BattleScene/EVT_BATTLE_{entry[2]}/dbfile0000.raw16.bytes // p0data7: // Assets/Resources/CommonAsset/EventEngine/EventBinary/Battle/{Lang}/EVT_BATTLE_{entry[2]}.eb.bytes // resources: // EmbeddedAsset/Text/{Lang}/Battle/{ID}.mes } else if (String.Compare(entry[0], "CharacterDefaultName") == 0 && entry.Length >= 4) { // eg.: CharacterDefaultName 0 US Zinedine // REMARK: Character default names can also be changed with the option "[Import] Text = 1" although it would monopolise the whole machinery of text importing // "[Import] Text = 1" has the priority over DictionaryPatch if (CharacterNamesFormatter._characterNames == null) continue; Int32 ID; if (!Int32.TryParse(entry[1], out ID)) continue; String[] nameArray; if (!CharacterNamesFormatter._characterNames.TryGetValue(entry[2], out nameArray)) nameArray = new String[ID + 1]; if (nameArray.Length <= ID) { nameArray = new String[ID + 1]; CharacterNamesFormatter._characterNames[entry[2]].CopyTo(nameArray, 0); } nameArray[ID] = String.Join(" ", entry, 3, entry.Length - 3); // Character names can't have spaces now and are max 8 char long, so there's no real point in joining instead of using entry[3] directly CharacterNamesFormatter._characterNames[entry[2]] = nameArray; } else if (String.Compare(entry[0], "3DModel") == 0) { // For both field models and enemy battle models (+ animations) // eg.: // 3DModel 98 GEO_NPC_F0_RMF // 3DModelAnimation 200 ANH_NPC_F0_RMF_IDLE // 3DModelAnimation 25 ANH_NPC_F0_RMF_WALK // 3DModelAnimation 38 ANH_NPC_F0_RMF_RUN // 3DModelAnimation 40 ANH_NPC_F0_RMF_TURN_L // 3DModelAnimation 41 ANH_NPC_F0_RMF_TURN_R // 3DModelAnimation 54 55 56 57 59 ANH_NPC_F0_RMF_ANGRY_INN if (FF9BattleDB.GEO == null) continue; Int32 idcount = entry.Length - 2; Int32[] ID = new Int32[entry.Length-2]; Boolean formatOK = true; for (Int32 idindex = 0; formatOK && idindex < idcount; ++idindex) if (!Int32.TryParse(entry[idindex + 1], out ID[idindex])) formatOK = false; if (!formatOK) continue; for (Int32 idindex = 0; formatOK && idindex < idcount; ++idindex) { FF9BattleDB.GEO[ID[idindex]] = entry[entry.Length - 1]; } // TODO: make it work for replacing battle weapon models // Currently, a line like "3DModel 476 GEO_ACC_F0_OPB" for replacing the dagger by a book freezes the game on black screen when battle starts } else if (String.Compare(entry[0], "3DModelAnimation") == 0) { // eg.: See above // When adding custom animations, the name must follow the following pattern: // ANH_[MODEL TYPE]_[MODEL VERSION]_[MODEL 3 LETTER CODE]_[WHATEVER] // in such a way that the model's name GEO_[...] and its new animation ANH_[...] have the middle block in common in their name // Then that custom animation's file must be placed in that model's animation folder // (eg. "assets/resources/animations/98/100000.anim" for a custom animation of Zidane with ID 100000) if (FF9DBAll.AnimationDB == null || FF9BattleDB.Animation == null) continue; Int32 idcount = entry.Length - 2; Int32[] ID = new Int32[entry.Length - 2]; Boolean formatOK = true; for (Int32 idindex = 0; formatOK && idindex < idcount; ++idindex) if (!Int32.TryParse(entry[idindex + 1], out ID[idindex])) formatOK = false; if (!formatOK) continue; for (Int32 idindex = 0; formatOK && idindex < idcount; ++idindex) { FF9DBAll.AnimationDB[ID[idindex]] = entry[entry.Length - 1]; FF9BattleDB.Animation[ID[idindex]] = entry[entry.Length - 1]; } } else if (String.Compare(entry[0], "PlayerBattleModel") == 0 && entry.Length >= 39) { // For party battle models and animations // Check btl_mot's note for the sorting of battle animations // eg.: // 3DModelAnimation 100000 ANH_SUB_F0_KJA_MYCUSTOM_ANIM // PlayerBattleModel 0 GEO_SUB_F0_KJA GEO_SUB_F0_KJA 18 // ANH_SUB_F0_KJA_ARMS_CROSS_2_2 ANH_SUB_F0_KJA_ARMS_CROSS_2_2 ANH_MON_B3_125_003 ANH_MON_B3_125_040 // ANH_SUB_F0_KJA_DOWN ANH_SUB_F0_KJA_ARMS_CROSS_2_2 ANH_SUB_F0_KJA_ARMS_CROSS_2_2 ANH_SUB_F0_KJA_MYCUSTOM_ANIM // ANH_SUB_F0_KJA_DOWN ANH_SUB_F0_KJA_IDLE ANH_SUB_F0_KJA_ARMS_CROSS_2_3 ANH_SUB_F0_KJA_ARMS_CROSS_2_2 // ANH_SUB_F0_KJA_SHOW_OFF_1_1 ANH_SUB_F0_KJA_SHOW_OFF_1_2 ANH_SUB_F0_KJA_SHOW_OFF_1_3 // ANH_MON_B3_125_021 ANH_SUB_F0_KJA_LAUGH_2_2 ANH_SUB_F0_KJA_SHOW_OFF_2_2 // ANH_SUB_F0_KJA_OJIGI_1 ANH_SUB_F0_KJA_OJIGI_2 // ANH_SUB_F0_KJA_GET_HSK_1 ANH_SUB_F0_KJA_GET_HSK_2 ANH_SUB_F0_KJA_GET_HSK_2 ANH_SUB_F0_KJA_GET_HSK_3 ANH_SUB_F0_KJA_ARMS_CROSS_2_2 ANH_SUB_F0_KJA_ARMS_CROSS_2_2 // ANH_MON_B3_125_020 ANH_MON_B3_125_021 ANH_MON_B3_125_022 // ANH_SUB_F0_KJA_WALK ANH_SUB_F0_KJA_WALK ANH_SUB_F0_KJA_RAIN_1 // ANH_SUB_F0_KJA_ARMS_CROSS_2_1 ANH_SUB_F0_KJA_ARMS_UP_KUBIFURI_2 // (in a single line) if (FF9.btl_mot.mot == null || BattlePlayerCharacter.PlayerModelFileName == null || btl_init.model_id == null) continue; Int32 ID; Byte boneID; if (!Int32.TryParse(entry[1], out ID)) continue; if (!Byte.TryParse(entry[4], out boneID)) continue; if (ID < 0 || ID >= 19) // Replace only existing characters continue; BattlePlayerCharacter.PlayerModelFileName[ID] = entry[2]; // Model btl_init.model_id[ID] = entry[2]; btl_init.model_id[ID + 19] = entry[3]; // Trance model BattlePlayerCharacter.PlayerWeaponToBoneName[ID] = boneID; // Model's weapon bone for (Int32 animid = 0; animid < 34; ++animid) FF9.btl_mot.mot[ID, animid] = entry[animid + 5]; List<String> modelAnimList; String animlistID = "Animations/" + entry[2]; String animID, animModelID; if (!_animationInFolder.TryGetValue(animlistID, out modelAnimList)) modelAnimList = new List<String>(); for (Int32 animid = 0; animid < 34; ++animid) { if (!_animationReverseFolder.TryGetValue(entry[animid + 5], out animModelID)) // Animation registered in "AnimationFolderMapping.txt": use ID of registered model animModelID = entry[2]; // Custom animation: the path is "Animation/[ID of battle model]/[Anim ID]" animID = "Animations/" + animModelID + "/" + entry[animid + 5]; if (!modelAnimList.Contains(animID)) { modelAnimList.Add(animID); _animationReverseFolder[entry[animid + 5]] = animModelID; } } _animationInFolder[animlistID] = modelAnimList; } } } public const String MemoriaInfoExtension = ".memnfo"; public const String MemoriaDictionaryPatcherPath = "DictionaryPatch.txt"; public const TextureFormat DefaultTextureFormat = TextureFormat.ARGB32; public static Boolean UseBundles; public static Boolean ForceUseBundles; public static AssetFolder[] Folder; private static Dictionary<String, List<String>> _animationInFolder; private static Dictionary<String, String> _animationReverseFolder; public class AssetBundleRef { public AssetBundleRef(String strUrl, Int32 intVersionIn) { this.fullUrl = strUrl; this.version = intVersionIn; } public AssetBundle assetBundle; public Int32 version; public String fullUrl; } public class AssetFolder { public AssetFolder(String path) { this.FolderPath = path; this.DictAssetBundleRefs = new Dictionary<String, AssetBundleRef>(); } public String FolderPath; public Dictionary<String, AssetBundleRef> DictAssetBundleRefs; } }
43.622851
276
0.709408
[ "MIT" ]
FlameHorizon/Memoria
Assembly-CSharp/Global/Asset/AssetManager.cs
43,143
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// System.Array.Reverse(System.Array) /// </summary> public class ArrayReverse1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1:Reverse an int array "); try { int length = TestLibrary.Generator.GetInt16(-55); int[] i1 = new int[length]; int[] i2 = new int[length]; for (int i = 0; i < length; i++) { int value = TestLibrary.Generator.GetByte(-55); i1[i] = value; i2[length - 1 - i] = value; } Array.Reverse(i1); for (int i = 0; i < length; i++) { if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:Reverse an string array "); try { int length = TestLibrary.Generator.GetByte(-55); string[] s1 = new string[length]; string[] s2 = new string[length]; for (int i = 0; i < length; i++) { string value = TestLibrary.Generator.GetString(-55, false, 0, 255); s1[i] = value; s2[length - 1 - i] = value; } Array.Reverse(s1); for (int i = 0; i < length; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Reverse an array which only has one element"); try { Array myarray1 = Array.CreateInstance(typeof(int), 1); int value = TestLibrary.Generator.GetInt32(-55); myarray1.SetValue(value, 0); Array.Reverse(myarray1); if ((int)myarray1.GetValue(0) != value) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Reverse an array which has no element"); try { Array myarray1 = Array.CreateInstance(typeof(int), 0); Array.Reverse(myarray1); if (myarray1.Length != 0) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Reverse a string array twice which included null element"); try { string[] s1 = new string[8]{"Jack", null, "Mary", null, "Mike", "Peter", "Mary", "Joan"}; string[] s2 = new string[8]; s1.CopyTo(s2, 0); Array.Reverse(s1); Array.Reverse(s1); for (int i = 0; i < 8; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The array is a null reference "); try { Array myarray = null; Array.Reverse(myarray); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected "); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The array is not one dimension "); try { int[,] s1 = new int[2, 2] { { 1, 2 }, { 3, 4 } }; Array.Reverse(s1); TestLibrary.TestFramework.LogError("103", "The RankException is not throw as expected "); retVal = false; } catch (RankException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArrayReverse1 test = new ArrayReverse1(); TestLibrary.TestFramework.BeginTestCase("ArrayReverse1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
27.966292
118
0.503549
[ "MIT" ]
AaronRobinsonMSFT/coreclr
tests/src/CoreMangLib/cti/system/array/arrayreserse1.cs
7,467
C#
using PokemonBattele; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using MyUnityEventDispatcher; using System.Collections; using TinyTeam.UI; using Entitas; public sealed partial class BattleController : SingletonMonobehavior<BattleController>, IEndBattleEvent { public Transform PlayerTransform; public Transform PlayerPokemonTransform; public Transform EnemyPokemonTransform; private List<BattlePokemonData> wildPokemons = new List<BattlePokemonData>(); public List<BattlePokemonData> playPokemons = new List<BattlePokemonData>(); public BattlePokemonData PlayerCurPokemonData { get; private set; } public BattlePokemonData EnemyCurPokemonData { get; private set; } private GameContext context; private BattleState battleState; private int PlayChooseSkillID = -1; private int EnemyChooseSkillID = -1; public readonly float BattleTime = 2f; private string PlayerChooseBagItemName = "", EnemyChooseBagItemName = ""; public int FirstHand = -1; private bool BattlePause = false; public int BattleAroundCount = 0; private void Start() { context = Contexts.sharedInstance.game; NotificationCenter<int>.Get().AddEventListener("UseSkill", PlayerPokemonUseSkill); NotificationCenter<int>.Get().AddEventListener("PokemonDeathMessage", PokemonDeathEvent); NotificationCenter<string>.Get().AddEventListener("UseBagItem", PlayerUseBagItem); NotificationCenter<int>.Get().AddEventListener("CatchPokemon", CatchPokemonResultEvent); NotificationCenter<int>.Get().AddEventListener("ExchangePokemon", ExchangePokemon); NotificationCenter<bool>.Get().AddEventListener("BattlePause", StopBattlePause); EndBattleSystem.EndBattleEvent += EndBattleEvent; BattleStateForPlayer.InitEvent += PlayerRound; BattleStateForBattle.InitEvent += BattleRound; } public bool CanBattle { get { return null != PlayerCurPokemonData && null != EnemyCurPokemonData; } } public void InitWildPokemon(params Pokemon[] pokemons) { wildPokemons = new List<Pokemon>(pokemons) .Select(x=>BattlePokemonData.Context[x.GetInstanceID()]) .ToList(); if (0 == pokemons.Length) { Debug.LogWarning("没有野生精灵怎么打"); Contexts.sharedInstance.game.isBattleFlag = false; return; } EnemyCurPokemonData = wildPokemons[0]; } public void InitPlayerPokemons(List<Pokemon> pokemons) { playPokemons = pokemons .Select(x => BattlePokemonData.Context[x.GetInstanceID()]) .ToList(); //战斗中使用的精灵每个种族只能有一只 Dictionary<int, BattlePokemonData> map = new Dictionary<int, BattlePokemonData>(); int count = playPokemons.Count; for (int i = count -1;i>=0;--i) { BattlePokemonData pokemonData = playPokemons[i]; if (!map.ContainsKey(pokemonData.race.raceid)) map.Add(pokemonData.race.raceid, pokemonData); else { playPokemons.RemoveAt(i); } } if (0 == pokemons.Count) { Debug.LogError("没有精灵怎么打"); Contexts.sharedInstance.game.isBattleFlag = false; return; } PlayerCurPokemonData = playPokemons[0]; } public void BeginBattle() { //召唤精灵 GameObject playerPokemon = PokemonFactory.InitPokemon(PlayerCurPokemonData.race.raceid); playerPokemon.transform.position = PlayerPokemonTransform.position ; playerPokemon.transform.parent = PlayerPokemonTransform; PokemonFactory.PokemonBallEffect(playerPokemon.transform.position); GameObject enemyPokemon = PokemonFactory.InitPokemon(EnemyCurPokemonData.race.raceid); enemyPokemon.transform.position = EnemyPokemonTransform.position ; enemyPokemon.transform.parent = EnemyPokemonTransform; PokemonFactory.PokemonBallEffect(enemyPokemon.transform.position); PlayerCurPokemonData.transform = playerPokemon.transform; EnemyCurPokemonData.transform = enemyPokemon.transform; //控制精灵和训练家朝向 playerPokemon.transform.LookAt(enemyPokemon.transform); enemyPokemon.transform.LookAt(playerPokemon.transform); PlayerController.Instance.transform.LookAt(enemyPokemon.transform); Quaternion quaternion = PlayerController.Instance.transform.rotation; quaternion.x = 0; quaternion.z = 0; PlayerController.Instance.transform.rotation = quaternion; //初始化精灵数据 foreach(BattlePokemonData pokemon in playPokemons) { pokemon.Recover(); } foreach (BattlePokemonData pokemon in wildPokemons) { pokemon.Recover(); } //考虑特性 if (AbilityManager.AbilityImpacts.ContainsKey(PlayerCurPokemonData.ShowAbility)) AbilityManager.AbilityImpacts[PlayerCurPokemonData.ShowAbility] .OnBeCalled(PlayerCurPokemonData); //考虑特性 if (AbilityManager.AbilityImpacts.ContainsKey(EnemyCurPokemonData.ShowAbility)) AbilityManager.AbilityImpacts[EnemyCurPokemonData.ShowAbility] .OnBeCalled(EnemyCurPokemonData); battleState = new BattleStateForPlayer(); } public void EndBattleEvent() { //初始化精灵数据 foreach (BattlePokemonData pokemon in playPokemons) { if(pokemon.transform!= null) { pokemon.transform.gameObject.SetActive(false); ObjectPoolController.PokemonObjectsPool[pokemon.race.raceid] = pokemon.transform.gameObject; } GameEntity entity = pokemon.entity; Action action = entity.pokemonDataChangeEvent.Event; action = () => { }; entity.ReplacePokemonDataChangeEvent(action); pokemon.Recover(); } foreach (BattlePokemonData pokemon in wildPokemons) { pokemon.transform.gameObject.SetActive(false); ObjectPoolController.PokemonObjectsPool[pokemon.race.raceid] = pokemon.transform.gameObject; GameEntity entity = pokemon.entity; Action action = entity.pokemonDataChangeEvent.Event; action = () => { }; entity.ReplacePokemonDataChangeEvent(action); pokemon.Recover(); } wildPokemons = new List<BattlePokemonData>(); playPokemons = new List<BattlePokemonData>(); PlayerCurPokemonData = null; EnemyCurPokemonData = null; battleState = null; GameEntity[] entities = context.GetEntities(GameMatcher.BattlePokemonData); var playerPokemons = context.playerData.scriptableObject.pokemons; foreach (var e in entities) { if(!playerPokemons.Contains(e.battlePokemonData.data.pokemon)) { e.isDestroy = true; } } } /// <summary> /// 我方精灵使用技能 /// </summary> /// <param name="notific"></param> private void PlayerPokemonUseSkill(Notification<int> notific) { int skillID = PlayerCurPokemonData.skills[notific.param]; int pp = PlayerCurPokemonData.skillPPs[notific.param]; if (pp <= 0) { NotificationCenter<int>.Get().DispatchEvent("DisableSkillButton", notific.param); return; } if(DisableSkill.context.ContainsKey(PlayerCurPokemonData.ID)) { int disableskillID = DisableSkill.context[PlayerCurPokemonData.ID]; for(int i=0;i< PlayerCurPokemonData.skills.Count;++i) { if(disableskillID == PlayerCurPokemonData.skills[i]) { NotificationCenter<int>.Get().DispatchEvent("DisableSkillButton", i); return; } } } PlayChooseSkillID = skillID; DebugHelper.LogFormat("你选择使用了技能{0}",ResourceController.Instance.allSkillDic[PlayChooseSkillID].sname); UpdateBattleState(); } private void PlayerUseBagItem(Notification<string> notific) { PlayerChooseBagItemName = notific.param; UpdateBattleState(); } private void CatchPokemonResultEvent(Notification<int> notific) { battleState = null; StartCoroutine(WaitBattleEnd()); } private void StopBattlePause(Notification<bool> notific) { BattlePause = notific.param; } private void ExchangePokemon(Notification<int> notific) { if(PlayerCurPokemonData.ChangeStateForPokemonEnums.Contains(ChangeStateEnumForPokemon.CanNotEscape)) { //不允许逃脱 DebugHelper.LogFormat("当前精灵{0}处于逃脱状态,不允许替换精灵", PlayerCurPokemonData.Ename); return; } TTUIPage.ShowPage<UIBattle_Skills>(); BattlePokemonData newCallPokemon = playPokemons[notific.param]; ExchangePokemon(newCallPokemon); UpdateBattleState(); } private void ExchangePokemon(BattlePokemonData newCallPokemon) { DebugHelper.LogFormat("我方玩家将精灵{0}替换成了{1}", PlayerCurPokemonData.Ename, newCallPokemon.Ename); //回收精灵GameObject PlayerCurPokemonData.transform.gameObject.SetActive(false); ObjectPoolController.PokemonObjectsPool[PlayerCurPokemonData.race.raceid] = PlayerCurPokemonData.transform.gameObject; //如果剧毒就重置计数 if (AbnormalStateEnum.BadlyPoison == PlayerCurPokemonData.Abnormal) { BadlyPoisonState.count[PlayerCurPokemonData.ID] = 1; } //能力阶级重置 PlayerCurPokemonData.StatModifiers = new StatModifiers(); //考虑特性 if (AbilityManager.AbilityImpacts.ContainsKey(PlayerCurPokemonData.ShowAbility)) AbilityManager.AbilityImpacts[PlayerCurPokemonData.ShowAbility] .OnLeave(PlayerCurPokemonData); PlayerCurPokemonData = newCallPokemon; PlayChooseSkillID = -1; //召唤新的精灵 GameObject playerPokemon = PokemonFactory.InitPokemon(PlayerCurPokemonData.race.raceid); playerPokemon.transform.position = PlayerPokemonTransform.position; playerPokemon.transform.parent = PlayerPokemonTransform; PokemonFactory.PokemonBallEffect(playerPokemon.transform.position); PlayerCurPokemonData.transform = playerPokemon.transform; //控制精灵和训练家朝向 playerPokemon.transform.LookAt(EnemyCurPokemonData.transform); //考虑特性 if (AbilityManager.AbilityImpacts.ContainsKey(PlayerCurPokemonData.ShowAbility)) AbilityManager.AbilityImpacts[PlayerCurPokemonData.ShowAbility] .OnBeCalled(PlayerCurPokemonData); TTUIPage.ShowPage<UIBattle_PokemonInfos>(); } /// <summary> /// 更新战斗状态 /// </summary> private void UpdateBattleState() { if(!CanBattle) { return; } battleState = battleState.ChangeState(); } /// <summary> /// 玩家回合 /// </summary> private void PlayerRound() { DebugHelper.Log("开始进入准备回合"); BattleAroundCount++; EnemyAction(); } /// <summary> /// 对战回合 /// </summary> private void BattleRound() { if (!CanBattle) return; DebugHelper.Log("开始进入对战回合"); StartCoroutine(IEBattleAround()); } IEnumerator IEBattleAround() { var wait = new WaitWhile ( () => { return BattlePause; } ); //我方玩家使用道具 if (""!= PlayerChooseBagItemName&&ResourceController.Instance.UseBagUItemDict.ContainsKey(PlayerChooseBagItemName)) { UseBagItem use = ResourceController.Instance.UseBagUItemDict[PlayerChooseBagItemName]; if (null != use&&use.canUseInBattle) { BattlePause = true; if(!use.UseForPlay) use.Effect(EnemyCurPokemonData); else use.Effect(PlayerCurPokemonData); } } yield return wait; if(CanBattle&&null!=battleState) { if ("" != EnemyChooseBagItemName && ResourceController.Instance.UseBagUItemDict.ContainsKey(EnemyChooseBagItemName)) { UseBagItem use = ResourceController.Instance.UseBagUItemDict[EnemyChooseBagItemName]; if (null != use && use.canUseInBattle) { BattlePause = true; if (use.UseForPlay) use.Effect(EnemyCurPokemonData); else use.Effect(PlayerCurPokemonData); } } } yield return wait; //互相攻击 if(PlayChooseSkillID!=-1&&EnemyChooseSkillID!=-1) { if (PlayerCurPokemonData.Speed > EnemyCurPokemonData.Speed) { FirstHand = PlayerCurPokemonData.ID; PlayerBattleAround(); yield return wait; EnemyBattleAround(); } else { FirstHand = EnemyCurPokemonData.ID; EnemyBattleAround(); yield return wait; PlayerBattleAround(); } } else if(-1== PlayChooseSkillID && -1!= EnemyChooseSkillID) { FirstHand = EnemyCurPokemonData.ID; EnemyBattleAround(); } else if (-1 == EnemyChooseSkillID && -1 != PlayChooseSkillID) { FirstHand = PlayerCurPokemonData.ID; PlayerBattleAround(); } yield return wait; BattleAroundEnd(); } /// <summary> /// 更新玩家和精灵数据 /// </summary> private void UpdatePokemonDatas() { foreach(var data in wildPokemons) { var entity = data.entity; entity.ReplaceBattlePokemonData(data); } foreach (var data in playPokemons) { var entity = data.entity; entity.ReplaceBattlePokemonData(data); } context.ReplacePlayerData(context.playerData.scriptableObject); } private void PlayerBattleAround() { UpdatePokemonDatas(); if (CanBattle&&null!=battleState) { DebugHelper.Log("我方开始了行动"); PlayerCurPokemonData.ChooseSkillType = SkillType.NULL; if (NeedReplaceSKill.context.ContainsKey(PlayerCurPokemonData.ID)) { PlayChooseSkillID = NeedReplaceSKill.context[PlayerCurPokemonData.ID]; } if (ResourceController.Instance.allSkillDic.ContainsKey(PlayChooseSkillID)) { Skill PlayerSkill = ResourceController.Instance.allSkillDic[PlayChooseSkillID]; if (null != PlayerSkill) { BattlePause = true; PlayerCurPokemonData.ChooseSkillType = PlayerSkill.type; UseSkill.Attack(PlayerSkill, PlayerCurPokemonData, EnemyCurPokemonData); } } } } private void EnemyBattleAround() { UpdatePokemonDatas(); if (CanBattle && null != battleState) { DebugHelper.Log("敌方开始了行动"); EnemyCurPokemonData.ChooseSkillType = SkillType.NULL; if(NeedReplaceSKill.context.ContainsKey(EnemyCurPokemonData.ID)) { EnemyChooseSkillID = NeedReplaceSKill.context[EnemyCurPokemonData.ID]; } if (ResourceController.Instance.allSkillDic.ContainsKey(EnemyChooseSkillID)) { Skill EnemySkill = ResourceController.Instance.allSkillDic[EnemyChooseSkillID]; if (null != EnemySkill) { BattlePause = true; EnemyCurPokemonData.ChooseSkillType = EnemySkill.type; UseSkill.Attack(EnemySkill, EnemyCurPokemonData, PlayerCurPokemonData); } } } } private void BattleAroundEnd() { PlayerCurPokemonData.StateForAbnormal.UpdateInPlayerAround(PlayerCurPokemonData); EnemyCurPokemonData.StateForAbnormal.UpdateInPlayerAround(EnemyCurPokemonData); int cout = PlayerCurPokemonData.ChangeStateForPokemonEnums.Count; for(int i = cout-1; i>=0;--i) { var state = PlayerCurPokemonData.ChangeStateForPokemonEnums[i]; ChangeStateForPokemon.ChangeStateForPokemons[state].UpdateInPlayerAround(PlayerCurPokemonData); } cout = EnemyCurPokemonData.ChangeStateForPokemonEnums.Count; for (int i = cout - 1; i >= 0; --i) { var state = EnemyCurPokemonData.ChangeStateForPokemonEnums[i]; ChangeStateForPokemon.ChangeStateForPokemons[state].UpdateInPlayerAround(PlayerCurPokemonData); } UpdatePokemonDatas(); EnemyChooseSkillID = -1; PlayChooseSkillID = -1; PlayerChooseBagItemName = ""; EnemyChooseBagItemName = ""; if (null != battleState && CanBattle) UpdateBattleState(); } /// <summary> /// 敌方行动 /// </summary> private void EnemyAction() { int index = RandomService.game.Int(0, EnemyCurPokemonData.skills.Count); EnemyChooseSkillID = EnemyCurPokemonData.skills[index]; if (NeedReplaceSKill.context.ContainsKey(EnemyCurPokemonData.ID)) { EnemyChooseSkillID = NeedReplaceSKill.context[EnemyCurPokemonData.ID]; } DebugHelper.LogFormat("野外的精灵{0}选择使用了技能{1}", EnemyCurPokemonData.Ename, ResourceController.Instance.allSkillDic[EnemyChooseSkillID].sname); } /// <summary> /// 精灵死亡事件 /// </summary> /// <param name="notific"></param> public void PokemonDeathEvent(Notification<int> notific) { int hashcode = notific.param; if (!CanBattle||null==battleState) return; if(hashcode == PlayerCurPokemonData.ID) { DebugHelper.LogFormat("我方精灵{0}不能继续作战了", PlayerCurPokemonData.Ename); BattlePokemonData newCallPokemon = null; foreach (BattlePokemonData pokemon in playPokemons) { if(pokemon.curHealth>0) { newCallPokemon = pokemon; break; } } if(null == newCallPokemon) { PlayerCurPokemonData.transform.gameObject.SetActive(false); ObjectPoolController.PokemonObjectsPool[PlayerCurPokemonData.race.raceid] = PlayerCurPokemonData.transform.gameObject; battleState = null; StartCoroutine(WaitBattleEnd()); return; } ExchangePokemon(newCallPokemon); } else if(hashcode == EnemyCurPokemonData.ID) { DebugHelper.LogFormat("敌方精灵{0}不能继续作战了", EnemyCurPokemonData.Ename); battleState = null; StartCoroutine(WaitBattleEnd()); } } private IEnumerator WaitBattleEnd() { string winer = "敌方"; if(null == EnemyCurPokemonData||EnemyCurPokemonData.curHealth<=0) { winer = "我方"; WinResoult(); } DebugHelper.LogFormat("战斗结束,{0}取得了胜利",winer); TTUIPage.ShowPage<UIBattleResult>(); yield return new WaitForSeconds(BattleTime+0.5f); context.isBattleFlag = false; } /// <summary> /// 获胜后的奖励 /// </summary> private void WinResoult() { var bagitems = ResourceController.Instance.UseBagUItemDict.Keys; var trainer = context.playerData.scriptableObject; var trainerBagItems = trainer.bagItems; int randomIndex = RandomService.game.Int(0, bagitems.Count); int i = 0; string itemName = ""; foreach (var item in bagitems) { if(i++ == randomIndex) { itemName = item; break; } } if(bagitems.Contains(itemName)) { int itemCount = RandomService.game.Int(1, 5); DebugHelper.LogFormat("玩家获得 {0} {1}个", itemName, itemCount); trainerBagItems.Add(BagItems.Build(itemName,itemCount )); context.ReplacePlayerData(trainer); } } }
32.887147
128
0.604804
[ "MIT" ]
Avatarchik/Pokemon_Unity3D_Entitas
Assets/Scripts/Controllers/BattleController.cs
21,576
C#
using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Facebook; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Nop.Core; using Nop.Plugin.ExternalAuth.Facebook.Models; using Nop.Services.Authentication.External; using Nop.Services.Configuration; using Nop.Services.Localization; using Nop.Services.Messages; using Nop.Services.Security; using Nop.Web.Framework; using Nop.Web.Framework.Controllers; using Nop.Web.Framework.Mvc.Filters; namespace Nop.Plugin.ExternalAuth.Facebook.Controllers { public class FacebookAuthenticationController : BasePluginController { #region Fields private readonly FacebookExternalAuthSettings _facebookExternalAuthSettings; private readonly IAuthenticationPluginManager _authenticationPluginManager; private readonly IExternalAuthenticationService _externalAuthenticationService; private readonly ILocalizationService _localizationService; private readonly INotificationService _notificationService; private readonly IOptionsMonitorCache<FacebookOptions> _optionsCache; private readonly IPermissionService _permissionService; private readonly ISettingService _settingService; private readonly IStoreContext _storeContext; private readonly IWorkContext _workContext; #endregion #region Ctor public FacebookAuthenticationController(FacebookExternalAuthSettings facebookExternalAuthSettings, IAuthenticationPluginManager authenticationPluginManager, IExternalAuthenticationService externalAuthenticationService, ILocalizationService localizationService, INotificationService notificationService, IOptionsMonitorCache<FacebookOptions> optionsCache, IPermissionService permissionService, ISettingService settingService, IStoreContext storeContext, IWorkContext workContext) { _facebookExternalAuthSettings = facebookExternalAuthSettings; _authenticationPluginManager = authenticationPluginManager; _externalAuthenticationService = externalAuthenticationService; _localizationService = localizationService; _notificationService = notificationService; _optionsCache = optionsCache; _permissionService = permissionService; _settingService = settingService; _storeContext = storeContext; _workContext = workContext; } #endregion #region Methods [AuthorizeAdmin] [Area(AreaNames.Admin)] public IActionResult Configure() { if (!_permissionService.Authorize(StandardPermissionProvider.ManageExternalAuthenticationMethods)) return AccessDeniedView(); var model = new ConfigurationModel { ClientId = _facebookExternalAuthSettings.ClientKeyIdentifier, ClientSecret = _facebookExternalAuthSettings.ClientSecret }; return View("~/Plugins/ExternalAuth.Facebook/Views/Configure.cshtml", model); } [HttpPost] [AdminAntiForgery] [AuthorizeAdmin] [Area(AreaNames.Admin)] public IActionResult Configure(ConfigurationModel model) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageExternalAuthenticationMethods)) return AccessDeniedView(); if (!ModelState.IsValid) return Configure(); //save settings _facebookExternalAuthSettings.ClientKeyIdentifier = model.ClientId; _facebookExternalAuthSettings.ClientSecret = model.ClientSecret; _settingService.SaveSetting(_facebookExternalAuthSettings); //clear Facebook authentication options cache _optionsCache.TryRemove(FacebookDefaults.AuthenticationScheme); _notificationService.SuccessNotification(_localizationService.GetResource("Admin.Plugins.Saved")); return Configure(); } public IActionResult Login(string returnUrl) { var methodIsAvailable = _authenticationPluginManager .IsPluginActive(FacebookAuthenticationDefaults.SystemName, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id); if (!methodIsAvailable) throw new NopException("Facebook authentication module cannot be loaded"); if (string.IsNullOrEmpty(_facebookExternalAuthSettings.ClientKeyIdentifier) || string.IsNullOrEmpty(_facebookExternalAuthSettings.ClientSecret)) { throw new NopException("Facebook authentication module not configured"); } //configure login callback action var authenticationProperties = new AuthenticationProperties { RedirectUri = Url.Action("LoginCallback", "FacebookAuthentication", new { returnUrl = returnUrl }) }; authenticationProperties.SetString(FacebookAuthenticationDefaults.ErrorCallback, Url.RouteUrl("Login", new { returnUrl })); return Challenge(authenticationProperties, FacebookDefaults.AuthenticationScheme); } public async Task<IActionResult> LoginCallback(string returnUrl) { //authenticate Facebook user var authenticateResult = await HttpContext.AuthenticateAsync(FacebookDefaults.AuthenticationScheme); if (!authenticateResult.Succeeded || !authenticateResult.Principal.Claims.Any()) return RedirectToRoute("Login"); //create external authentication parameters var authenticationParameters = new ExternalAuthenticationParameters { ProviderSystemName = FacebookAuthenticationDefaults.SystemName, AccessToken = await HttpContext.GetTokenAsync(FacebookDefaults.AuthenticationScheme, "access_token"), Email = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Email)?.Value, ExternalIdentifier = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value, ExternalDisplayIdentifier = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Name)?.Value, Claims = authenticateResult.Principal.Claims.Select(claim => new ExternalAuthenticationClaim(claim.Type, claim.Value)).ToList() }; //authenticate Nop user return _externalAuthenticationService.Authenticate(authenticationParameters, returnUrl); } #endregion } }
44.322581
143
0.705386
[ "MIT" ]
EvaSRGitHub/NopCommerce-HomePageNewProductsPlugin
src/Plugins/Nop.Plugin.ExternalAuth.Facebook/Controllers/FacebookAuthenticationController.cs
6,872
C#
namespace MLAPI.Serialization { /// <summary> /// Arithmetic helper class /// </summary> public static class Arithmetic { // Sign bits for different data types internal const long SIGN_BIT_64 = -9223372036854775808; internal const int SIGN_BIT_32 = -2147483648; internal const short SIGN_BIT_16 = -32768; internal const sbyte SIGN_BIT_8 = -128; // Ceiling function that doesn't deal with floating point values // these only work correctly with possitive numbers internal static ulong CeilingExact(ulong u1, ulong u2) => (u1 + u2 - 1) / u2; internal static long CeilingExact(long u1, long u2) => (u1 + u2 - 1) / u2; internal static uint CeilingExact(uint u1, uint u2) => (u1 + u2 - 1) / u2; internal static int CeilingExact(int u1, int u2) => (u1 + u2 - 1) / u2; internal static ushort CeilingExact(ushort u1, ushort u2) => (ushort)((u1 + u2 - 1) / u2); internal static short CeilingExact(short u1, short u2) => (short)((u1 + u2 - 1) / u2); internal static byte CeilingExact(byte u1, byte u2) => (byte)((u1 + u2 - 1) / u2); internal static sbyte CeilingExact(sbyte u1, sbyte u2) => (sbyte)((u1 + u2 - 1) / u2); /// <summary> /// ZigZag encodes a signed integer and maps it to a unsigned integer /// </summary> /// <param name="value">The signed integer to encode</param> /// <returns>A ZigZag encoded version of the integer</returns> public static ulong ZigZagEncode(long value) => (ulong)((value >> 63) ^ (value << 1)); /// <summary> /// Decides a ZigZag encoded integer back to a signed integer /// </summary> /// <param name="value">The unsigned integer</param> /// <returns>The signed version of the integer</returns> public static long ZigZagDecode(ulong value) => (((long)(value >> 1) & 0x7FFFFFFFFFFFFFFFL) ^ ((long)(value << 63) >> 63)); /// <summary> /// Gets the output size in bytes after VarInting a unsigned integer /// </summary> /// <param name="value">The unsigned integer whose length to get</param> /// <returns>The amount of bytes</returns> public static int VarIntSize(ulong value) => value <= 240 ? 1 : value <= 2287 ? 2 : value <= 67823 ? 3 : value <= 16777215 ? 4 : value <= 4294967295 ? 5 : value <= 1099511627775 ? 6 : value <= 281474976710655 ? 7 : value <= 72057594037927935 ? 8 : 9; internal static long Div8Ceil(ulong value) => (long)((value >> 3) + ((value & 1UL) | ((value >> 1) & 1UL) | ((value >> 2) & 1UL))); } }
48.333333
139
0.581488
[ "MIT" ]
0vjm3wfw9gqm4j/com.unity.multiplayer.mlapi
com.unity.multiplayer.mlapi/Runtime/Serialization/Arithmetic.cs
2,757
C#
using System; using Eto.Drawing; using System.Reflection; using Eto.Forms; using System.Collections.Generic; namespace Pablo.Formats.Rip.Tools { public class Bezier : TwoPointTool<Commands.Bezier> { int segments = 100; int? movingPoint; bool moving; Point? connectingPoint; public override string Description { get { return "Draws a curved line with four control points (Z)"; } } public override Keys Accelerator { get { return Keys.Z; } } public override Eto.Drawing.Image Image { get { return ImageCache.BitmapFromResource("Pablo.Formats.Rip.Icons.Bezier.png"); } } public override IEnumerable<RipOptionalCommand> Styles { get { foreach (var style in base.Styles) yield return style; yield return Document.Create<Commands.Color>(); yield return Document.Create<Commands.LineStyle>(); } } protected override void SetStartLocation (Point start, Keys modifiers, Point location) { start = Point.Max (Point.Empty, start); this.Command.Points = new Point[4]; this.Command.Points [0] = start; this.Command.Segments = segments; } protected override void SetEndLocation (Point end, Keys modifiers, Point location) { end = Point.Max (Point.Empty, end); var start = this.Command.Points [0]; var inc = (end - start) / 3; this.Command.Points [1] = connectingPoint ?? start + inc; this.Command.Points [2] = start + inc * 2; this.Command.Points [3] = end; } void FindClosestPoint (Point location) { double distance = double.MaxValue; for (int i = 0; i<this.Command.Points.Length; i++) { var point = this.Command.Points [i]; var dist = Point.Distance (point, location); if (dist < distance) { distance = dist; movingPoint = i; } } } public override void Unselected () { base.Unselected (); moving = false; movingPoint = null; } protected override void ApplyInvertedDrawing (IList<Rectangle> updates = null) { base.ApplyInvertedDrawing (updates); var points = this.Command.Points; var oldcol = this.BGI.GetColor (); var oldlinestyle = this.BGI.GetLineStyle (); var oldthickness = this.BGI.GetLineThickness (); this.BGI.SetColor (1); this.BGI.SetLineStyle (Pablo.BGI.BGICanvas.LineStyle.Dotted); this.BGI.SetLineThickness (1); this.BGI.DrawPoly (new Point[] { points [0], points [1], points [3], points [2] }, updates); this.BGI.SetColor (2); this.BGI.SetLineStyle (Pablo.BGI.BGICanvas.LineStyle.Solid); this.BGI.SetLineThickness (oldthickness); foreach (var point in points) { this.BGI.Ellipse (new Rectangle (point - 3, new Size (6, 6)), updates); } this.BGI.SetColor (oldcol); this.BGI.SetLineStyle (oldlinestyle); } public override void OnMouseDown (MouseEventArgs e) { if (moving) { switch (e.Buttons) { case MouseButtons.Primary: FindClosestPoint ((Point)e.Location); break; } } else base.OnMouseDown (e); } public override void OnMouseMove (MouseEventArgs e) { if (moving) { switch (e.Buttons) { case MouseButtons.Primary: if (movingPoint != null) { var updates = new List<Rectangle> (); RemoveDrawing (updates); this.Command.Points [movingPoint.Value] = Point.Max (Point.Empty, (Point)e.Location); ApplyDrawing (updates); Handler.FlushCommands (updates); e.Handled = true; } break; } } else base.OnMouseMove (e); } public override void OnMouseUp (MouseEventArgs e) { if (moving) { switch (e.Buttons) { case MouseButtons.Primary: if (movingPoint != null) { var updates = new List<Rectangle> (); RemoveDrawing (updates); this.Command.Points [movingPoint.Value] = Point.Max (Point.Empty, (Point)e.Location); ApplyDrawing (updates); Handler.FlushCommands (updates); movingPoint = null; } break; case MouseButtons.Alternate: Finish (e.Modifiers, (Point)e.Location); break; } } else base.OnMouseUp (e); } void Finish (Keys modifiers, Point location) { Start = this.Command.Points [3]; connectingPoint = Start + (Start - this.Command.Points[2]); var updates = new List<Rectangle> (); moving = false; movingPoint = null; RemoveDrawing (updates); base.FinishCommand (modifiers, updates); CreateCommand (); SetStartLocation (Start, Keys.None, Start); SetEndLocation (location, Keys.None, location); ApplyDrawing (updates); Handler.FlushCommands (updates); } protected override void FinishCommand (Keys modifiers, IList<Rectangle> updates = null) { moving = true; connectingPoint = null; ApplyDrawing (updates); } public override Control GeneratePad () { var layout = new DynamicLayout { Padding = Padding.Empty, Spacing = Size.Empty }; //layout.Container.MinimumSize = new Size (100, 20); layout.Add(TopSeparator()); layout.Add (new Controls.LineStylePad (Handler, true)); var font = new Font (SystemFont.Default, 7); layout.Add (new Label{ Text = "Segments", Font = font, HorizontalAlign = HorizontalAlign.Center }); var segmentBox = new NumericUpDown{ Font = new Font (SystemFont.Default, 8), Value = segments, MinValue = 1, MaxValue = 999, Size = new Size(20, -1) }; segmentBox.ValueChanged += delegate { segments = Math.Min (999, Math.Max (1, (int)segmentBox.Value)); if (Command != null) { var updates = new List<Rectangle> (); RemoveDrawing (updates); Command.Segments = segments; ApplyDrawing (updates); Handler.FlushCommands (updates); } }; layout.Add (segmentBox); layout.Add (null); return layout; } } }
25.690265
102
0.650534
[ "MIT" ]
blocktronics/pablodraw
Source/Pablo/Formats/Rip/Tools/Bezier.cs
5,806
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using Trifolia.Authentication; using Trifolia.Shared; using Trifolia.Authorization; namespace Trifolia.Web { public class SecurableForm : Page { protected override void OnPreLoad(EventArgs e) { SecurableAttribute securableAttribute = this.GetType().GetCustomAttributes(true).SingleOrDefault(y => y.GetType() == typeof(SecurableAttribute)) as SecurableAttribute; if (securableAttribute != null && securableAttribute.SecurableNames != null && !UserHasSecurable(securableAttribute.SecurableNames)) { RedirectToLogin(); return; } base.OnPreLoad(e); } /// <summary> /// Overloaded version of UserHasSecurable(string[]) for checking a single securable /// </summary> public bool UserHasSecurable(string securable) { if (string.IsNullOrEmpty(securable)) return true; return UserHasSecurable(new string[] { securable }); } /// <summary> /// Determines if the authenticated user has a role associated with the named securable. /// </summary> /// <param name="securables">The name(s) of the securable to check.</param> /// <returns>Returns false if a user is not logged in. Return true if the authenticated user has a role associated with the requested securable, otherwise returns false.</returns> public bool UserHasSecurable(string[] securables) { if (securables.Count(y => string.IsNullOrEmpty(y)) > 0) return true; if (!Page.User.Identity.IsAuthenticated) return false; string userName = Page.User.Identity.Name; if (CheckPoint.Instance.Authorize(userName, securables) == AuthorizationTypes.AuthorizationSuccessful) return true; return false; } private void RedirectToLogin() { string url = string.Format("/Account/Login?ReturnUrl={0}", Request.Url.AbsolutePath); Response.Redirect(url); } } }
33.235294
187
0.618142
[ "Apache-2.0" ]
BOBO41/trifolia
Trifolia.Web/SecurableForm.cs
2,262
C#
namespace dotnet_dbinfo { public enum SupportedDatabaseType { SQLSERVER, DYNAMODB, COSMOSDB, MONGODB, SQLAZURE } }
14
37
0.553571
[ "MIT" ]
berkid89/dotnet-dbinfo
dotnet-dbinfo/SupportedDatabaseType.cs
170
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Sunny.UI; using DEETU.Map; using DEETU.Tool; using DEETU.Core; using DEETU.Source.Window.LayerAttributes; using System.Drawing.Drawing2D; using System.Security.Cryptography; namespace DEETU.Source.Window { public partial class FillSymbolPage : UITitlePage { #region 字段 private GeoMapLayer mLayer; // 渲染的图层 private GeoSimpleRenderer mSimpleRenderer = null; // 记录生成的简单渲染 private GeoClassBreaksRenderer mClassBreaksRenderer = null; // 记录生成的分级渲染 private GeoUniqueValueRenderer mUniqueValueRenderer = null; // 记录生成的唯一值渲染 private List<GeoUniqueValueRenderer> mUniqueValueRenderers = new List<GeoUniqueValueRenderer>(); // 为了渐变色选择框的方便,生成渲染并存储在这里 private List<GeoClassBreaksRenderer> mClassBreaksRenderers = new List<GeoClassBreaksRenderer>(); private Color[][] mColors = GeoMapDrawingTools.GetColors(); // 提前生成一点好看的颜色 private Button mClassDefaultButton = null; // 给两个渲染添加默认值 private Button mUniqueDefaultButton = null; #endregion public FillSymbolPage(GeoMapLayer layer) { InitializeComponent(); mLayer = layer; renderMethodCB.SelectedIndexChanged += RenderMethodCB_SelectedIndexChanged; renderTabControl.SelectedIndexChanged += RenderTabControl_SelectedIndexChanged; InitializeTabs(); } private void InitializeTabs() { // Backgroud color simpleTab.BackColor = this.BackColor; uniqueValueTab.BackColor = this.BackColor; classBreakTab.BackColor = this.BackColor; // 一些基本的属性 foreach(GeoSimpleLineSymbolStyleConstant s in Enum.GetValues(typeof(GeoSimpleLineSymbolStyleConstant))) { edgeStyleComboBox.Items.Add(s.ToString()); } for (int i = 0; i < mLayer.AttributeFields.Count; i++) uniqueFieldComboBox.Items.Add(mLayer.AttributeFields.GetItem(i).Name); for (int i = 0; i < mLayer.AttributeFields.Count; i++) if(mLayer.AttributeFields.GetItem(i).ValueType != GeoValueTypeConstant.dText) classFieldComboBox.Items.Add(mLayer.AttributeFields.GetItem(i).Name); // 对于不同的渲染模式进行配置 // 通过出触发时间来进行处理 if (mLayer.Renderer.RendererType == GeoRendererTypeConstant.Simple) { mSimpleRenderer = mLayer.Renderer as GeoSimpleRenderer; renderMethodCB.SelectedIndex = 0; renderTabControl.SelectedIndex = 0; initializeSimpleRenderer(); } else if (mLayer.Renderer.RendererType == GeoRendererTypeConstant.UniqueValue) { mUniqueValueRenderer = mLayer.Renderer as GeoUniqueValueRenderer; renderMethodCB.SelectedIndex = 1; renderTabControl.SelectedIndex = 1; uniqueFieldComboBox.SelectedIndex = mLayer.AttributeFields.FindField(mUniqueValueRenderer.Field); } else { mClassBreaksRenderer = mLayer.Renderer as GeoClassBreaksRenderer; uiIntegerUpDown2.Value = (mLayer.Renderer as GeoClassBreaksRenderer).BreakCount; renderMethodCB.SelectedIndex = 2; renderTabControl.SelectedIndex = 2; classFieldComboBox.SelectedItem = mClassBreaksRenderer.Field; // classFieldComboBox.SelectedIndex = mLayer.AttributeFields.FindField(mClassBreaksRenderer.Field); } } // 建立简单渲染的图片 private Bitmap CreateSimpleFillSymbolImage(GeoSimpleFillSymbol symbol) { Bitmap styleImage = new Bitmap(50, 25); Graphics g = Graphics.FromImage(styleImage); SolidBrush sBrush = new SolidBrush(symbol.Color); Pen sPen = new Pen(symbol.Outline.Color, (float)symbol.Outline.Size); g.FillRectangle(sBrush, new Rectangle(0, 0, styleImage.Width, styleImage.Height)); g.DrawRectangle(sPen, new Rectangle(0, 0, styleImage.Width, styleImage.Height)); return styleImage; } // 建立默认按钮 private Button GetFillSymbolButton(GeoSimpleFillSymbol symbol, string name) { Button sButton = new Button(); sButton.BackColor = symbol.Color; sButton.Name = name; sButton.Dock = DockStyle.Fill; sButton.FlatAppearance.BorderColor = symbol.Outline.Color; sButton.FlatAppearance.BorderSize = (int)symbol.Outline.Size; MouseEventHandler handler = (sender, e) => SymbolGridButton_MouseClick(sButton, symbol); sButton.MouseClick += handler; return sButton; } #region event // 处理默认按钮弹出的事件 private void SymbolGridButton_MouseClick(Button button, GeoSimpleFillSymbol symbol) { EditSimpleSymbolForm SimpleForm = new EditSimpleSymbolForm(symbol); FormClosedEventHandler handle = (sender, e) => SimpleForm_FormClosed(button, symbol); SimpleForm.FormClosed += handle; SimpleForm.Show(); } // 在默认按钮修改完成以后,进行刷新 private void SimpleForm_FormClosed(Button button, GeoSimpleFillSymbol symbol) { button.BackColor = symbol.Color; button.FlatAppearance.BorderColor = symbol.Outline.Color; button.FlatAppearance.BorderSize = (int)symbol.Outline.Size; button.Refresh(); if (button.Name == "class") UpdateClassBreaksRenderersOutLine(); else if (button.Name == "unique") UpdateUniqueValueRenderersOutLine(); } // 选择颜色 private void fillColorPicker_ValueChanged(object sender, Color value) { ((mLayer.Renderer as GeoSimpleRenderer).Symbol as GeoSimpleFillSymbol).Color = value; } // 选择边框颜色 private void edgeColorPicker_ValueChanged(object sender, Color value) { ((mLayer.Renderer as GeoSimpleRenderer).Symbol as GeoSimpleFillSymbol).Outline.Color = value; } // 选择宽度 private void edgeWidthDoubleUpDown_ValueChanged(object sender, double value) { ((mLayer.Renderer as GeoSimpleRenderer).Symbol as GeoSimpleFillSymbol).Outline.Size = value; } // 选择边框样式 private void edgeStyleComboBox_SelectedIndexChanged(object sender, EventArgs e) { ((mLayer.Renderer as GeoSimpleRenderer).Symbol as GeoSimpleFillSymbol).Outline.Style = (GeoSimpleLineSymbolStyleConstant)edgeStyleComboBox.SelectedIndex; } // 唯一值渲染字段修改 private void uniqueFieldComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (uniqueFieldComboBox.SelectedIndex == -1) return; // 如果没有新建唯一值渲染,或者是新的字段 if (mUniqueValueRenderer == null || mUniqueValueRenderer.Field != uniqueFieldComboBox.SelectedItem.ToString()) { mLayer.Renderer = CreateUniqueValueRenderer(uniqueFieldComboBox.SelectedItem.ToString()); mUniqueValueRenderer = mLayer.Renderer as GeoUniqueValueRenderer; } if(mLayer.Renderer != null) { initializeUniqueValueRenderer(); } } // 分级渲染字段修改 private void classFieldComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (classFieldComboBox.SelectedIndex == -1) return; // 如果没有新建分级渲染,或者是新的字段 if (mClassBreaksRenderer == null || mClassBreaksRenderer.Field != classFieldComboBox.SelectedItem.ToString()) { // 新建一个渐变色 Color sStartColor = new GeoSimpleFillSymbol().Color; Color sEndColor = Color.FromArgb(sStartColor.R / 2, sStartColor.G / 2, sStartColor.B / 2); mLayer.Renderer = CreateClassBreaksRenderer(classFieldComboBox.SelectedItem.ToString(), uiIntegerUpDown2.Value, sStartColor, sEndColor); mClassBreaksRenderer = mLayer.Renderer as GeoClassBreaksRenderer; } if(mLayer.Renderer != null) { initializeClassBreaksRenderer(uiIntegerUpDown2.Value); } } // 绘制渐变色的combobox private void ClassColorgradComboBox_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index == -1) return; Graphics g = e.Graphics; Rectangle r = e.Bounds; Color StartColor = (mClassBreaksRenderers[e.Index].GetSymbol(0) as GeoSimpleFillSymbol).Color; Color EndColor = (mClassBreaksRenderers[e.Index].GetSymbol(mClassBreaksRenderers[e.Index].BreakCount - 1) as GeoSimpleFillSymbol).Color; LinearGradientBrush sBrush = new LinearGradientBrush(new RectangleF(r.X, r.Y, r.Width, r.Height - 2), StartColor, EndColor, LinearGradientMode.Horizontal); e.Graphics.FillRectangle(sBrush, r); g.DrawRectangle(new Pen(this.BackColor), r); e.DrawFocusRectangle(); } // 绘制唯一值渲染的颜色选择盒 private void UniqueColorgradComboBox_DrawItem(object sender, DrawItemEventArgs e) { if(e.Index == -1) return; Graphics g = e.Graphics; Rectangle r = e.Bounds; int n = mUniqueValueRenderers[e.Index].ValueCount; for (int i = 0; i < n; ++i) { SolidBrush sBrush = new SolidBrush((mUniqueValueRenderers[e.Index].GetSymbol(i) as GeoSimpleFillSymbol).Color); Rectangle sRect = new Rectangle(r.X + i * r.Width / n, r.Y, r.Width / n, r.Height); g.FillRectangle(sBrush, sRect); } g.DrawRectangle(new Pen(this.BackColor), r); e.DrawFocusRectangle(); } // 选择渲染方式变化时的函数 // 大体上就是判断一下是否点击过,点击过之后不会生成新的,不会因为用户选择别的方式而删除前面编辑的结果 private void RenderTabControl_SelectedIndexChanged(object sender, EventArgs e) { renderMethodCB.SelectedIndex = renderTabControl.SelectedIndex; if (renderMethodCB.SelectedItem.ToString() == "单一符号") { if (mSimpleRenderer == null) { mLayer.Renderer = CreateSimpleRenderer(); initializeSimpleRenderer(); } else mLayer.Renderer = mSimpleRenderer; } else if (renderMethodCB.SelectedItem.ToString() == "分级符号") { if(classFieldComboBox.Items.Count == 0) { MessageBox.Show("没有可以渲染的字段"); } else if (mClassBreaksRenderer == null) { classFieldComboBox.SelectedIndex = 0; } else mLayer.Renderer = mClassBreaksRenderer; } else if (renderMethodCB.SelectedItem.ToString() == "唯一值") { if (uniqueFieldComboBox.Items.Count == 0) { MessageBox.Show("没有可以渲染的字段"); } else if (mUniqueValueRenderer == null) { uniqueFieldComboBox.SelectedIndex = 0; } else mLayer.Renderer = mUniqueValueRenderer; } } private void RenderMethodCB_SelectedIndexChanged(object sender, EventArgs e) { renderTabControl.SelectedIndex = renderMethodCB.SelectedIndex; } // 创建一个分级渲染 // 用字段,分级数,起始颜色,终止颜色来进行处理 private GeoClassBreaksRenderer CreateClassBreaksRenderer(string field, int n, Color startColor, Color endColor) { try { GeoClassBreaksRenderer sRenderer = new GeoClassBreaksRenderer(); sRenderer.Field = field; List<double> sValues = new List<double>(); int sFeatureCount = mLayer.Features.Count; int sFieldIndex = mLayer.AttributeFields.FindField(sRenderer.Field); GeoValueTypeConstant sFieldValueType = mLayer.AttributeFields.GetItem(sFieldIndex).ValueType; switch (sFieldValueType) { case GeoValueTypeConstant.dDouble: for (int i = 0; i < sFeatureCount; i++) { double sValue = Convert.ToDouble(mLayer.Features.GetItem(i).Attributes.GetItem(sFieldIndex)); sValues.Add(sValue); } break; case GeoValueTypeConstant.dSingle: for (int i = 0; i < sFeatureCount; i++) { double sValue = Convert.ToSingle(mLayer.Features.GetItem(i).Attributes.GetItem(sFieldIndex)); sValues.Add(sValue); } break; case GeoValueTypeConstant.dInt16: for (int i = 0; i < sFeatureCount; i++) { double sValue = Convert.ToInt16(mLayer.Features.GetItem(i).Attributes.GetItem(sFieldIndex)); sValues.Add(sValue); } break; case GeoValueTypeConstant.dInt32: for (int i = 0; i < sFeatureCount; i++) { double sValue = Convert.ToInt32(mLayer.Features.GetItem(i).Attributes.GetItem(sFieldIndex)); sValues.Add(sValue); } break; case GeoValueTypeConstant.dInt64: for (int i = 0; i < sFeatureCount; i++) { double sValue = Convert.ToInt64(mLayer.Features.GetItem(i).Attributes.GetItem(sFieldIndex)); sValues.Add(sValue); } break; } double sMinValue = sValues.Min(); double sMaxValue = sValues.Max(); for (int i = 0; i < n; i++) { double sValue = sMinValue + (sMaxValue - sMinValue) * (i + 1) / n; GeoSimpleFillSymbol sSymbol = new GeoSimpleFillSymbol(); sRenderer.AddBreakValue(sValue, sSymbol); } Color sStartColor = startColor; Color sEndColor = endColor; sRenderer.RampColor(sStartColor, sEndColor); sRenderer.DefaultSymbol = new GeoSimpleFillSymbol(); return sRenderer; } catch(Exception e) { MessageBox.Show("这个字段无法进行分级渲染!"); return null; } } // 当唯一值颜色选择过后修改DataGridView private void uniqueColorgradComboBox_SelectedIndexChanged(object sender, EventArgs e) { mLayer.Renderer = mUniqueValueRenderer = mUniqueValueRenderers[uniqueColorgradComboBox.SelectedIndex]; uniqueDataGridView.Rows.Clear(); GeoUniqueValueRenderer uniqueValueRenderer = mLayer.Renderer as GeoUniqueValueRenderer; for (int i = 0; i < uniqueValueRenderer.ValueCount; i++) { GeoSimpleFillSymbol fillSymbol = (GeoSimpleFillSymbol)uniqueValueRenderer.GetSymbol(i); Bitmap symbolImage = CreateSimpleFillSymbolImage(fillSymbol); uniqueDataGridView.AddRow(symbolImage, uniqueValueRenderer.GetValue(i)); } uniqueDataGridView.Refresh(); } // 分级渲染修改后刷新DataGridView private void classColorgradComboBox_SelectedIndexChanged(object sender, EventArgs e) { mLayer.Renderer = mClassBreaksRenderer = mClassBreaksRenderers[classColorgradComboBox.SelectedIndex]; classDataGridView.Rows.Clear(); GeoClassBreaksRenderer classBreaksRenderer = mLayer.Renderer as GeoClassBreaksRenderer; for (int i = 0; i < classBreaksRenderer.BreakCount; i++) { GeoSimpleFillSymbol fillSymbol = (GeoSimpleFillSymbol)classBreaksRenderer.GetSymbol(i); Bitmap symbolImage = CreateSimpleFillSymbolImage(fillSymbol); classDataGridView.AddRow(symbolImage, classBreaksRenderer.GetBreakValue(i).ToString("F2")); } classDataGridView.Refresh(); } // 可以单独修改唯一值单个符号 private void uniqueDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0) { EditSimpleSymbolForm SimpleForm = new EditSimpleSymbolForm((mLayer.Renderer as GeoUniqueValueRenderer).GetSymbol(e.RowIndex)); FormClosedEventHandler handle = (obj, eve) => DataGridView_FormClosed(e.RowIndex, GeoRendererTypeConstant.UniqueValue); SimpleForm.FormClosed += handle; SimpleForm.Show(); } } // 可以单独修改分级的单个符号 private void classDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0) { EditSimpleSymbolForm SimpleForm = new EditSimpleSymbolForm((mLayer.Renderer as GeoClassBreaksRenderer).GetSymbol(e.RowIndex)); FormClosedEventHandler handle = (obj, eve) => DataGridView_FormClosed(e.RowIndex, GeoRendererTypeConstant.ClassBreaks); SimpleForm.FormClosed += handle; SimpleForm.Show(); } }// 在datagridview的符号修改之后,要对那个修改的符号进行刷新 private void DataGridView_FormClosed(int index, GeoRendererTypeConstant type) { if (type == GeoRendererTypeConstant.ClassBreaks) { GeoSimpleFillSymbol symbol = (GeoSimpleFillSymbol)(mLayer.Renderer as GeoClassBreaksRenderer).GetSymbol(index); classDataGridView.Rows[index].Cells[0].Value = CreateSimpleFillSymbolImage(symbol); classDataGridView.Refresh(); } else if (type == GeoRendererTypeConstant.UniqueValue) { GeoSimpleFillSymbol symbol = (GeoSimpleFillSymbol)(mLayer.Renderer as GeoUniqueValueRenderer).GetSymbol(index); uniqueDataGridView.Rows[index].Cells[0].Value = CreateSimpleFillSymbolImage(symbol); uniqueDataGridView.Refresh(); } } // 修改了分级数 private void uiIntegerUpDown2_ValueChanged(object sender, int value) { if (mClassBreaksRenderer == null) { MessageBox.Show("当前没有可以调整分级数的渲染!"); return; } if (mClassBreaksRenderer.BreakCount != value) { Color sStartColor = (mClassBreaksRenderer.GetSymbol(0) as GeoSimpleFillSymbol).Color; Color sEndColor = (mClassBreaksRenderer.GetSymbol(mClassBreaksRenderer.BreakCount - 1) as GeoSimpleFillSymbol).Color; mLayer.Renderer = CreateClassBreaksRenderer(classFieldComboBox.SelectedItem.ToString(), value, sStartColor, sEndColor); mClassBreaksRenderer = mLayer.Renderer as GeoClassBreaksRenderer; } if (mLayer.Renderer != null) { initializeClassBreaksRenderer(value); } } #endregion // 创建简单渲染 private void initializeSimpleRenderer() { GeoSimpleRenderer simpleRenderer = (GeoSimpleRenderer)mLayer.Renderer; mSimpleRenderer = simpleRenderer; GeoSimpleFillSymbol fillSymbol = (GeoSimpleFillSymbol)simpleRenderer.Symbol; fillColorPicker.Value = fillSymbol.Color; edgeColorPicker.Value = fillSymbol.Outline.Color; edgeWidthDoubleUpDown.Value = fillSymbol.Outline.Size; edgeStyleComboBox.SelectedIndex = (int)fillSymbol.Outline.Style; } // 初始化唯一值渲染界面 private void initializeUniqueValueRenderer() { uniqueColorgradComboBox.Items.Clear(); uniqueDataGridView.Rows.Clear(); mUniqueValueRenderers.Clear(); GeoUniqueValueRenderer uniqueValueRenderer = (GeoUniqueValueRenderer)mLayer.Renderer; mUniqueValueRenderer = uniqueValueRenderer; mUniqueValueRenderers.Add(mUniqueValueRenderer); if (mUniqueDefaultButton != null) uniqueTableLayoutPanel.Controls.Remove(mUniqueDefaultButton); Button defaultSymbolButton = GetFillSymbolButton((GeoSimpleFillSymbol)uniqueValueRenderer.DefaultSymbol, "unique"); mUniqueDefaultButton = defaultSymbolButton; uniqueTableLayoutPanel.Controls.Add(defaultSymbolButton, 1, 2); for (int i = 0; i < uniqueValueRenderer.ValueCount; i++) { GeoSimpleFillSymbol fillSymbol = (GeoSimpleFillSymbol)uniqueValueRenderer.GetSymbol(i); Bitmap symbolImage = CreateSimpleFillSymbolImage(fillSymbol); uniqueDataGridView.AddRow(symbolImage, uniqueValueRenderer.GetValue(i)); } CreateUniqueValueRenderers((mLayer.Renderer as GeoUniqueValueRenderer).Field); uniqueColorgradComboBox.Items.AddRange(mUniqueValueRenderers.ToArray()); uniqueColorgradComboBox.SelectedIndex = 0; uniqueDataGridView.Refresh(); } // 初始化分级渲染界面 private void initializeClassBreaksRenderer(int value) { classColorgradComboBox.Items.Clear(); classDataGridView.Rows.Clear(); mClassBreaksRenderers.Clear(); GeoClassBreaksRenderer classBreaksRenderer = (GeoClassBreaksRenderer)mLayer.Renderer; mClassBreaksRenderer = classBreaksRenderer; mClassBreaksRenderers.Add(mClassBreaksRenderer); if (mClassDefaultButton != null) classTableLayoutPanel.Controls.Remove(mClassDefaultButton); Button defaultSymbolButton = GetFillSymbolButton((GeoSimpleFillSymbol)classBreaksRenderer.DefaultSymbol, "class"); mClassDefaultButton = defaultSymbolButton; classTableLayoutPanel.Controls.Add(defaultSymbolButton, 1, 2); for (int i = 0; i < classBreaksRenderer.BreakCount; i++) { GeoSimpleFillSymbol fillSymbol = (GeoSimpleFillSymbol)classBreaksRenderer.GetSymbol(i); Bitmap symbolImage = CreateSimpleFillSymbolImage(fillSymbol); classDataGridView.AddRow(symbolImage, classBreaksRenderer.GetBreakValue(i).ToString("F2")); } CreateClassBreaksRenderers((mLayer.Renderer as GeoClassBreaksRenderer).Field, value); classColorgradComboBox.Items.AddRange(mClassBreaksRenderers.ToArray()); classColorgradComboBox.SelectedIndex = 0; classDataGridView.Refresh(); } // 创建多个分级渲染 private void CreateClassBreaksRenderers(string field, int value) { for (int i = 0; i < mColors.Length; ++i) { mClassBreaksRenderers.Add(CreateClassBreaksRenderer(field, value, mColors[i][0], mColors[i][1])); } } // 创建唯一值渲染 private GeoUniqueValueRenderer CreateUniqueValueRenderer(string field) { try { GeoUniqueValueRenderer sRenderer = new GeoUniqueValueRenderer(); sRenderer.Field = field; int index = mLayer.AttributeFields.FindField(field); List<string> sValues = new List<string>(); int sFeatureCount = mLayer.Features.Count; for (int i = 0; i < sFeatureCount; i++) { string svalue = mLayer.Features.GetItem(i).Attributes.GetItem(index).ToString(); sValues.Add(svalue); } // 去除重复 sValues = sValues.Distinct().ToList(); // 生成符号 int sValueCount = sValues.Count; for (int i = 0; i < sValueCount; i++) { GeoSimpleFillSymbol sSymbol = new GeoSimpleFillSymbol(); sRenderer.AddUniqueValue(sValues[i], sSymbol); } sRenderer.DefaultSymbol = new GeoSimpleFillSymbol(); return sRenderer; } catch (Exception e) { MessageBox.Show("这个字段不能进行唯一值渲染"); return null; } } // 创建多个唯一值渲染供选择 private void CreateUniqueValueRenderers(string field) { for (int i = 0; i < 5; ++i) { mUniqueValueRenderers.Add(CreateUniqueValueRenderer(field)); } } // 建立简单渲染 private GeoSimpleRenderer CreateSimpleRenderer() { GeoSimpleRenderer sRenderer = new GeoSimpleRenderer(); GeoSimpleFillSymbol sSymbol = new GeoSimpleFillSymbol(); sRenderer.Symbol = sSymbol; return sRenderer; } // 更新所有分级渲染的宽度 private void UpdateClassBreaksRenderersOutLine() { for (int i = 0; i < mClassBreaksRenderers.Count; ++i) { GeoClassBreaksRenderer sRenderer = mClassBreaksRenderers[i]; for (int j = 0; j < sRenderer.BreakCount; ++j) { GeoSimpleFillSymbol sSymbol = (sRenderer.GetSymbol(j) as GeoSimpleFillSymbol); GeoSimpleFillSymbol sDefaultSymbol = (mClassBreaksRenderer.DefaultSymbol as GeoSimpleFillSymbol); sSymbol.Outline.Size = sDefaultSymbol.Outline.Size; sSymbol.Outline.Style = sDefaultSymbol.Outline.Style; sSymbol.Outline.Color = sDefaultSymbol.Outline.Color; } } } // 更新所有唯一值渲染宽度 private void UpdateUniqueValueRenderersOutLine() { for (int i = 0; i < mUniqueValueRenderers.Count; ++i) { GeoUniqueValueRenderer sRenderer = mUniqueValueRenderers[i]; for (int j = 0; j < sRenderer.ValueCount; ++j) { GeoSimpleFillSymbol sSymbol = (sRenderer.GetSymbol(j) as GeoSimpleFillSymbol); GeoSimpleFillSymbol sDefaultSymbol = (mUniqueValueRenderer.DefaultSymbol as GeoSimpleFillSymbol); sSymbol.Outline.Size = sDefaultSymbol.Outline.Size; sSymbol.Outline.Style = sDefaultSymbol.Outline.Style; sSymbol.Outline.Color = sDefaultSymbol.Outline.Color; } } } } }
46.00678
167
0.597333
[ "MIT" ]
GIS-design-application/DEETU
Source/Window/LayerAttributesForm/FillSymbolPage.cs
28,298
C#
namespace Peach.Core.Debuggers.DebugEngine.Tlb { using System; public enum __MIDL___MIDL_itf_DbgEng_0001_0077_0056 { DEBUG_DATA_MmModifiedPageListHeadAddr = 0x198 } }
18.454545
56
0.704433
[ "MIT" ]
FXTi/peachfuzz-code
Peach.Core.OS.Windows/Debuggers/DebugEngine/Tlb/__MIDL___MIDL_itf_DbgEng_0001_0077_0056.cs
203
C#
//_______________________________________________________________ // Title : Assembly info for: <Define Assembly Title> // System : Microsoft VisualStudio 2015 / C# // // Copyright (C) 2020 Mariusz Postol LODZ POLAND // +48 608 619 899 // mpostol@cas.eu // https://github.com/mpostol/OPC-UA-OOI //_______________________________________________________________ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("<Define Assembly Title>")] [assembly: AssemblyDescription("DefaultProductName: <Define Assembly Title>")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mariusz Postol")] [assembly: AssemblyProduct("DefaultProductName")] [assembly: AssemblyCopyright("Copyright (C) 2020 Mariusz Postol LODZ POLAND")] [assembly: AssemblyTrademark("Object Oriented Internet")] [assembly: AssemblyCulture("")] [assembly: Guid("<GUID>")] [assembly: AssemblyVersion("0.00.00.*")] [assembly: AssemblyFileVersion("0.00.00")]
39.269231
78
0.77571
[ "MIT" ]
BiancoRoyal/OPC-UA-OOI
CommonResources/T4Definitions/Template.AssemblyInfo.cs
1,023
C#
namespace OrderFulfillment.Core.Models.External.OrderProduction { public class OrderIdentity { public string PartnerCode { get; set; } public string PartnerSubCode { get; set; } public string PartnerRegionCode { get; set; } public string PartnerOrderId { get; set; } } }
29.090909
64
0.65625
[ "MIT" ]
jsquire/Portfolio
src/OrderFulfillment/Core/Models/External/OrderProduction/OrderIdentity.cs
322
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. #nullable disable using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { internal class TaskItemsEnum<T> : IVsEnumTaskItems where T : IVsTaskItem { private readonly T[] _items; private int _next; public TaskItemsEnum(T[] immutableItems) { _items = immutableItems; _next = 0; } int IVsEnumTaskItems.Next(uint celt, IVsTaskItem[] rgelt, uint[] pceltFetched) { checked { int i; for (i = 0; i < celt && _next + i < _items.Length; i++) { rgelt[i] = _items[_next + i]; } _next += i; if (pceltFetched != null) { pceltFetched[0] = (uint)i; } return (i == celt) ? VSConstants.S_OK : VSConstants.S_FALSE; } } int IVsEnumTaskItems.Skip(uint celt) { checked { _next += (int)celt; } return VSConstants.S_OK; } int IVsEnumTaskItems.Reset() { _next = 0; return VSConstants.S_OK; } int IVsEnumTaskItems.Clone(out IVsEnumTaskItems taskItemsEnum) { taskItemsEnum = new TaskItemsEnum<T>(_items); return VSConstants.S_OK; } } }
25.731343
86
0.523782
[ "MIT" ]
333fred/roslyn
src/VisualStudio/Core/Def/Implementation/Utilities/TaskItemsEnum.cs
1,726
C#
namespace MusicHub.DataProcessor { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Xml.Serialization; using Data; using MusicHub.Data.Models; using MusicHub.Data.Models.Enums; using MusicHub.DataProcessor.ImportDtos; using Newtonsoft.Json; public class Deserializer { private const string ErrorMessage = "Invalid data"; private const string SuccessfullyImportedWriter = "Imported {0}"; private const string SuccessfullyImportedProducerWithPhone = "Imported {0} with phone: {1} produces {2} albums"; private const string SuccessfullyImportedProducerWithNoPhone = "Imported {0} with no phone number produces {1} albums"; private const string SuccessfullyImportedSong = "Imported {0} ({1} genre) with duration {2}"; private const string SuccessfullyImportedPerformer = "Imported {0} ({1} songs)"; public static string ImportWriters(MusicHubDbContext context, string jsonString) { var sb = new StringBuilder(); var json = JsonConvert.DeserializeObject<WritersDto[]>(jsonString); var writers = new List<Writer>(); foreach (var dto in json) { if (IsValid(dto)) { var writer = new Writer { Name = dto.Name, Pseudonym = dto.Pseudonym }; writers.Add(writer); sb.AppendLine($"Imported {writer.Name}"); } else { sb.AppendLine(ErrorMessage); continue; } } context.Writers.AddRange(writers); context.SaveChanges(); return sb.ToString().TrimEnd(); } public static string ImportProducersAlbums(MusicHubDbContext context, string jsonString) { var producerDtos = JsonConvert.DeserializeObject<ProducerDto[]>(jsonString); var sb = new StringBuilder(); var producers = new List<Producer>(); foreach (var dto in producerDtos) { var albums = new List<Album>(); bool haveError = false; if (IsValid(dto)) { foreach (var album in dto.Albums) { if (IsValid(album)) { var currentAlbum = new Album { Name = album.Name, ReleaseDate = DateTime.ParseExact(album.ReleaseDate, "dd/MM/yyyy", CultureInfo.InvariantCulture) }; albums.Add(currentAlbum); } else { sb.AppendLine(ErrorMessage); haveError = true; } } } else { sb.AppendLine(ErrorMessage); continue; } if (haveError) { continue; } var producer = new Producer { Name = dto.Name, PhoneNumber = dto.PhoneNumber, Pseudonym = dto.Pseudonym, Albums = albums }; if (string.IsNullOrEmpty(producer.PhoneNumber)) { sb.AppendLine($"Imported {producer.Name} with no phone number produces {producer.Albums.Count} albums"); } else { sb.AppendLine($"Imported {producer.Name} with phone: {producer.PhoneNumber} produces {producer.Albums.Count} albums"); } producers.Add(producer); } context.Producers.AddRange(producers); context.SaveChanges(); return sb.ToString().TrimEnd(); } public static string ImportSongs(MusicHubDbContext context, string xmlString) { var xmlSerializer = new XmlSerializer(typeof(List<SongDto>), new XmlRootAttribute("Songs")); var songDtos = new List<SongDto>(); using (var reader = new StringReader(xmlString)) { songDtos = (List<SongDto>)xmlSerializer.Deserialize(reader); } var sb = new StringBuilder(); var songs = new List<Song>(); foreach (var dto in songDtos) { var currentGenre = Enum.TryParse<Genre>(dto.Genre, out Genre genre); var album = context.Albums.FirstOrDefault(a => a.Id == dto.AlbumId); if (dto.WriterId > 23 || album == null || currentGenre == false) { sb.AppendLine(ErrorMessage); continue; } if (IsValid(dto)) { var song = new Song { Name = dto.Name, Duration = TimeSpan.ParseExact(dto.Duration, "c", CultureInfo.InvariantCulture), CreatedOn = DateTime.ParseExact(dto.CreatedOn, "dd/MM/yyyy", CultureInfo.InvariantCulture), Genre = Enum.Parse<Genre>(dto.Genre), AlbumId = dto.AlbumId, WriterId = dto.WriterId, Price = dto.Price }; songs.Add(song); sb.AppendLine($"Imported {song.Name} ({song.Genre} genre) with duration {song.Duration}"); } else { sb.AppendLine(ErrorMessage); continue; } } context.Songs.AddRange(songs); context.SaveChanges(); return sb.ToString().TrimEnd(); } public static string ImportSongPerformers(MusicHubDbContext context, string xmlString) { var xmlSerializer = new XmlSerializer(typeof(List<SongPerformerDto>), new XmlRootAttribute("Performers")); var dtos = new List<SongPerformerDto>(); using (var reader = new StringReader(xmlString)) { dtos = (List<SongPerformerDto>)xmlSerializer.Deserialize(reader); } var performers = new List<Performer>(); var sb = new StringBuilder(); foreach (var dto in dtos) { var performerSongs = new List<SongPerformer>(); if (IsValid(dto)) { var performer = new Performer { FirstName = dto.FirstName, LastName = dto.LastName, Age = dto.Age, NetWorth = dto.NetWorth, }; bool haveError = false; foreach (var song in dto.PerformerSongs) { var currentSong = context.Songs.FirstOrDefault(s => s.Id == song.SongId); if (currentSong == null) { haveError = true; continue; } var songPerformer = new SongPerformer { Performer = performer, Song = currentSong }; performerSongs.Add(songPerformer); } if (haveError) { sb.AppendLine(ErrorMessage); continue; } performer.PerformerSongs = performerSongs; performers.Add(performer); sb.AppendLine($"Imported {performer.FirstName} ({performer.PerformerSongs.Count} songs)"); } else { sb.AppendLine(ErrorMessage); continue; } } context.Performers.AddRange(performers); context.SaveChanges(); return sb.ToString().TrimEnd(); } private static bool IsValid(object entity) { var validationContext = new ValidationContext(entity); var validationResult = new List<ValidationResult>(); bool isValid = Validator.TryValidateObject(entity, validationContext, validationResult, true); return isValid; } } }
33.505455
138
0.462666
[ "MIT" ]
antoniovelev/Softuni
C#/Entity Framework/01. Model Defition_Skeleton + Datasets/MusicHub/DataProcessor/Deserializer.cs
9,216
C#
using System; using System.Collections.Generic; namespace DemoSite.Models { // Models returned by AccountController actions. public class ExternalLoginViewModel { public string Name { get; set; } public string Url { get; set; } public string State { get; set; } } public class ManageInfoViewModel { public string LocalLoginProvider { get; set; } public string UserName { get; set; } public IEnumerable<UserLoginInfoViewModel> Logins { get; set; } public IEnumerable<ExternalLoginViewModel> ExternalLoginProviders { get; set; } } public class UserInfoViewModel { public string UserName { get; set; } public bool HasRegistered { get; set; } public string LoginProvider { get; set; } } public class UserLoginInfoViewModel { public string LoginProvider { get; set; } public string ProviderKey { get; set; } } }
22.022727
87
0.638803
[ "Apache-2.0" ]
darcythomas/zxcvbn.net
DemoSite/Models/AccountViewModels.cs
971
C#
using System; using System.Threading.Tasks; using d60.Cirqus; using d60.Cirqus.Ntfs.Config; namespace Exchanger { class Program { static void Main(string[] args) { try { new Program().Run(args).Wait(); } catch (AggregateException ex) { foreach (var e in ex.InnerExceptions) { Console.WriteLine("ERROR: " + e.Message); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } async Task Run(string[] args) { var processor = CommandProcessor.With() .EventStore(x => x.UseFiles(".")) .Create(); //add remote //add remote //sync remotes } } }
22.536585
63
0.428571
[ "MIT" ]
asgerhallas/Exchanger
src/Exchanger/Program.cs
926
C#
using System.Data.Entity.ModelConfiguration; namespace BloggerData { public class ArticleConfiguration : EntityTypeConfiguration<Article> { public ArticleConfiguration() { ToTable("Article"); Property(a => a.Title).IsRequired().HasMaxLength(100); Property(a => a.Contents).IsRequired(); Property(a => a.Author).IsRequired().HasMaxLength(50); Property(a => a.URL).IsRequired().HasMaxLength(200); Property(a => a.DateCreated).HasColumnType("datetime2"); Property(a => a.DateEdited).HasColumnType("datetime2"); } } }
33.473684
72
0.61478
[ "Apache-2.0" ]
catalintomescu/OpenFx
OpenDataFx/BloggerData/ArticleConfiguration.cs
638
C#
using System; using System.Runtime.Serialization; namespace Neurocita.Reactive.Pipes { public static class ObservableExtensions { public static IDisposable ToPipeStream<T>(this IObservable<T> observable, string pipeName, IFormatter formatter = null) { return new PipeStreamServerProducer<T>(observable, pipeName, formatter); } public static IDisposable ToPipeStream<T>(this IObservable<T> observable, string serverName, string pipeName, IFormatter formatter = null) { return new PipeStreamClientProducer<T>(observable, serverName, pipeName, formatter); } } }
35.833333
146
0.706977
[ "MIT" ]
neurocita/Reactive
Neurocita.Reactive/Neurocita.Reactive.Pipes/src/ObservableExtensions.cs
647
C#
using System.Threading; using Xunit; namespace STAExamples { public class Samples { [Fact] public static void Fact_OnMTAThread() { Assert.Equal(ApartmentState.MTA, Thread.CurrentThread.GetApartmentState()); } [STAFact] public static void STAFact_OnSTAThread() { Assert.Equal(ApartmentState.STA, Thread.CurrentThread.GetApartmentState()); } [STATheory] [InlineData(0)] public static void STATheory_OnSTAThread(int unused) { Assert.Equal(ApartmentState.STA, Thread.CurrentThread.GetApartmentState()); } } }
23.607143
87
0.611195
[ "Apache-2.0" ]
AArnott/xunit.samples
STAExamples/Samples.cs
663
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.Web.V20201001.Outputs { [OutputType] public sealed class SkuCapacityResponse { /// <summary> /// Default number of workers for this App Service plan SKU. /// </summary> public readonly int? Default; /// <summary> /// Maximum number of workers for this App Service plan SKU. /// </summary> public readonly int? Maximum; /// <summary> /// Minimum number of workers for this App Service plan SKU. /// </summary> public readonly int? Minimum; /// <summary> /// Available scale configurations for an App Service plan. /// </summary> public readonly string? ScaleType; [OutputConstructor] private SkuCapacityResponse( int? @default, int? maximum, int? minimum, string? scaleType) { Default = @default; Maximum = maximum; Minimum = minimum; ScaleType = scaleType; } } }
27.38
81
0.589481
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Web/V20201001/Outputs/SkuCapacityResponse.cs
1,369
C#
using System; using System.Linq; using Xunit; namespace Nerven.CommandLineParser.Tests { public static class TestHelper { public static void TestCommandLineParser(ICommandLineParser parser, CommandLineSplitter splitter, string line, CommandLineItem[] expectedItems) { var _commandLine = splitter.ParseString(line); var _actualItems = parser.ParseCommandLine(_commandLine); for (var _i = 0; _i < expectedItems.Length && _i < _actualItems.Count; _i++) { Assert.Equal(expectedItems[_i].ToString(), _actualItems[_i].ToString(), StringComparer.Ordinal); Assert.Equal(expectedItems[_i], _actualItems[_i]); } Assert.Equal(expectedItems.Length, _actualItems.Count); Assert.True(expectedItems.SequenceEqual(_actualItems)); Assert.Equal(_commandLine.Value, splitter.ParseString(_commandLine.Value).Value); } public static void CommandLineIsSplittedLikeWin32Does(string line, CommandLineSplitter parser) { var _commandLine = parser.ParseString(line); var _actualArgs = _commandLine.GetArgs(); var _expectedArgs = Win32CommandLineToArgvW.Split(line); Assert.True(_commandLine.Equals(_expectedArgs)); Assert.False(_commandLine.Equals(_expectedArgs.Concat(new[] { string.Empty }).ToArray())); Assert.Equal(string.Join(Environment.NewLine, _expectedArgs), string.Join(Environment.NewLine, _actualArgs)); Assert.Equal(_expectedArgs.Length, _commandLine.Parts.Count); for (var _i = 0; _i < _expectedArgs.Length; _i++) { Assert.Equal(_i, _commandLine.Parts[_i].Index); Assert.Equal(_expectedArgs[_i], _commandLine.Parts[_i].Value); Assert.True(_commandLine.Parts[_i].Equals(_expectedArgs[_i])); } Assert.Equal(_commandLine.Value, parser.ParseString(_commandLine.Value).Value); } } }
43.425532
151
0.654581
[ "MIT" ]
Nerven/CommandLineParser
tests/Nerven.CommandLineParser.Tests/TestHelper.cs
2,043
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 elasticache-2015-02-02.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.ElastiCache.Model { ///<summary> /// ElastiCache exception /// </summary> public class CacheSubnetGroupNotFoundException : AmazonElastiCacheException { /// <summary> /// Constructs a new CacheSubnetGroupNotFoundException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public CacheSubnetGroupNotFoundException(string message) : base(message) {} public CacheSubnetGroupNotFoundException(string message, Exception innerException) : base(message, innerException) {} public CacheSubnetGroupNotFoundException(Exception innerException) : base(innerException) {} public CacheSubnetGroupNotFoundException(string message, Exception innerException, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, RequestId, statusCode) {} public CacheSubnetGroupNotFoundException(string message, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, RequestId, statusCode) {} } }
39.54717
175
0.694179
[ "Apache-2.0" ]
samritchie/aws-sdk-net
AWSSDK_DotNet35/Amazon.ElastiCache/Model/CacheSubnetGroupNotFoundException.cs
2,096
C#
namespace TreniniDotNet.Application.Collecting.Shops { public static class NewShopAddressInput { public static readonly ShopAddressInput Empty = With(); public static ShopAddressInput With( string line1 = null, string line2 = null, string city = null, string region = null, string postalCode = null, string country = null) => new ShopAddressInput { Line1 = line1, Line2 = line2, City = city, Region = region, PostalCode = postalCode, Country = country }; } }
29.521739
63
0.516937
[ "MIT" ]
CarloMicieli/TreniniDotNet
Tests/Application.UnitTests/Collecting/Shops/NewShopAddressInput.cs
679
C#
using System; using System.Runtime.ExceptionServices; using System.Threading.Tasks; namespace AdventOfCode.Solutions { public class Day10 { public static async Task Problem1() { var data = await Data.GetDataLines(); bool [,] space = new bool[data.Length,data[0].Length]; IntCo2 best = MostSighted(data, space, out int mostSighted); Console.WriteLine($"Best location ({best.X}, {best.Y}) can sight {mostSighted} asteroids"); } public static async Task Problem2() { var data = await Data.GetDataLines(); bool [,] space = new bool[data.Length,data[0].Length]; IntCo2 center = MostSighted(data, space, out _); int cx = space.GetUpperBound(0) + 1; int cy = space.GetUpperBound(1) + 1; double?[,] angles = new double?[space.GetUpperBound(0) + 1, space.GetUpperBound(1) + 1]; IntCo2? zap; for (int i = 0; i < 199; i++) { zap = GetAsteroid(angles); if (!zap.HasValue) { CalculateAngles(space, center, angles); } zap = GetAsteroid(angles); space[zap.Value.X, zap.Value.Y] = false; angles[zap.Value.X, zap.Value.Y] = null; } zap = GetAsteroid(angles); if (!zap.HasValue) CalculateAngles(space, center, angles); zap = GetAsteroid(angles); Console.WriteLine($"200th zap at ({zap.Value.X}, {zap.Value.Y}) => {zap.Value.X * 100 + zap.Value.Y}"); } private static void CalculateAngles(bool[,] space, IntCo2 center, double?[,] angles) { int cx = space.GetUpperBound(0) + 1; int cy = space.GetUpperBound(1) + 1; for (int dx = -cx; dx < cx; dx++) { for (int dy = -cy; dy < cy; dy++) { if (FancyMath.Gcd(Math.Abs(dx), Math.Abs(dy)) != 1) continue; for (int i = 1; i < Math.Max(cx, cy); i++) { int tx = center.X + dx * i; int ty = center.Y + dy * i; if (tx < 0 || tx >= cx || ty < 0 || ty >= cy) break; if (space[tx, ty]) { angles[tx, ty] = (Math.Atan2(dy, dx) - Math.Atan2(-1, 0) + 2 * Math.PI) % (2 * Math.PI); break; } } } } } private static IntCo2? GetAsteroid(double?[,] angles) { double first = 1000; IntCo2? best = null; for (int x = 0; x <= angles.GetUpperBound(0); x++) { for (int y = 0; y <= angles.GetUpperBound(1); y++) { if (angles[x, y] < first) { first = angles[x, y].Value; best = new (x, y); } } } return best; } private static IntCo2 MostSighted(string[] data, bool[,] space, out int mostSighted) { int cy = data.Length; int cx = data[0].Length; for (int y = 0; y < cy; y++) { string line = data[y]; for (int x = 0; x < cx; x++) { space[x, y] = line[x] == '#'; } } mostSighted = 0; IntCo2 best = new (0, 0); for (int y = 0; y < cy; y++) { for (int x = 0; x < cx; x++) { int sightable = 0; for (int dx = -cx; dx < cx; dx++) { for (int dy = -cy; dy < cy; dy++) { if (FancyMath.Gcd(Math.Abs(dx), Math.Abs(dy)) != 1) continue; for (int i = 1; i < Math.Max(cx, cy); i++) { int tx = x + dx * i; int ty = y + dy * i; if (tx < 0 || tx >= cx || ty < 0 || ty >= cy) break; if (space[tx, ty]) { sightable++; break; } } } } if (sightable > mostSighted) { mostSighted = sightable; best = new (x, y); } } } return best; } } }
33.302632
116
0.358751
[ "Unlicense" ]
ChadNedzlek/advent-of-code-2019
Solutions/Day10.cs
5,064
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Unity.Entities; using Unity.Transforms; using Unity.Mathematics; public class MoveForwardSystem : ComponentSystem { struct Group { public readonly int Length; public ComponentDataArray<Position> positionData; public ComponentDataArray<Rotation> rotationData; } [Inject] Group group; protected override void OnUpdate() { for (int i = 0; i < group.Length; i++) { float3 position = group.positionData[i].Value; position += Time.deltaTime * 20 * math.forward(group.rotationData[i].Value); group.positionData[i] = new Position { Value = position }; } } }
27.428571
89
0.641927
[ "Apache-2.0" ]
FantasyTianyu/UnityECSDemo
Assets/Scripts/ECS/System/MoveForwardSystem.cs
770
C#