content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Windows.Media; namespace HL7Comparer { [Flags] public enum TextMarkerTypes { /// <summary> /// Use no marker /// </summary> None = 0x0000, /// <summary> /// Use squiggly underline marker /// </summary> SquigglyUnderline = 0x001, /// <summary> /// Normal underline. /// </summary> NormalUnderline = 0x002, /// <summary> /// Dotted underline. /// </summary> DottedUnderline = 0x004, Rectangle = 0x008 } public interface ITextMarkerService { void AddMarker(int offset, int length, string message); void Clear(); } }
21.264706
63
0.524205
[ "MIT" ]
julien-lebot/HL7-Comparer
HL7Comparer/ITextMarkerService.cs
725
C#
namespace NMetrics.Reporting { /// <summary> /// A tag interface to indicate that a class is a reporter /// </summary> public interface IReporter { } }
18.7
63
0.57754
[ "MIT" ]
thattolleyguy/nmetrics
NMetrics.Core/Reporting/IReporter.cs
189
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Snake { /// <summary> /// An x-y coordinate pair representing a location point /// </summary> class Point { public int X{get; set;} public int Y{get; set;} /// <summary> /// Object constructor /// </summary> /// <param name="X">X coordinate of the point</param> /// <param name="Y">Y coordinate of the point</param> public Point(int X,int Y) { this.X = X; this.Y = Y; } } }
21.758621
61
0.543582
[ "MIT" ]
Wisdou/Snake
Snake/Point.cs
633
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace Memberships.Entities { [Table("Section")] public class Section { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [MaxLength(255)] public string Title { get; set; } } }
22.095238
61
0.69181
[ "MIT" ]
atk0dev/MembershipsApp
Memberships/Memberships/Entities/Section.cs
466
C#
using System; using System.Threading.Tasks; namespace Ivvy.API { /// <summary> /// ApiClientEvents provides a default implementation of IApiClientEvents which does nothing. /// </summary> public class ApiClientEvents : IApiClientEvents { public ApiClientEvents() { OnAfterApiCalled = details => Task.CompletedTask; } public Func<ApiCallDetails, Task> OnAfterApiCalled { get; set; } public virtual Task AfterApiCalledAsync(ApiCallDetails details) => OnAfterApiCalled(details); } }
25.478261
101
0.645051
[ "MIT" ]
MihailSotirov/ivvy-sdk-net
src/ApiClientEvents.cs
586
C#
using System; using System.Globalization; using Xamarin.CommunityToolkit.Extensions; using Xamarin.Forms; namespace Xamarin.CommunityToolkit.Converters { /// <summary> /// Converts text (string, char) to certain case. /// </summary> [ContentProperty(nameof(Type))] public class TextCaseConverter : ValueConverterExtension, IValueConverter { /// <summary> /// The desired text case that the text should be converted to. /// </summary> public TextCaseType Type { get; set; } /// <summary> /// Converts text (string, char) to certain case. /// </summary> /// <param name="value">The text to convert.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The desired text case that the text should be converted to (TextCaseType enum value).</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>The lowercase text representation.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => value == null || value is string || value is char ? Convert(value?.ToString(), parameter) : throw new ArgumentException("Value is neither a string nor a char", nameof(value)); public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException(); object Convert(string value, object parameter) => GetParameter(parameter) switch { TextCaseType.Lower => value?.ToLowerInvariant(), TextCaseType.Upper => value?.ToUpperInvariant(), _ => value }; TextCaseType GetParameter(object parameter) => parameter == null ? Type : parameter switch { TextCaseType type => type, string typeString => Enum.TryParse(typeString, out TextCaseType result) ? result : throw new ArgumentException("Cannot parse text case from the string", nameof(parameter)), int typeInt => Enum.IsDefined(typeof(TextCaseType), typeInt) ? (TextCaseType)typeInt : throw new ArgumentException("Cannot convert integer to text case enum value", nameof(parameter)), _ => TextCaseType.None, }; } }
37.5
123
0.709885
[ "MIT" ]
AbuMandour/XamarinCommunityToolkit
XamarinCommunityToolkit/Converters/TextCaseConverter.shared.cs
2,177
C#
using System.Collections.Generic; using NonogramNet.Lib.Model; namespace NonogramNet.Lib.Test { using System.Net.NetworkInformation; public static class BoardSamples { /* * XXX_X * XX_XX * X_X_X * X___X * _____ */ public static IBoard Board1 = Board.MakeBoard( RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {4}, new List<int> {2}, new List<int> {1, 1}, new List<int> {1}, new List<int> {4} }), RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {3, 1}, new List<int> {2, 2}, new List<int> {1, 1, 1}, new List<int> {1, 1}, new List<int>() }) ); /* * _XX * _X_ * X_X */ public static IBoard Board2 = Board.MakeBoard( RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {1}, new List<int> {2}, new List<int> {1, 1} }), RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {2}, new List<int> {1}, new List<int> {1, 1} }) ); /* * XXX * _XX * X_X */ public static IBoard Board3 = Board.MakeBoard( RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {1,1}, new List<int> {2}, new List<int> {3} }), RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {3}, new List<int> {2}, new List<int> {1, 1} }) ); /* * X_X * __X * X__ */ public static IBoard Board4 = Board.MakeBoard( RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {1,1}, new List<int> {}, new List<int> {2} }), RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {1, 1}, new List<int> {1}, new List<int> {1} }) ); /* * X__ * _XX * X__ */ public static IBoard Board5 = Board.MakeBoard( RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {1,1}, new List<int> {1}, new List<int> {1} }), RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {1}, new List<int> {2}, new List<int> {1} }) ); /* */ public static IBoard Board6 = Board.MakeBoard( RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {3,3}, new List<int> {1,1,1,1,2}, new List<int> {1,1,1,1,3}, new List<int> {1,1,3,3}, new List<int> {1,1,3,3}, new List<int> {1,1,1,1,3}, new List<int> {1,1,1,1,2}, new List<int> {3,3}, }), RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {6}, new List<int> {1,1}, new List<int> {8}, new List<int> {1,1}, new List<int> {1,1}, new List<int> {4}, new List<int> {2}, new List<int> {2}, new List<int> {1,1}, new List<int> {1,1}, new List<int> {1,1}, new List<int> {1,4,1}, new List<int> {8}, new List<int> {6}, }) ); /* ___XX * _____ * _____ * X____ * X____ * */ public static IBoard Board7 = Board.MakeBoard( RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {2}, new List<int>(), new List<int>(), new List<int> {1}, new List<int> {1}}), RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {2}, new List<int>(), new List<int>(), new List<int> {1}, new List<int> {1}}) ); /* ____X * ____X * _____ * _____ * XX___ * */ public static IBoard Board7_ManualFlipped = Board.MakeBoard( RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {1}, new List<int> {1}, new List<int> {}, new List<int> {}, new List<int> {2}}), RulesMatrix.MakeRulesMatrix(new List<List<int>> { new List<int> {1}, new List<int> {1}, new List<int> {}, new List<int> {}, new List<int> {2}}) ); } }
28
68
0.3831
[ "MIT" ]
PedersenThomas/NonogramNet.Lib
NonogramNet.Lib.Test/BoardSamples.cs
5,434
C#
using JWTSimpleServer; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using System; using System.Collections.Generic; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Builder; using System.Linq; using JWTSimpleServer.Abstractions; namespace FunctionalTests { public class TestServerBuilder { private IAuthenticationProvider authProvider; private bool _useInMemoryStore = false; public TestServerBuilder WithSuccessAuthentication() { authProvider = new FakeSuccessAuthenticationProvider(); return this; } public TestServerBuilder WithInMemoryStore() { _useInMemoryStore = true; return this; } public TestServer Build() { var webhostBuilder = new WebHostBuilder() .ConfigureServices(services => { var serviceCollection = services.AddJwtSimpleServer(options => { options.IssuerSigningKey = Constants.DefaultSigningKey; }) .AddTransient(ctx => { return authProvider; }); if (_useInMemoryStore) { serviceCollection.AddJwtInMemoryRefreshTokenStore(); } serviceCollection.AddMvcCore(options => options.EnableEndpointRouting = false) .AddAuthorization(); }).Configure(app => { app.UseJwtSimpleServer(setup => { setup.IssuerSigningKey = Constants.DefaultSigningKey; }) .UseMvc(); }); return new TestServer(webhostBuilder); } internal class FakeSuccessAuthenticationProvider : IAuthenticationProvider { public Task ValidateClientAuthentication(JwtSimpleServerContext context) { context.Success(Enumerable.Empty<Claim>().ToList()); return Task.CompletedTask; } } } }
30.92
98
0.561018
[ "Apache-2.0" ]
cdorde/JWTSimpleServer
test/FunctionalTests/TestServerBuilder.cs
2,321
C#
using System; using System.Text; namespace Networking.Files.PcapNG { public partial class NameResolutionBlock { /// <summary> /// Name Resolution Block Record /// </summary> public partial class Record : Octets { /// <summary> /// Type /// </summary> public RecordType Type { get { return (RecordType)base.GetUInt16(Layout.RecordTypeBegin); } } /// <summary> /// Value Length /// </summary> public UInt16 ValueLength { get { return base.GetUInt16(Layout.RecordValueBegin); } } /// <summary> /// IP /// </summary> public IPAddress IP { get { var ipAddressLength = GetIPAddressLength(); if (ipAddressLength == 0) { return null; } return new IPAddress { Bytes = GetBytes(Layout.RecordHeaderLength, ipAddressLength) }; } } /// <summary> /// Host /// </summary> public String Host { get { var ipAddressLength = GetIPAddressLength(); if (ipAddressLength == 0) { return null; } var hostBytesBegin = Layout.RecordHeaderLength + ipAddressLength; var hostBytesEnd = ValueLength - ipAddressLength; var hostBytes = GetBytes(hostBytesBegin, hostBytesEnd).ToArray(); return Encoding.UTF8.GetString(hostBytes).TrimEnd('\0'); } } private Int32 GetIPAddressLength() { switch (Type) { case RecordType.IPv4: return IPAddress.Layout.V4Length; case RecordType.IPv6: return IPAddress.Layout.V6Length; default: return 0; } } } } }
28
85
0.402521
[ "MIT" ]
heshang233/networking
src/networking.files/PcapNG/NameResolutionBlock.Record.cs
2,380
C#
// <copyright file="TestCaseHistoryEntryController.cs" company="Automate The Planet Ltd."> // Copyright 2020 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using Meissa.Model; using Meissa.Server.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace Meissa.API.Controllers { [Route("api/testcaseHistoryEntries")] public class TestCaseHistoryEntryController : Controller { private readonly ILogger<TestCaseHistoryEntryController> _logger; private readonly MeissaRepository _meissaRepository; public TestCaseHistoryEntryController(ILogger<TestCaseHistoryEntryController> logger, MeissaRepository repository) { _logger = logger; _meissaRepository = repository; } [HttpGet("id")] public async Task<IActionResult> GetTestCaseHistoryEntry([FromBody] int id) { try { var testCaseHistoryEntry = await _meissaRepository.GetByIdAsync<TestCaseHistoryEntry>(id).ConfigureAwait(false); if (testCaseHistoryEntry == null) { _logger.LogInformation($"TestCaseHistoryEntry with id {id} wasn't found."); return NotFound(); } var testCaseHistoryEntryDto = Mapper.Map<TestCaseHistoryEntryDto>(testCaseHistoryEntry); return Ok(testCaseHistoryEntryDto); } catch (Exception ex) { _logger.LogCritical($"Exception while getting test run with id {id}.", ex); return StatusCode(500, "A problem happened while handling your request."); } } [HttpGet] public async Task<IActionResult> GetTestCaseHistoryEntrys() { try { var testCaseHistoryEntrys = await _meissaRepository.GetAllQueryWithRefreshAsync<TestCaseHistoryEntry>().ConfigureAwait(false); var testCaseHistoryEntryDtos = Mapper.Map<IEnumerable<TestCaseHistoryEntryDto>>(testCaseHistoryEntrys); return Ok(testCaseHistoryEntryDtos); } catch (Exception ex) { _logger.LogCritical("Exception while getting test runs.", ex); return StatusCode(500, "A problem happened while handling your request."); } } [HttpPost] public async Task<IActionResult> CreateTestCaseHistoryEntryAsync([FromBody] TestCaseHistoryEntryDto testCaseHistoryEntryDto) { if (testCaseHistoryEntryDto == null) { return BadRequest(); } if (!ModelState.IsValid) { return BadRequest(ModelState); } var testCaseHistoryEntry = Mapper.Map<TestCaseHistoryEntry>(testCaseHistoryEntryDto); var result = await _meissaRepository.InsertWithSaveAsync(testCaseHistoryEntry).ConfigureAwait(false); var resultDto = Mapper.Map<TestCaseHistoryEntryDto>(result); return Ok(resultDto); } [HttpPut] public async Task<IActionResult> UpdateTestCaseHistoryEntryAsync([FromBody] KeyValuePair<int, TestCaseHistoryEntryDto> updateObject) { if (updateObject.Value == null) { return BadRequest(); } if (!ModelState.IsValid) { return BadRequest(ModelState); } var entityToBeUpdated = await _meissaRepository.GetByIdAsync<TestCaseHistoryEntry>(updateObject.Key).ConfigureAwait(false); if (entityToBeUpdated == null) { return NotFound(); } entityToBeUpdated = Mapper.Map(updateObject.Value, entityToBeUpdated); await _meissaRepository.UpdateWithSaveAsync(entityToBeUpdated).ConfigureAwait(false); return NoContent(); } [HttpDelete] public async Task<IActionResult> DeleteTestCaseHistoryEntryAsync([FromBody] int id) { var entityToBeRemoved = await _meissaRepository.GetByIdAsync<TestCaseHistoryEntry>(id).ConfigureAwait(false); if (entityToBeRemoved == null) { return NotFound(); } await _meissaRepository.DeleteWithSaveAsync(entityToBeRemoved).ConfigureAwait(false); return NoContent(); } } }
37.630435
142
0.637974
[ "Apache-2.0" ]
AutomateThePlanet/Meissa
Meissa.Server/Controllers/TestCaseHistoryEntryController.cs
5,195
C#
using FullControls.Common; using System; using System.Collections.Specialized; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Markup; namespace FullControls.Controls { /// <summary> /// Represents a control that contains a stacked list of items. /// Each item can be <b>expanded</b> or <b>collapsed</b> to reveal the content associated with that item. /// </summary> [TemplatePart(Name = PartContentHost, Type = typeof(Decorator))] [DefaultEvent(nameof(ItemIsExpandedChanged))] [ContentProperty(nameof(Items))] [DefaultProperty(nameof(Items))] public class Accordion : Control { private readonly ItemsControl itemsControl; /// <summary> /// ContentHost template part. /// </summary> protected const string PartContentHost = "PART_ContentHost"; /// <summary> /// Gets or sets a collection of <see cref="AccordionItem"/> to display inside the <see cref="Accordion"/>. /// </summary> public AccordionItemCollection Items { get => (AccordionItemCollection)GetValue(ItemsProperty); set => SetValue(ItemsProperty, value); } /// <summary> /// Identifies the <see cref="Items"/> dependency property. /// </summary> public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(nameof(Items), typeof(AccordionItemCollection), typeof(Accordion), new PropertyMetadata(null, new PropertyChangedCallback((d, e) => ((Accordion)d).OnItemsInstanceChanged((AccordionItemCollection)e.NewValue, (AccordionItemCollection)e.OldValue)))); /// <summary> /// Gets the number of elements actually contained inside the <see cref="Accordion"/>. /// </summary> public int ItemsCount => Items != null ? Items.Count : 0; /// <summary> /// Gets a value indicating if the <see cref="Accordion"/> has items. /// </summary> public bool HasItems => ItemsCount > 0; /// <summary> /// Occurs when in an item <see cref="AccordionItem.IsExpanded"/> is changed. /// </summary> public event EventHandler<ItemExpandedChangedEventArgs> ItemIsExpandedChanged; static Accordion() { DefaultStyleKeyProperty.OverrideMetadata(typeof(Accordion), new FrameworkPropertyMetadata(typeof(Accordion))); IsEnabledProperty.OverrideMetadata(typeof(Accordion), new FrameworkPropertyMetadata(new PropertyChangedCallback((d, e) => ((Accordion)d).OnEnabledChanged((bool)e.NewValue)))); } /// <summary> /// Initializes a new instance of <see cref="Accordion"/>. /// </summary> public Accordion() : base() { Loaded += (o, e) => OnLoaded(e); itemsControl = new ItemsControl(); Items = new(); } /// <summary> /// Reset the <see cref="Accordion"/> by setting <see cref="Items"/> to a new instance. /// </summary> public void Reset() => Items = new(); /// <summary> /// Clear the <see cref="Accordion"/> by removing all the <see cref="AccordionItem"/> from <see cref="Items"/>, /// and setting <see cref="Items"/> to a new instance. /// </summary> public void Clear() { Items.Clear(); Reset(); } /// <inheritdoc/> public override void OnApplyTemplate() { base.OnApplyTemplate(); Decorator contentHost = (Decorator)Template.FindName(PartContentHost, this); if (contentHost != null) contentHost.Child = itemsControl; } /// <summary> /// Called when the element is laid out, rendered, and ready for interaction. /// </summary> /// <param name="e">Event data.</param> protected virtual void OnLoaded(RoutedEventArgs e) { } /// <summary> /// Called when the <see cref="UIElement.IsEnabled"/> is changed. /// </summary> /// <param name="enabledState">Actual state of <see cref="UIElement.IsEnabled"/>.</param> protected virtual void OnEnabledChanged(bool enabledState) { } /// <summary> /// Called when in an item <see cref="AccordionItem.IsExpanded"/> is changed. /// </summary> /// <param name="e">Event data.</param> protected virtual void OnItemExpandedChanged(ItemExpandedChangedEventArgs e) => ItemIsExpandedChanged?.Invoke(this, e); /// <summary> /// Called when the instance of the <see cref="Items"/> collection is changed. /// </summary> /// <param name="newItems">The new <see cref="Items"/> collection.</param> /// <param name="oldItems">The old <see cref="Items"/> collection.</param> protected virtual void OnItemsInstanceChanged(AccordionItemCollection newItems, AccordionItemCollection oldItems) { if (oldItems != null) oldItems.CollectionChanged -= OnItemsChanged; if (newItems != null) newItems.CollectionChanged += OnItemsChanged; ReloadItems(); } /// <summary> /// Called when the <see cref="Items"/> collection is internally changed. /// </summary> /// <param name="e">Event data.</param> protected virtual void OnItemsChanged(NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: itemsControl.Items.Insert(e.NewStartingIndex, Items[e.NewStartingIndex]); SetExpandedChangedHandler(e.NewStartingIndex); break; case NotifyCollectionChangedAction.Remove: RemoveExpandedChangedHandler(e.OldStartingIndex); itemsControl.Items.RemoveAt(e.OldStartingIndex); break; case NotifyCollectionChangedAction.Replace: RemoveExpandedChangedHandler(e.OldStartingIndex); itemsControl.Items[e.OldStartingIndex] = Items[e.NewStartingIndex]; SetExpandedChangedHandler(e.NewStartingIndex); break; case NotifyCollectionChangedAction.Move: itemsControl.Items.RemoveAt(e.OldStartingIndex); itemsControl.Items.Insert(e.NewStartingIndex, Items[e.NewStartingIndex]); break; case NotifyCollectionChangedAction.Reset: ReloadItems(); break; default: ReloadItems(); break; } } /// <summary> /// Reloads all the <see cref="Items"/>. /// </summary> private void ReloadItems() { RemoveExpandedChangedHandler(0, itemsControl.Items.Count - 1); itemsControl.Items.Clear(); if (Items != null) { foreach (AccordionItem item in Items) itemsControl.Items.Add(item); SetExpandedChangedHandler(0, itemsControl.Items.Count - 1); } } #region ExpandedChangedHandler setters /// <summary> /// Set the ExpandedChanged handler to an item. /// </summary> /// <param name="index">Item index.</param> private void SetExpandedChangedHandler(int index) { if (itemsControl.Items[index] != null) { ((AccordionItem)itemsControl.Items[index]).IsExpandedChanged -= OnItemExpandedChanged; ((AccordionItem)itemsControl.Items[index]).IsExpandedChanged += OnItemExpandedChanged; } } /// <summary> /// Remove the ExpandedChanged handler to some items. /// </summary> /// <param name="startIndex">First item index.</param> /// <param name="endIndex">Last item index.</param> private void SetExpandedChangedHandler(int startIndex, int endIndex) { for (int i = startIndex; i <= endIndex; i++) SetExpandedChangedHandler(i); } /// <summary> /// Remove the ExpandedChanged handler to an item. /// </summary> /// <param name="index">Item index.</param> private void RemoveExpandedChangedHandler(int index) { if (itemsControl.Items[index] != null) { ((AccordionItem)itemsControl.Items[index]).IsExpandedChanged -= OnItemExpandedChanged; } } /// <summary> /// Remove the ExpandedChanged handler to some items. /// </summary> /// <param name="startIndex">First item index.</param> /// <param name="endIndex">Last item index.</param> private void RemoveExpandedChangedHandler(int startIndex, int endIndex) { for (int i = startIndex; i <= endIndex; i++) RemoveExpandedChangedHandler(i); } #endregion #region EventHandlers private void OnItemsChanged(object s, NotifyCollectionChangedEventArgs e) => OnItemsChanged(e); private void OnItemExpandedChanged(object s, ItemExpandedChangedEventArgs e) => OnItemExpandedChanged(e); #endregion } }
39.479167
138
0.589974
[ "MIT" ]
devpelux/fullcontrols
FullControls/Controls/Accordion.cs
9,477
C#
namespace Penshell.Core { using System; using System.CommandLine; using System.CommandLine.Invocation; /// <summary> /// Abstract base class for all penshell commands. /// </summary> public abstract class PenshellCommand : Command { /// <summary> /// Initializes a new instance of the <see cref="PenshellCommand"/> class. /// </summary> /// <param name="console">The <see cref="IPenshellConsole"/> instance.</param> /// <param name="name">The name.</param> /// <param name="description">The desciption.</param> protected PenshellCommand(IPenshellConsole console, string name, string? description = null) : base(name, description) { this.Console = console ?? throw new ArgumentNullException(nameof(console)); this.Handler = this.CreateCommandHandler(); } /// <summary> /// Gets the <see cref="IPenshellConsole"/> instance. /// </summary> public IPenshellConsole Console { get; } /// <summary> /// Creates the command handler. /// </summary> /// <returns>The <see cref="ICommandHandler"/> instance.</returns> protected abstract ICommandHandler CreateCommandHandler(); } }
34.864865
100
0.604651
[ "MIT" ]
IForgeDe/Penshell
src/Penshell.Core/PenshellCommand.cs
1,292
C#
using UnityEngine; using System.Collections; using UnityEngine.UI; public class modifyModeText : MonoBehaviour { Text modeText; // Use this for initialization void Start () { modeText = gameObject.GetComponent<Text> (); modeText.text = "Current Selection is: " + GameManager.instance.selectMode; } // Update is called once per frame void Update () {//used to update and display to the user their currently selected modeText.text = "Current Selection is: " + GameManager.instance.selectMode; } }
27.105263
82
0.737864
[ "MIT" ]
arisonu123/FortressDefender
ATaylor_UATanksV1/FortressDefender/Assets/Scripts/UIScripts/modifyModeText.cs
517
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AcrHelloworld { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.740741
70
0.646043
[ "MIT" ]
bellstar/dotnetcore-build-container-demo
AcrHelloworld/Program.cs
695
C#
namespace gps_service.Core { using System; using Models; public static class Geo { public static float Distance(GeoPosition pos1, GeoPosition pos2) { var rad = 6372795; var llat1 = pos1.Latitude; var llong1 = pos1.Longitude; var llat2 = pos2.Latitude; var llong2 = pos2.Longitude; var lat1 = llat1 * MathF.PI / 180f; var lat2 = llat2 * MathF.PI / 180f; var long1 = llong1 * MathF.PI / 180f; var long2 = llong2 * MathF.PI / 180f; var cl1 = MathF.Cos(lat1); var cl2 = MathF.Cos(lat2); var sl1 = MathF.Sin(lat1); var sl2 = MathF.Sin(lat2); var delta = long2 - long1; var cdelta = MathF.Cos(delta); var sdelta = MathF.Sin(delta); var y = MathF.Sqrt(MathF.Pow(cl2 * sdelta, y: 2) + MathF.Pow(cl1 * sl2 - sl1 * cl2 * cdelta, y: 2)); var x = sl1 * sl2 + cl1 * cl2 * cdelta; var ad = MathF.Atan2(y, x); var dist = ad * rad; return dist; } } }
29.95122
113
0.463355
[ "MIT" ]
0xF6/ASPCoreGPSService
gps-service/Core/Geo.cs
1,230
C#
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; using System.Text; using Amazon.Runtime; using Amazon.S3.Util; using Amazon.Util; using System.Globalization; using Amazon.S3.Model.Internal.MarshallTransformations; using Amazon.S3; namespace Amazon.S3.Model { /// <summary> /// Returns information about the GetObject response and response metadata. /// </summary> public partial class GetObjectResponse : StreamResponse { private string deleteMarker; private string acceptRanges; private Expiration expiration; private DateTime? restoreExpiration; private bool restoreInProgress; private DateTime? lastModified; private string eTag; private int? missingMeta; private string versionId; private DateTime? expires; private ObjectLockLegalHoldStatus objectLockLegalHoldStatus; private ObjectLockMode objectLockMode; private DateTime? objectLockRetainUntilDate; private string websiteRedirectLocation; private ServerSideEncryptionMethod serverSideEncryption; private ServerSideEncryptionCustomerMethod serverSideEncryptionCustomerMethod; private string serverSideEncryptionKeyManagementServiceKeyId; private HeadersCollection headersCollection = new HeadersCollection(); private MetadataCollection metadataCollection = new MetadataCollection(); private ReplicationStatus replicationStatus; private int? partsCount; private S3StorageClass storageClass; private RequestCharged requestCharged; private int? tagCount; private string bucketName; private string key; /// <summary> /// Flag which returns true if the Expires property has been unmarshalled /// from the raw value or set by user code. /// </summary> private bool isExpiresUnmarshalled; internal string RawExpires { get; set; } /// <summary> /// Gets and sets the BucketName property. /// </summary> public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } /// <summary> /// Gets and sets the Key property. /// </summary> public string Key { get { return this.key; } set { this.key = value; } } /// <summary> /// Specifies whether the object retrieved was (true) or was not (false) a Delete Marker. If false, this response header does not appear in the /// response. /// /// </summary> public string DeleteMarker { get { return this.deleteMarker; } set { this.deleteMarker = value; } } // Check to see if DeleteMarker property is set internal bool IsSetDeleteMarker() { return this.deleteMarker != null; } /// <summary> /// The collection of headers for the request. /// </summary> public HeadersCollection Headers { get { if (this.headersCollection == null) this.headersCollection = new HeadersCollection(); return this.headersCollection; } } /// <summary> /// The collection of meta data for the request. /// </summary> public MetadataCollection Metadata { get { if (this.metadataCollection == null) this.metadataCollection = new MetadataCollection(); return this.metadataCollection; } } /// <summary> /// Gets and sets the AcceptRanges. /// </summary> public string AcceptRanges { get { return this.acceptRanges; } set { this.acceptRanges = value; } } // Check to see if AcceptRanges property is set internal bool IsSetAcceptRanges() { return this.acceptRanges != null; } /// <summary> /// Gets and sets the Expiration property. /// Specifies the expiration date for the object and the /// rule governing the expiration. /// Is null if expiration is not applicable. /// </summary> public Expiration Expiration { get { return this.expiration; } set { this.expiration = value; } } // Check to see if Expiration property is set internal bool IsSetExpiration() { return this.expiration != null; } /// <summary> /// Gets and sets the RestoreExpiration property. /// RestoreExpiration will be set for objects that have been restored from Amazon Glacier. /// It indiciates for those objects how long the restored object will exist. /// </summary> public DateTime? RestoreExpiration { get { return this.restoreExpiration; } set { this.restoreExpiration = value; } } /// <summary> /// Gets and sets the RestoreInProgress /// Will be true when the object is in the process of being restored from Amazon Glacier. /// </summary> public bool RestoreInProgress { get { return this.restoreInProgress; } set { this.restoreInProgress = value; } } /// <summary> /// Last modified date of the object /// /// </summary> public DateTime LastModified { get { return this.lastModified ?? default(DateTime); } set { this.lastModified = value; } } // Check to see if LastModified property is set internal bool IsSetLastModified() { return this.lastModified.HasValue; } /// <summary> /// An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL /// /// </summary> public string ETag { get { return this.eTag; } set { this.eTag = value; } } // Check to see if ETag property is set internal bool IsSetETag() { return this.eTag != null; } /// <summary> /// This is set to the number of metadata entries not returned in x-amz-meta headers. This can happen if you create metadata using an API like /// SOAP that supports more flexible metadata than the REST API. For example, using SOAP, you can create metadata whose values are not legal /// HTTP headers. /// /// </summary> public int MissingMeta { get { return this.missingMeta ?? default(int); } set { this.missingMeta = value; } } // Check to see if MissingMeta property is set internal bool IsSetMissingMeta() { return this.missingMeta.HasValue; } /// <summary> /// Version of the object. /// /// </summary> public string VersionId { get { return this.versionId; } set { this.versionId = value; } } // Check to see if VersionId property is set internal bool IsSetVersionId() { return this.versionId != null; } /// <summary> /// The date and time at which the object is no longer cacheable. /// /// </summary> public DateTime Expires { get { if (this.isExpiresUnmarshalled) { return this.expires.Value; } else { this.expires = AmazonS3Util.ParseExpiresHeader(this.RawExpires, this.ResponseMetadata.RequestId); this.isExpiresUnmarshalled = true; return this.expires.Value; } } set { this.expires = value; this.isExpiresUnmarshalled = true; } } // Check to see if Expires property is set internal bool IsSetExpires() { return this.expires.HasValue; } /// <summary> /// Gets and sets the property ObjectLockLegalHoldStatus. /// </summary> public ObjectLockLegalHoldStatus ObjectLockLegalHoldStatus { get { return this.objectLockLegalHoldStatus; } set { this.objectLockLegalHoldStatus = value; } } // Check to see if ObjectLockLegalHoldStatus property is set internal bool IsSetObjectLockLegalHoldStatus() { return this.objectLockLegalHoldStatus != null; } /// <summary> /// Gets and sets the property ObjectLockMode. /// <para> /// The Object Lock mode currently in place for this object. /// </para> /// </summary> public ObjectLockMode ObjectLockMode { get { return this.objectLockMode; } set { this.objectLockMode = value; } } // Check to see if ObjectLockMode property is set internal bool IsSetObjectLockMode() { return this.objectLockMode != null; } /// <summary> /// Gets and sets the property ObjectLockRetainUntilDate. /// <para> /// The date and time when this object's Object Lock will expire. /// </para> /// </summary> public DateTime ObjectLockRetainUntilDate { get { return this.objectLockRetainUntilDate.GetValueOrDefault(); } set { this.objectLockRetainUntilDate = value; } } // Check to see if ObjectLockRetainUntilDate property is set internal bool IsSetObjectLockRetainUntilDate() { return this.objectLockRetainUntilDate.HasValue; } /// <summary> /// If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. /// Amazon S3 stores the value of this header in the object metadata. /// /// </summary> public string WebsiteRedirectLocation { get { return this.websiteRedirectLocation; } set { this.websiteRedirectLocation = value; } } // Check to see if WebsiteRedirectLocation property is set internal bool IsSetWebsiteRedirectLocation() { return this.websiteRedirectLocation != null; } /// <summary> /// The Server-side encryption algorithm used when storing this object in S3. /// /// </summary> public ServerSideEncryptionMethod ServerSideEncryptionMethod { get { return this.serverSideEncryption; } set { this.serverSideEncryption = value; } } // Check to see if ServerSideEncryptionMethod property is set internal bool IsSetServerSideEncryptionMethod() { return this.serverSideEncryption != null; } /// <summary> /// The class of storage used to store the object. /// /// </summary> public S3StorageClass StorageClass { get { return this.storageClass; } set { this.storageClass = value; } } // Check to see if StorageClass property is set internal bool IsSetStorageClass() { return this.storageClass != null; } /// <summary> /// The id of the AWS Key Management Service key that Amazon S3 uses to encrypt and decrypt the object. /// </summary> public string ServerSideEncryptionKeyManagementServiceKeyId { get { return this.serverSideEncryptionKeyManagementServiceKeyId; } set { this.serverSideEncryptionKeyManagementServiceKeyId = value; } } /// <summary> /// Checks if ServerSideEncryptionKeyManagementServiceKeyId property is set. /// </summary> /// <returns>true if ServerSideEncryptionKeyManagementServiceKeyId property is set.</returns> internal bool IsSetServerSideEncryptionKeyManagementServiceKeyId() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionKeyManagementServiceKeyId); } /// <summary> /// The status of the replication job associated with this source object. /// </summary> public ReplicationStatus ReplicationStatus { get { return this.replicationStatus; } set { this.replicationStatus = value; } } /// <summary> /// Checks if ReplicationStatus property is set. /// </summary> /// <returns>true if ReplicationStatus property is set.</returns> internal bool IsSetReplicationStatus() { return ReplicationStatus != null; } /// <summary> /// The number of parts this oject has. /// </summary> public int? PartsCount { get { return this.partsCount; } set { this.partsCount = value; } } /// <summary> /// Checks if PartsCount is set. /// </summary> /// <returns>true if PartsCount property is set.</returns> internal bool IsSetPartsCount() { return this.partsCount.HasValue; } /// <summary> /// The Server-side encryption algorithm to be used with the customer provided key. /// /// </summary> public ServerSideEncryptionCustomerMethod ServerSideEncryptionCustomerMethod { get { if (this.serverSideEncryptionCustomerMethod == null) return ServerSideEncryptionCustomerMethod.None; return this.serverSideEncryptionCustomerMethod; } set { this.serverSideEncryptionCustomerMethod = value; } } /// <summary> /// If present, indicates that the requester was successfully charged for the request. /// </summary> public RequestCharged RequestCharged { get { return this.requestCharged; } set { this.requestCharged = value; } } /// <summary> /// Checks to see if RequestCharged is set. /// </summary> /// <returns>true, if RequestCharged property is set.</returns> internal bool IsSetRequestCharged() { return requestCharged != null; } /// <summary> /// The number of tags, if any, on the object. /// </summary> public int TagCount { get { return this.tagCount ?? 0; } set { this.tagCount = value; } } #if BCL /// <summary> /// Writes the content of the ResponseStream a file indicated by the filePath argument. /// </summary> /// <param name="filePath">The location where to write the ResponseStream</param> public void WriteResponseStreamToFile(string filePath) { WriteResponseStreamToFile(filePath, false); } /// <summary> /// Writes the content of the ResponseStream a file indicated by the filePath argument. /// </summary> /// <param name="filePath">The location where to write the ResponseStream</param> /// <param name="append">Whether or not to append to the file if it exists</param> public void WriteResponseStreamToFile(string filePath, bool append) { CreateDirectory(filePath); Stream downloadStream = CreateDownloadStream(filePath, append); using (downloadStream) { long current = 0; byte[] buffer = new byte[S3Constants.DefaultBufferSize]; int bytesRead = 0; long totalIncrementTransferred = 0; while ((bytesRead = this.ResponseStream.Read(buffer, 0, buffer.Length)) > 0) { downloadStream.Write(buffer, 0, bytesRead); current += bytesRead; totalIncrementTransferred += bytesRead; if (totalIncrementTransferred >= AWSSDKUtils.DefaultProgressUpdateInterval) { this.OnRaiseProgressEvent(filePath, totalIncrementTransferred, current, this.ContentLength, completed:false); totalIncrementTransferred = 0; } } ValidateWrittenStreamSize(current); // Encrypted objects may have size smaller than the total amount of data transfered due to padding. // Instead of changing the file size or the total downloaded size, pass a flag that indicate that the transfer is complete. this.OnRaiseProgressEvent(filePath, totalIncrementTransferred, current, this.ContentLength, completed:true); } } private static Stream CreateDownloadStream(string filePath, bool append) { Stream downloadStream; if (append && File.Exists(filePath)) downloadStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read, S3Constants.DefaultBufferSize); else downloadStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, S3Constants.DefaultBufferSize); return downloadStream; } private static void CreateDirectory(string filePath) { // Make sure the directory exists to write too. FileInfo fi = new FileInfo(filePath); Directory.CreateDirectory(fi.DirectoryName); } #endif #if !UNITY #region Progress Event /// <summary> /// The event for Write Object progress notifications. All /// subscribers will be notified when a new progress /// event is raised. /// </summary> /// <remarks> /// Subscribe to this event if you want to receive /// put object progress notifications. Here is how:<br /> /// 1. Define a method with a signature similar to this one: /// <code> /// private void displayProgress(object sender, WriteObjectProgressArgs args) /// { /// Console.WriteLine(args); /// } /// </code> /// 2. Add this method to the Put Object Progress Event delegate's invocation list /// <code> /// GetObjectResponse response = s3Client.GetObject(request); /// response.WriteObjectProgressEvent += displayProgress; /// </code> /// </remarks> public event EventHandler<WriteObjectProgressArgs> WriteObjectProgressEvent; #endregion /// <summary> /// This method is called by a producer of write object progress /// notifications. When called, all the subscribers in the /// invocation list will be called sequentially. /// </summary> /// <param name="file">The file being written.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> /// <param name="completed">True if transfer is complete</param> internal void OnRaiseProgressEvent(string file, long incrementTransferred, long transferred, long total, bool completed) { AWSSDKUtils.InvokeInBackground(WriteObjectProgressEvent, new WriteObjectProgressArgs(this.BucketName, this.Key, file, this.VersionId, incrementTransferred, transferred, total, completed), this); } private void ValidateWrittenStreamSize(long bytesWritten) { #if !PCL // Check if response stream or it's base stream is a AESDecryptionStream var stream = Runtime.Internal.Util.WrapperStream.SearchWrappedStream(this.ResponseStream, (s => s is Runtime.Internal.Util.DecryptStream)); // Don't validate length if response is an encrypted object. if (stream!=null) return; #endif if (bytesWritten != this.ContentLength) { string amzId2; if(!this.ResponseMetadata.Metadata.TryGetValue(HeaderKeys.XAmzId2Header, out amzId2)) amzId2 = string.Empty; string amzCfId; if(!this.ResponseMetadata.Metadata.TryGetValue(HeaderKeys.XAmzCloudFrontIdHeader, out amzCfId)) amzCfId = string.Empty; string message = null; if (string.IsNullOrEmpty(amzCfId)) { message = string.Format(CultureInfo.InvariantCulture, "The total bytes read {0} from response stream is not equal to the Content-Length {1} for the object {2} in bucket {3}." + " Request ID = {4} , AmzId2 = {5}.", bytesWritten, this.ContentLength, this.Key, this.BucketName, this.ResponseMetadata.RequestId, amzId2); } else { message = string.Format(CultureInfo.InvariantCulture, "The total bytes read {0} from response stream is not equal to the Content-Length {1} for the object {2} in bucket {3}." + " Request ID = {4} , AmzId2 = {5} , AmzCfId = {6}.", bytesWritten, this.ContentLength, this.Key, this.BucketName, this.ResponseMetadata.RequestId, amzId2, amzCfId); } throw new StreamSizeMismatchException(message, this.ContentLength, bytesWritten, this.ResponseMetadata.RequestId, amzId2, amzCfId); } } #if BCL45 || NETSTANDARD /// <summary> /// Writes the content of the ResponseStream a file indicated by the filePath argument. /// </summary> /// <param name="filePath">The location where to write the ResponseStream</param> /// <param name="append">Whether or not to append to the file if it exists</param> /// <param name="cancellationToken">Cancellation token which can be used to cancel this operation.</param> public async System.Threading.Tasks.Task WriteResponseStreamToFileAsync(string filePath, bool append, System.Threading.CancellationToken cancellationToken) { // Make sure the directory exists to write too. FileInfo fi = new FileInfo(filePath); Directory.CreateDirectory(fi.DirectoryName); Stream downloadStream; if (append && File.Exists(filePath)) downloadStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read, S3Constants.DefaultBufferSize); else downloadStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, S3Constants.DefaultBufferSize); try { long current = 0; #if NETSTANDARD Stream stream = this.ResponseStream; #else Stream stream = new BufferedStream(this.ResponseStream); #endif byte[] buffer = new byte[S3Constants.DefaultBufferSize]; int bytesRead = 0; long totalIncrementTransferred = 0; while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length) .ConfigureAwait(continueOnCapturedContext: false)) > 0) { cancellationToken.ThrowIfCancellationRequested(); await downloadStream.WriteAsync(buffer, 0, bytesRead) .ConfigureAwait(continueOnCapturedContext: false); current += bytesRead; totalIncrementTransferred += bytesRead; if (totalIncrementTransferred >= AWSSDKUtils.DefaultProgressUpdateInterval) { this.OnRaiseProgressEvent(filePath, totalIncrementTransferred, current, this.ContentLength, completed:false); totalIncrementTransferred = 0; } } ValidateWrittenStreamSize(current); // Encrypted objects may have size smaller than the total amount of data trasnfered due to padding. // Instead of changing the file size or the total downloaded size, pass a flag that indicate that the transfer is complete. this.OnRaiseProgressEvent(filePath, totalIncrementTransferred, current, this.ContentLength, completed:true); } finally { downloadStream.Dispose(); } } #endif #endif } #if !UNITY /// <summary> /// Encapsulates the information needed to provide /// download progress for the Write Object Event. /// </summary> public class WriteObjectProgressArgs : TransferProgressArgs { /// <summary> /// The constructor takes the number of /// currently transferred bytes and the /// total number of bytes to be transferred /// </summary> /// <param name="bucketName">The bucket name for the S3 object being written.</param> /// <param name="key">The object key for the S3 object being written.</param> /// <param name="versionId">The version-id of the S3 object.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> /// <param name="completed">True if finished writing</param> internal WriteObjectProgressArgs(string bucketName, string key, string versionId, long incrementTransferred, long transferred, long total, bool completed) : base(incrementTransferred, transferred, total) { this.BucketName = bucketName; this.Key = key; this.VersionId = versionId; this.IsCompleted = completed; } /// <summary> /// The constructor takes the number of /// currently transferred bytes and the /// total number of bytes to be transferred /// </summary> /// <param name="bucketName">The bucket name for the S3 object being written.</param> /// <param name="key">The object key for the S3 object being written.</param> /// <param name="filePath">The file for the S3 object being written.</param> /// <param name="versionId">The version-id of the S3 object.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> /// <param name="completed">True if finished writing</param> internal WriteObjectProgressArgs(string bucketName, string key, string filePath, string versionId, long incrementTransferred, long transferred, long total, bool completed) : base(incrementTransferred, transferred, total) { this.BucketName = bucketName; this.Key = key; this.VersionId = versionId; this.FilePath = filePath; this.IsCompleted = completed; } /// <summary> /// Gets the bucket name for the S3 object being written. /// </summary> public string BucketName { get; private set; } /// <summary> /// Gets the object key for the S3 object being written. /// </summary> public string Key { get; private set; } /// <summary> /// Gets the version-id of the S3 object. /// </summary> public string VersionId { get; private set; } /// <summary> /// The file for the S3 object being written. /// </summary> public string FilePath { get; private set; } /// <summary> /// True if writing is complete /// </summary> public bool IsCompleted { get; private set; } } #endif }
38.014249
206
0.590486
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/S3/Custom/Model/GetObjectResponse.cs
29,347
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 es-2015-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Elasticsearch.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Elasticsearch.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ElasticsearchDomainConfig Object /// </summary> public class ElasticsearchDomainConfigUnmarshaller : IUnmarshaller<ElasticsearchDomainConfig, XmlUnmarshallerContext>, IUnmarshaller<ElasticsearchDomainConfig, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ElasticsearchDomainConfig IUnmarshaller<ElasticsearchDomainConfig, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ElasticsearchDomainConfig Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ElasticsearchDomainConfig unmarshalledObject = new ElasticsearchDomainConfig(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("AccessPolicies", targetDepth)) { var unmarshaller = AccessPoliciesStatusUnmarshaller.Instance; unmarshalledObject.AccessPolicies = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("AdvancedOptions", targetDepth)) { var unmarshaller = AdvancedOptionsStatusUnmarshaller.Instance; unmarshalledObject.AdvancedOptions = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CognitoOptions", targetDepth)) { var unmarshaller = CognitoOptionsStatusUnmarshaller.Instance; unmarshalledObject.CognitoOptions = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EBSOptions", targetDepth)) { var unmarshaller = EBSOptionsStatusUnmarshaller.Instance; unmarshalledObject.EBSOptions = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ElasticsearchClusterConfig", targetDepth)) { var unmarshaller = ElasticsearchClusterConfigStatusUnmarshaller.Instance; unmarshalledObject.ElasticsearchClusterConfig = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ElasticsearchVersion", targetDepth)) { var unmarshaller = ElasticsearchVersionStatusUnmarshaller.Instance; unmarshalledObject.ElasticsearchVersion = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EncryptionAtRestOptions", targetDepth)) { var unmarshaller = EncryptionAtRestOptionsStatusUnmarshaller.Instance; unmarshalledObject.EncryptionAtRestOptions = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LogPublishingOptions", targetDepth)) { var unmarshaller = LogPublishingOptionsStatusUnmarshaller.Instance; unmarshalledObject.LogPublishingOptions = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("NodeToNodeEncryptionOptions", targetDepth)) { var unmarshaller = NodeToNodeEncryptionOptionsStatusUnmarshaller.Instance; unmarshalledObject.NodeToNodeEncryptionOptions = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SnapshotOptions", targetDepth)) { var unmarshaller = SnapshotOptionsStatusUnmarshaller.Instance; unmarshalledObject.SnapshotOptions = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("VPCOptions", targetDepth)) { var unmarshaller = VPCDerivedInfoStatusUnmarshaller.Instance; unmarshalledObject.VPCOptions = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ElasticsearchDomainConfigUnmarshaller _instance = new ElasticsearchDomainConfigUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ElasticsearchDomainConfigUnmarshaller Instance { get { return _instance; } } } }
42.75
188
0.612342
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Elasticsearch/Generated/Model/Internal/MarshallTransformations/ElasticsearchDomainConfigUnmarshaller.cs
6,498
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Net; using System.Net.Mail; public partial class RecuperarSenhaFunc : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string newPass; newPass = GenerateRandomCode(); //mudar para a senha padrão DateTime dtAlt = DateTime.Today; String dataSenha = dtAlt.ToString("yyyy/MM/dd"); sqlResetarSenhaFunc.UpdateParameters["data_alt"].DefaultValue = dataSenha; sqlResetarSenhaFunc.UpdateParameters["senha"].DefaultValue = newPass.ToString(); sqlResetarSenhaFunc.Update(); Session["novaSenhaFuncSenha"] = newPass.ToString(); SmtpClient cliente = new SmtpClient("smtp.live.com"); cliente.EnableSsl = true; MailAddress remetente = new MailAddress("monarcaperfumes@gmail.com", "Monarca Perfumes Ltda."); MailAddress destinatario = new MailAddress(Session["emailFuncSenha"].ToString(), "Funcionário"); MailMessage mensagem = new MailMessage(remetente, destinatario); mensagem.Body = "Olá!" + "\r\n" + "" + "Sua senha foi alterada, conforme pedido enviado para nosso site. Agora, sua senha é <b>" + Session["novaSenhaFuncSenha"].ToString() + "</b>." + "\r\n" + "Lembramos que essa é uma senha temporária. Entre em sua conta <b>imediatamente</b> e atualize sua senha." + "\r\n" + "" + "Atenciosamente," + "\r\n" + "Monarca Perfumes Ltda."; mensagem.IsBodyHtml = true; mensagem.Subject = "Recuperação de Senha"; NetworkCredential credenciais = new NetworkCredential("generico6wa@hotmail.com", "generico3g", ""); cliente.Credentials = credenciais; try { cliente.Send(mensagem); lblSucesso.Text = "Enviamos um email para você, com instruções para recuperar sua senha."; } catch (Exception ex) { lblSucesso.Text = ex.ToString(); } } private string GenerateRandomCode() { Random r = new Random(); string s = ""; for (int j = 0; j < 8; j++) { int i = r.Next(3); int ch; switch (i) { case 1: ch = r.Next(0, 9); s = s + ch.ToString(); break; case 2: ch = r.Next(65, 90); s = s + Convert.ToChar(ch).ToString(); break; case 3: ch = r.Next(97, 122); s = s + Convert.ToChar(ch).ToString(); break; default: ch = r.Next(97, 122); s = s + Convert.ToChar(ch).ToString(); break; } r.NextDouble(); r.Next(100, 1999); } return s; } protected void btnLogin_Click(object sender, EventArgs e) { Session.Abandon(); Response.Redirect("LoginFunc.aspx"); } }
32.438095
169
0.515854
[ "MIT" ]
ApoOliveira18/Monarca
projetoMonarca/RecuperarSenhaFunc.aspx.cs
3,419
C#
using System.Collections.Generic; using System.Linq; using System.Threading; namespace LANMaker.Data { public class CombinedGameService { private readonly StateContainer state; public CombinedGameService(StateContainer state) { this.state = state; } public List<CombinedGame> GetCombinedGames() { var manifest = state.Manifest; var configuration = state.Configuration; var list = new List<CombinedGame>(); foreach (var serverGame in manifest.Games) { list.Add(new CombinedGame { ServerGame = serverGame, ClientGame = configuration.InstalledGames.FirstOrDefault(clientGame => clientGame.Name == serverGame.Name) }); } return list.OrderBy(combinedGame => combinedGame.ServerGame.Title).ToList(); } } }
26.055556
126
0.593817
[ "MIT" ]
drogoganor/LANMaker
LANMaker/Data/CombinedGameService.cs
940
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.CSharp.Transforms; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource { internal class CSharpDecompiledSourceService : IDecompiledSourceService { private readonly HostLanguageServices provider; private static readonly FileVersionInfo decompilerVersion = FileVersionInfo.GetVersionInfo(typeof(CSharpDecompiler).Assembly.Location); public CSharpDecompiledSourceService(HostLanguageServices provider) { this.provider = provider; } public async Task<Document> AddSourceToAsync(Document document, Compilation symbolCompilation, ISymbol symbol, CancellationToken cancellationToken) { // Get the name of the type the symbol is in var containingOrThis = symbol.GetContainingTypeOrThis(); var fullName = GetFullReflectionName(containingOrThis); string assemblyLocation = null; var isReferenceAssembly = symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass.Name == nameof(ReferenceAssemblyAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(ReferenceAssemblyAttribute).FullName); if (isReferenceAssembly) { try { var fullAssemblyName = symbol.ContainingAssembly.Identity.GetDisplayName(); GlobalAssemblyCache.Instance.ResolvePartialName(fullAssemblyName, out assemblyLocation, preferredCulture: CultureInfo.CurrentCulture); } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { } } if (assemblyLocation == null) { var reference = symbolCompilation.GetMetadataReference(symbol.ContainingAssembly); assemblyLocation = (reference as PortableExecutableReference)?.FilePath; if (assemblyLocation == null) { throw new NotSupportedException(EditorFeaturesResources.Cannot_navigate_to_the_symbol_under_the_caret); } } // Decompile document = PerformDecompilation(document, fullName, symbolCompilation, assemblyLocation); document = await AddAssemblyInfoRegionAsync(document, symbol, cancellationToken).ConfigureAwait(false); // Convert XML doc comments to regular comments, just like MAS var docCommentFormattingService = document.GetLanguageService<IDocumentationCommentFormattingService>(); document = await ConvertDocCommentsToRegularCommentsAsync(document, docCommentFormattingService, cancellationToken).ConfigureAwait(false); var node = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Apply formatting rules document = await Formatter.FormatAsync( document, SpecializedCollections.SingletonEnumerable(node.FullSpan), options: null, Formatter.GetDefaultFormattingRules(document), cancellationToken).ConfigureAwait(false); return document; } private Document PerformDecompilation(Document document, string fullName, Compilation compilation, string assemblyLocation) { // Load the assembly. var file = new PEFile(assemblyLocation, PEStreamOptions.PrefetchEntireImage); // Initialize a decompiler with default settings. var decompiler = new CSharpDecompiler(file, new AssemblyResolver(compilation), new DecompilerSettings()); // Escape invalid identifiers to prevent Roslyn from failing to parse the generated code. // (This happens for example, when there is compiler-generated code that is not yet recognized/transformed by the decompiler.) decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers()); var fullTypeName = new FullTypeName(fullName); // Try to decompile; if an exception is thrown the caller will handle it var text = decompiler.DecompileTypeAsString(fullTypeName); return document.WithText(SourceText.From(text)); } private async Task<Document> AddAssemblyInfoRegionAsync(Document document, ISymbol symbol, CancellationToken cancellationToken) { var assemblyInfo = MetadataAsSourceHelpers.GetAssemblyInfo(symbol.ContainingAssembly); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var assemblyPath = MetadataAsSourceHelpers.GetAssemblyDisplay(compilation, symbol.ContainingAssembly); var regionTrivia = SyntaxFactory.RegionDirectiveTrivia(true) .WithTrailingTrivia(new[] { SyntaxFactory.Space, SyntaxFactory.PreprocessingMessage(assemblyInfo) }); var oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.WithLeadingTrivia(new[] { SyntaxFactory.Trivia(regionTrivia), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.Comment("// " + assemblyPath), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.Comment($"// Decompiled with ICSharpCode.Decompiler {decompilerVersion.FileVersion}"), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.Trivia(SyntaxFactory.EndRegionDirectiveTrivia(true)), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.CarriageReturnLineFeed }); return document.WithSyntaxRoot(newRoot); } private async Task<Document> ConvertDocCommentsToRegularCommentsAsync(Document document, IDocumentationCommentFormattingService docCommentFormattingService, CancellationToken cancellationToken) { var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newSyntaxRoot = DocCommentConverter.ConvertToRegularComments(syntaxRoot, docCommentFormattingService, cancellationToken); return document.WithSyntaxRoot(newSyntaxRoot); } private string GetFullReflectionName(INamedTypeSymbol containingType) { var stack = new Stack<string>(); stack.Push(containingType.MetadataName); var ns = containingType.ContainingNamespace; do { stack.Push(ns.Name); ns = ns.ContainingNamespace; } while (ns != null && !ns.IsGlobalNamespace); return string.Join(".", stack); } } }
48.78125
201
0.697758
[ "Apache-2.0" ]
20chan/roslyn
src/EditorFeatures/CSharp/DecompiledSource/CSharpDecompiledSourceService.cs
7,807
C#
// Copyright (c) Microsoft. All rights reserved. using System; using System.Threading.Tasks; using Microsoft.Azure.Devices; using Microsoft.Azure.IoTSolutions.DeviceSimulation.Services.DataStructures; namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.Services.IotHub { public interface IServiceClient { void Init(string connString); Task<ServiceStatistics> GetServiceStatisticsAsync(); void Dispose(); } public class ServiceClientWrapper : IServiceClient, IDisposable { private IInstance instance; private ServiceClient serviceClient; public ServiceClientWrapper(IInstance instance) { this.instance = instance; } public void Init(string connString) { this.instance.InitOnce(); this.serviceClient = ServiceClient.CreateFromConnectionString(connString); this.instance.InitComplete(); } public async Task<ServiceStatistics> GetServiceStatisticsAsync() { this.instance.InitRequired(); return await this.serviceClient.GetServiceStatisticsAsync(); } public void Dispose() { this.ReleaseResources(); } ~ServiceClientWrapper() { this.ReleaseResources(); } private void ReleaseResources() { this.serviceClient?.Dispose(); this.instance = null; } } }
25.186441
86
0.629879
[ "MIT" ]
Azure/azure-iot-pcs-device-simulation
microservices/device-simulation-dotnet/Services/IotHub/ServiceClientWrapper.cs
1,486
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { public partial class Persona : IEquatable<Persona> { public override string ToString() => $"DNI: {Dni}, Nombre: {Nombre}, Apellidos: {Apellidos}"; public bool Equals(Persona other) => Dni.Equals(other.Dni) && Nif.Equals(other.Nif); } }
24.294118
101
0.670702
[ "Apache-2.0" ]
jofaval/-tfcgs-dam
EntityFrameworkModel/Persona.cs
415
C#
using Auth0.Core.Exceptions; using Auth0.ManagementApi.Models; using Auth0.Tests.Shared; using FluentAssertions; using System; using System.Threading.Tasks; using Xunit; namespace Auth0.ManagementApi.IntegrationTests { public class GuardianTests : TestBase, IAsyncLifetime { ManagementApiClient _managementApiClient; public async Task InitializeAsync() { string token = await GenerateManagementApiToken(); _managementApiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL")); } public Task DisposeAsync() { return Task.CompletedTask; } [Fact] public async Task Can_retrieve_guardian_factors() { var response = await _managementApiClient.Guardian.GetFactorsAsync(); response.Should().HaveCount(5); } [Fact] public async Task Retrieving_non_existent_enrollment_throws() { Func<Task> getFunc = async () => await _managementApiClient.Guardian.GetEnrollmentAsync("dev_123456"); (await getFunc.Should().ThrowAsync<ErrorApiException>()) .And.ApiError.ErrorCode.Should().Be("enrollment_not_found"); } [Fact] public async Task Deleting_non_existent_enrollment_throws() { Func<Task> deleteFunc = async () => await _managementApiClient.Guardian.DeleteEnrollmentAsync("dev_123456"); (await deleteFunc.Should().ThrowAsync<ErrorApiException>()) .And.ApiError.ErrorCode.Should().Be("enrollment_not_found"); } [Fact] public async Task Can_perform_sms_template_maintenance() { // Get the current templates var initialTemplates = await _managementApiClient.Guardian.GetSmsTemplatesAsync(); initialTemplates.Should().NotBeNull(); // Update the templates var templateUpdateRequest = new GuardianSmsEnrollmentTemplates { EnrollmentMessage = $"This is the enrollment message {Guid.NewGuid()}", VerificationMessage = $"This is the verification message {Guid.NewGuid()}" }; var templateUpdateResponse = await _managementApiClient.Guardian.UpdateSmsTemplatesAsync(templateUpdateRequest); templateUpdateResponse.Should().BeEquivalentTo(templateUpdateRequest); } [Fact] public async Task Can_create_enrollment_ticket() { // Create a connection for creating a user var connection = await _managementApiClient.Connections.CreateAsync(new ConnectionCreateRequest { Name = Guid.NewGuid().ToString("N"), Strategy = "auth0", EnabledClients = new[] { GetVariable("AUTH0_CLIENT_ID"), GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID") } }); // Create a new user var userCreateRequest = new UserCreateRequest { Connection = connection.Name, Email = $"{Guid.NewGuid():N}@nonexistingdomain.aaa", EmailVerified = true, Password = "jd78w3hku23134?" }; var user = await _managementApiClient.Users.CreateAsync(userCreateRequest); // Create an enrollment request var request = new CreateGuardianEnrollmentTicketRequest { UserId = user.UserId, MustSendMail = false }; var response = await _managementApiClient.Guardian.CreateEnrollmentTicketAsync(request); response.TicketId.Should().NotBeNull(); response.TicketUrl.Should().NotBeNull(); // Clean up after ourselves await _managementApiClient.Users.DeleteAsync(user.UserId); await _managementApiClient.Connections.DeleteAsync(connection.Id); } [Fact] public async Task Can_update_factors() { UpdateGuardianFactorResponse response; response = await _managementApiClient.Guardian.UpdateFactorAsync(new UpdateGuardianFactorRequest { Factor = GuardianFactorName.Sms, IsEnabled = false }); response.IsEnabled.Should().BeFalse(); response = await _managementApiClient.Guardian.UpdateFactorAsync(new UpdateGuardianFactorRequest { Factor = GuardianFactorName.Sms, IsEnabled = true }); response.IsEnabled.Should().BeTrue(); response = await _managementApiClient.Guardian.UpdateFactorAsync(new UpdateGuardianFactorRequest { Factor = GuardianFactorName.PushNotifications, IsEnabled = false }); response.IsEnabled.Should().BeFalse(); response = await _managementApiClient.Guardian.UpdateFactorAsync(new UpdateGuardianFactorRequest { Factor = GuardianFactorName.Sms, IsEnabled = true }); response.IsEnabled.Should().BeTrue(); } [Fact] public async Task Can_update_twilio_provider_configuration() { var request = new UpdateGuardianTwilioConfigurationRequest { AuthToken = Guid.NewGuid().ToString("N"), From = "+123456789", Sid = Guid.NewGuid().ToString("N") }; var response = await _managementApiClient.Guardian.UpdateTwilioConfigurationAsync(request); response.Should().BeEquivalentTo(request); request = new UpdateGuardianTwilioConfigurationRequest { AuthToken = Guid.NewGuid().ToString("N"), MessagingServiceSid = Guid.NewGuid().ToString("N"), Sid = Guid.NewGuid().ToString("N") }; response = await _managementApiClient.Guardian.UpdateTwilioConfigurationAsync(request); response.Should().BeEquivalentTo(request); response = await _managementApiClient.Guardian.GetTwilioConfigurationAsync(); response.Should().BeEquivalentTo(request); } } }
37.376471
124
0.607649
[ "MIT" ]
flarocca/auth0.net
tests/Auth0.ManagementApi.IntegrationTests/GuardianTests.cs
6,356
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _03.TownInfo { class Program { static void Main(string[] args) { string city = Console.ReadLine(); int population = int.Parse(Console.ReadLine()); int sqKm = int.Parse(Console.ReadLine()); Console.WriteLine($"Town {city} has population of {population} and area {sqKm} square km."); } } }
25.684211
105
0.584016
[ "MIT" ]
dradoslavov/Technology-Fundamentals
02.Data Types and Variables - Exercise/03.TownInfo/03.Town Info.cs
490
C#
using ShineEngine; using UnityEngine; /// <summary> /// 离线游戏控制 /// </summary> public class GameOfflineControl { private bool _playerLoaded=false; private int _currentBornCode = -1; /** 当前角色ID */ private long _currentPlayerID = -1; /** 本地存储文件路径 */ private string _playerSavePath; /** 角色缓存数据 */ private BytesWriteStream _stream = new BytesWriteStream(); /** 角色列表数据 */ private PlayerListData _listData; /** 离线事务列表数据 */ private ClientOfflineWorkListData _offlineWorkListData; /** 角色离线缓存数据 */ private PlayerOfflineCacheExData _offLineExData; /** 当前序号 */ private int _currentIndex = 0; // /** 总数据 */ // private SList<ClientOfflineWorkData> _workList=new SList<ClientOfflineWorkData>(); /** 初始化 */ public void init() { SystemControl.applicationQuitFunc+=onApplicationQuit; } private void onApplicationQuit() { saveOnce(); } /** 读取某角色(离线用) */ public void loadPlayer(long playerID) { int serverBornCode = GameC.save.getCacheServerBornCode(); if (_currentBornCode == serverBornCode && _currentPlayerID == playerID) return; _currentBornCode = serverBornCode; _currentPlayerID = playerID; //兼容旧版 if (_currentBornCode <= 0) { _playerSavePath = Application.persistentDataPath + "/player_" + playerID + "/offlinePlayer.bin"; } else { _playerSavePath = Application.persistentDataPath + "/player_" + serverBornCode + "_" + playerID + "/offlinePlayer.bin"; } _listData = null; if (FileUtils.fileExists(_playerSavePath)) { BytesReadStream stream = FileUtils.readFileForBytesReadStream(_playerSavePath); int version = stream.readInt(); //版本号不匹配 if (version != BaseC.config.getDBDataVersion()) { Ctrl.errorLog("本地存储结构版本不匹配,已清空persistant!,old:" + version + ",new:" + BaseC.config.getDBDataVersion()); //不是正式版 if (!ShineSetting.isOfficial) { if(ShineSetting.isRelease) { FileUtils.deleteFile(_playerSavePath); } else { FileUtils.clearDir(Application.persistentDataPath); } initNewPlayer(); return; } //跳过list stream.startReadObj(); stream.endReadObj(); _listData = null; } else { _listData = GameC.player.createListData(); _listData.readBytesFull(stream); } _offlineWorkListData = GameC.factory.createClientOfflineWorkListData(); _offlineWorkListData.readBytesFull(stream); _offLineExData = GameC.factory.createPlayerOfflineCacheExData(); _offLineExData.readBytesFull(stream); _currentIndex = _offlineWorkListData.index; } else { initNewPlayer(); } if(!_playerLoaded) { _playerLoaded=true; //需要离线部分 if (CommonSetting.useOfflineGame) { TimeDriver.instance.setInterval(onSave, CommonSetting.offlineSaveDelay); } } } private void initNewPlayer() { _listData = null; _offlineWorkListData = GameC.factory.createClientOfflineWorkListData(); _offlineWorkListData.initDefault(); _offLineExData = GameC.factory.createPlayerOfflineCacheExData(); _offLineExData.initDefault(); _currentIndex = _offlineWorkListData.index; } public void setCurrentIndex(int value) { _currentIndex = value; } /** 获取列表数据 */ public PlayerListData getListData() { return _listData; } /** 获取附属数据 */ public PlayerOfflineCacheExData getExData() { return _offLineExData; } public ClientOfflineWorkListData getOfflineWorkListData() { return _offlineWorkListData; } /** 准备推送离线事务数据 */ public SList<ClientOfflineWorkData> flushOfflineWork() { SList<ClientOfflineWorkData> list = new SList<ClientOfflineWorkData>(); list.addAll(_offlineWorkListData.list); return list; } /** 接受服务发送序号 */ public void receiveIndex(int sendIndex) { //如果不足,赋值(来解决多客户端互相离线登录的序号问题) if (_currentIndex < sendIndex) _currentIndex = sendIndex; ThreadControl.addAssistFunc(() => { ClientOfflineWorkData data; int find = -1; SList<ClientOfflineWorkData> list = _offlineWorkListData.list; for (int i = 0, len = list.size(); i < len; i++) { data = list.get(i); if (data.workIndex > sendIndex) { find = i; break; } } if (find == -1) { list.clear(); } else { list.removeRange(0, find); } }); } /** 保存一次 */ public void saveOnce() { if(!_playerLoaded) return; //初始化过的 if (GameC.player.system.inited()) { string path = _playerSavePath; PlayerListData data = GameC.player.createListData(); GameC.player.writeListData(data); BaseData exData = _offLineExData?.clone(); ThreadControl.addAssistFunc(() => { _stream.clear(); _stream.writeInt(BaseC.config.getDBDataVersion()); data.writeBytesFull(_stream); _offlineWorkListData.writeBytesFull(_stream); exData?.writeBytesFull(_stream); FileUtils.writeFileForBytesWriteStream(path, _stream); }); } } private void onSave(int delay) { saveOnce(); } /** 添加离线事务 */ public void addOfflineWork(ClientOfflineWorkData data) { data.workIndex = ++_currentIndex; data.workTime = DateControl.getTimeMillis(); ThreadControl.addAssistFunc(() => { _offlineWorkListData.index = data.workIndex; _offlineWorkListData.list.add(data); }); //当前在线 if (GameC.player.system.isOnline()) { SendClientOfflineWorkRequest.create(data).send(); } } // /** 客户端离线事务失败 */ // public void offlineWorkFailed(int receiveIndex,int serverIndex) // { // //出问题了,所以不相等 // if(receiveIndex!=serverIndex) // { // _currentIndex=serverIndex; // // ThreadControl.addAssistFunc(()=> // { // _offlineWorkListData.index=serverIndex; // _offlineWorkListData.list.clear(); // }); // } // else // { // this.receiveIndex(receiveIndex); // } // // GameC.info.showInfoCode(InfoCodeType.OfflineWorkFailed); // } /** 收到服务器序号 */ public void onReceive(int index, bool isSuccess) { this.receiveIndex(index); if (!isSuccess) { Ctrl.warnLog("离线事务失败", index); GameC.info.showInfoCode(InfoCodeType.OfflineWorkFailed); } } }
26.367003
132
0.524071
[ "Apache-2.0" ]
hw233/home3
core/client/game/src/commonGame/control/GameOfflineControl.cs
8,245
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.ComponentModel; using System.IO; using System.Threading; using Iot.Device.BrickPi3.Extensions; using Iot.Device.BrickPi3.Models; namespace Iot.Device.BrickPi3.Sensors { /// <summary> /// Create a EV3 Color sensor /// </summary> public class EV3ColorSensor : INotifyPropertyChanged, ISensor { private const int RedIndex = 0; private const int GreenIndex = 1; private const int BlueIndex = 2; private const int BackgroundIndex = 3; private Brick _brick = null; private ColorSensorMode _colorMode; private Int16[] _rawValues = new Int16[4]; private Timer _timer = null; private int _periodRefresh; private int _value; private string _valueAsString; /// <summary> /// Initialize an EV3 Color Sensor /// </summary> /// <param name="brick">Interface to main Brick component</param> /// <param name="port">Sensor port</param> public EV3ColorSensor(Brick brick, SensorPort port) : this(brick, port, ColorSensorMode.Color, 1000) { } /// <summary> /// Initialize an EV3 Color Sensor /// </summary> /// <param name="brick">Interface to main Brick component</param> /// <param name="port">Sensor port</param> /// <param name="mode">Color mode</param> public EV3ColorSensor(Brick brick, SensorPort port, ColorSensorMode mode) : this(brick, port, mode, 1000) { } /// <summary> /// Initilaize an EV3 Color Sensor /// </summary> /// <param name="brick">Interface to main Brick component</param> /// <param name="port">Sensor port</param> /// <param name="mode">Color mode</param> /// <param name="timeout">Period in millisecond to check sensor value changes</param> public EV3ColorSensor(Brick brick, SensorPort port, ColorSensorMode mode, int timeout) { _brick = brick; Port = port; _colorMode = mode; brick.SetSensorType((byte)Port, GetEV3Mode(mode)); _periodRefresh = timeout; _timer = new Timer(UpdateSensor, this, TimeSpan.FromMilliseconds(timeout), TimeSpan.FromMilliseconds(timeout)); } private void StopTimerInternal() { if (_timer != null) { _timer.Dispose(); _timer = null; } } private void OnPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } /// <summary> /// To notify a property has changed. The minimum time can be set up /// with timeout property /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Period to refresh the notification of property changed in milliseconds /// </summary> public int PeriodRefresh { get { return _periodRefresh; } set { _periodRefresh = value; _timer.Change(TimeSpan.FromMilliseconds(_periodRefresh), TimeSpan.FromMilliseconds(_periodRefresh)); } } private SensorType GetEV3Mode(ColorSensorMode mode) { SensorType ret = SensorType.EV3ColorReflected; switch (mode) { case ColorSensorMode.Color: ret = SensorType.EV3ColorColor; break; case ColorSensorMode.Reflection: ret = SensorType.EV3ColorReflected; break; case ColorSensorMode.Green: ret = SensorType.EV3ColorRawReflected; break; case ColorSensorMode.Blue: ret = SensorType.EV3ColorColorComponents; break; case ColorSensorMode.Ambient: ret = SensorType.EV3ColorAmbient; break; } return ret; } /// <summary> /// Set or get the color mode /// </summary> public ColorSensorMode ColorMode { get { return _colorMode; } set { if (value != _colorMode) { _colorMode = value; _brick.SetSensorType((byte)Port, GetEV3Mode(_colorMode)); } } } /// <summary> /// Return the raw value of the sensor /// </summary> public int Value { get { return ReadRaw(); } internal set { if (value != _value) { _value = value; OnPropertyChanged(nameof(Value)); } } } /// <summary> /// Return the raw value as a string of the sensor /// </summary> public string ValueAsString { get { return ReadAsString(); } internal set { if (_valueAsString != value) { _valueAsString = value; OnPropertyChanged(nameof(ValueAsString)); } } } /// <summary> /// Update the sensor and this will raised an event on the interface /// </summary> public void UpdateSensor(object state) { Value = ReadRaw(); ValueAsString = ReadAsString(); } private void GetRawValues() { try { var ret = _brick.GetSensor((byte)Port); switch (_colorMode) { case ColorSensorMode.Color: case ColorSensorMode.Reflection: case ColorSensorMode.Ambient: _rawValues[BackgroundIndex] = ret[0]; _rawValues[BlueIndex] = 0; _rawValues[GreenIndex] = 0; _rawValues[RedIndex] = 0; break; case ColorSensorMode.Green: case ColorSensorMode.Blue: _rawValues[BackgroundIndex] = ret[0]; _rawValues[BlueIndex] = ret[1]; _rawValues[GreenIndex] = ret[2]; _rawValues[RedIndex] = ret[3]; break; } } catch (Exception ex) when (ex is IOException) { } } /// <summary> /// Get the raw value /// </summary> /// <returns></returns> public int ReadRaw() { int val = 0; switch (_colorMode) { case ColorSensorMode.Color: case ColorSensorMode.Reflection: case ColorSensorMode.Ambient: val = (int)ReadColor(); break; case ColorSensorMode.Green: case ColorSensorMode.Blue: val = CalculateRawAverage(); break; } return val; } /// <summary> /// Read the intensity of the reflected or ambient light in percent. In color mode the color index is returned /// </summary> public int Read() { int val = 0; switch (_colorMode) { case ColorSensorMode.Color: case ColorSensorMode.Reflection: case ColorSensorMode.Ambient: val = (int)ReadColor(); break; default: val = CalculateRawAverageAsPct(); break; } return val; } private int CalculateRawAverage() { if (_colorMode == ColorSensorMode.Color) { return 0; } else { try { var ret = _brick.GetSensor((byte)Port); return (ret[0] + (ret[1] >> 8) + (ret[2] >> 16) + ret[3] >> 24) / 255 / 3; } catch (Exception ex) when (ex is IOException) { return 0; } } } private int CalculateRawAverageAsPct() { // Need to find out what is the ADC resolution // 1023 is probably the correct one return (CalculateRawAverage() * 100) / 1023; } /// <summary> /// Read the test value /// </summary> /// <returns></returns> public string ReadTest() { GetRawValues(); string ret = string.Empty; for (int i = 0; i < _rawValues.Length; i++) { ret += " " + _rawValues[i]; } ret += " " + (_rawValues[BackgroundIndex] + (_rawValues[BlueIndex] >> 8) + (_rawValues[GreenIndex] >> 16) + _rawValues[RedIndex] >> 24).ToString(); return ret; } /// <summary> /// Get the color as a string /// </summary> /// <returns></returns> public string ReadAsString() { string s = string.Empty; switch (_colorMode) { case ColorSensorMode.Color: s = ReadColor().ToString(); break; case ColorSensorMode.Reflection: case ColorSensorMode.Green: case ColorSensorMode.Blue: s = Read().ToString(); break; case ColorSensorMode.Ambient: s = Read().ToString(); break; } return s; } /// <summary> /// Reads the color. /// </summary> /// <returns>The color.</returns> public Color ReadColor() { Color color = Color.None; if (_colorMode == ColorSensorMode.Color) { try { color = (Color)_brick.GetSensor((byte)Port)[0]; } catch (Exception ex) when (ex is IOException) { color = Color.None; } } return color; } /// <summary> /// Reads the color of the RGB. /// </summary> /// <returns>The RGB color.</returns> public RGBColor ReadRGBColor() { GetRawValues(); return new RGBColor((byte)_rawValues[RedIndex], (byte)_rawValues[GreenIndex], (byte)_rawValues[BlueIndex]); } private Color CalculateColor() { GetRawValues(); int red = _rawValues[RedIndex]; int blue = _rawValues[BlueIndex]; int green = _rawValues[GreenIndex]; int blank = _rawValues[BackgroundIndex]; // we have calibrated values, now use them to determine the color // The following algorithm comes from the 1.29 Lego firmware. if (red > blue && red > green) { // Red dominant color if (red < 65 || (blank < 40 && red < 110)) { return Color.Black; } if (((blue >> 2) + (blue >> 3) + blue < green) && ((green << 1) > red)) { return Color.Yellow; } if ((green << 1) - (green >> 2) < red) { return Color.Red; } if (blue < 70 || green < 70 || (blank < 140 && red < 140)) { return Color.Black; } return Color.White; } else if (green > blue) { // Green dominant color if (green < 40 || (blank < 30 && green < 70)) { return Color.Black; } if ((blue << 1) < red) { return Color.Yellow; } if ((red + (red >> 2)) < green || (blue + (blue >> 2)) < green) { return Color.Green; } if (red < 70 || blue < 70 || (blank < 140 && green < 140)) { return Color.Black; } return Color.White; } else { // Blue dominant color if (blue < 48 || (blank < 25 && blue < 85)) { return Color.Black; } if ((((red * 48) >> 5) < blue && ((green * 48) >> 5) < blue) || ((red * 58) >> 5) < blue || ((green * 58) >> 5) < blue) { return Color.Blue; } if (red < 60 || green < 60 || (blank < 110 && blue < 120)) { return Color.Black; } if ((red + (red >> 3)) < blue || (green + (green >> 3)) < blue) { return Color.Blue; } return Color.White; } } /// <summary> /// Sensor port /// </summary> public SensorPort Port { get; } /// <summary> /// Gets sensor name /// </summary> /// <returns>Sensor name</returns> public string GetSensorName() { return "EV3 Color Sensor"; } /// <summary> /// Moves to next mode /// </summary> public void SelectNextMode() { ColorMode = ColorMode.Next(); } /// <summary> /// Moves to previous mode /// </summary> public void SelectPreviousMode() { ColorMode = ColorMode.Previous(); } /// <summary> /// Number of modes /// </summary> /// <returns>Number of modes supported</returns> public int NumberOfModes() { return Enum.GetNames(typeof(ColorSensorMode)).Length; } /// <summary> /// Selected mode /// </summary> /// <returns>String representing selected mode</returns> public string SelectedMode() { return ColorMode.ToString(); } } }
29.762646
159
0.443914
[ "MIT" ]
HakanL/iot
src/devices/BrickPi3/Sensors/EV3ColorSensor.cs
15,300
C#
using System.Collections.Generic; using System.Reflection; using IronText.Logging; using IronText.Reflection; using IronText.Reflection.Managed; using IronText.Reflection.Reporting; namespace IronText.Extensibility { public interface ICilMetadata { ICilMetadata Parent { get; } MemberInfo Member { get; } bool Validate(ILogging logging); IEnumerable<ICilMetadata> GetChildren(); void Bind(ICilMetadata parent, MemberInfo member); IEnumerable<CilSymbolFeature<Precedence>> GetSymbolPrecedence(); IEnumerable<CilSymbolFeature<CilContextProvider>> GetLocalContextProviders(); IEnumerable<CilSymbolRef> GetSymbolsInCategory(SymbolCategory category); IEnumerable<CilProduction> GetProductions(IEnumerable<CilSymbolRef> outcomes); IEnumerable<CilMerger> GetMergers(IEnumerable<CilSymbolRef> symbols); IEnumerable<CilMatcher> GetMatchers(); IEnumerable<IReport> GetReports(); } }
26.736842
87
0.722441
[ "Apache-2.0" ]
sucaba/IronTextLibrary
Src/IronText.Core/Extensibility/ICilMetadata.cs
1,018
C#
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Redshift.Model { /// <summary> /// Container for the parameters to the ModifyEventSubscription operation. /// <para> Modifies an existing Amazon Redshift event notification subscription. </para> /// </summary> public partial class ModifyEventSubscriptionRequest : AmazonRedshiftRequest { private string subscriptionName; private string snsTopicArn; private string sourceType; private List<string> sourceIds = new List<string>(); private List<string> eventCategories = new List<string>(); private string severity; private bool? enabled; /// <summary> /// The name of the modified Amazon Redshift event notification subscription. /// /// </summary> public string SubscriptionName { get { return this.subscriptionName; } set { this.subscriptionName = value; } } // Check to see if SubscriptionName property is set internal bool IsSetSubscriptionName() { return this.subscriptionName != null; } /// <summary> /// The Amazon Resource Name (ARN) of the SNS topic to be used by the event notification subscription. /// /// </summary> public string SnsTopicArn { get { return this.snsTopicArn; } set { this.snsTopicArn = value; } } // Check to see if SnsTopicArn property is set internal bool IsSetSnsTopicArn() { return this.snsTopicArn != null; } /// <summary> /// The type of source that will be generating the events. For example, if you want to be notified of events generated by a cluster, you would /// set this parameter to cluster. If this value is not specified, events are returned for all Amazon Redshift objects in your AWS account. You /// must specify a source type in order to specify source IDs. Valid values: cluster, cluster-parameter-group, cluster-security-group, and /// cluster-snapshot. /// /// </summary> public string SourceType { get { return this.sourceType; } set { this.sourceType = value; } } // Check to see if SourceType property is set internal bool IsSetSourceType() { return this.sourceType != null; } /// <summary> /// A list of one or more identifiers of Amazon Redshift source objects. All of the objects must be of the same type as was specified in the /// source type parameter. The event subscription will return only events generated by the specified objects. If not specified, then events are /// returned for all objects within the source type specified. Example: my-cluster-1, my-cluster-2 Example: my-snapshot-20131010 /// /// </summary> public List<string> SourceIds { get { return this.sourceIds; } set { this.sourceIds = value; } } // Check to see if SourceIds property is set internal bool IsSetSourceIds() { return this.sourceIds.Count > 0; } /// <summary> /// Specifies the Amazon Redshift event categories to be published by the event notification subscription. Values: Configuration, Management, /// Monitoring, Security /// /// </summary> public List<string> EventCategories { get { return this.eventCategories; } set { this.eventCategories = value; } } // Check to see if EventCategories property is set internal bool IsSetEventCategories() { return this.eventCategories.Count > 0; } /// <summary> /// Specifies the Amazon Redshift event severity to be published by the event notification subscription. Values: ERROR, INFO /// /// </summary> public string Severity { get { return this.severity; } set { this.severity = value; } } // Check to see if Severity property is set internal bool IsSetSeverity() { return this.severity != null; } /// <summary> /// A Boolean value indicating if the subscription is enabled. <c>true</c> indicates the subscription is enabled /// /// </summary> public bool Enabled { get { return this.enabled ?? default(bool); } set { this.enabled = value; } } // Check to see if Enabled property is set internal bool IsSetEnabled() { return this.enabled.HasValue; } } }
34.283951
151
0.60821
[ "Apache-2.0" ]
virajs/aws-sdk-net
AWSSDK_DotNet35/Amazon.Redshift/Model/ModifyEventSubscriptionRequest.cs
5,554
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DotNetGraphQL.Common; using GraphQL.Client.Http; using GraphQL.Common.Exceptions; using GraphQL.Common.Request; using GraphQL.Common.Response; using Polly; namespace DotNetGraphQL.Mobile { public static class GraphQLService { static readonly Lazy<GraphQLHttpClient> _clientHolder = new Lazy<GraphQLHttpClient>(CreateGraphQLClient); static GraphQLHttpClient Client => _clientHolder.Value; public static async IAsyncEnumerable<DogImagesModel> GetDogImages() { var graphQLRequest = new GraphQLRequest { Query = "query { dogs { avatarUrl, birthDate, breed, coatColor, imagesList, title, websiteUrl } }" }; var gitHubUserResponse = await AttemptAndRetry(() => Client.SendQueryAsync(graphQLRequest)).ConfigureAwait(false); foreach (var dogImageModel in gitHubUserResponse.GetDataFieldAs<IEnumerable<DogImagesModel>>("dogs")) yield return dogImageModel; } static GraphQLHttpClient CreateGraphQLClient() => new GraphQLHttpClient(new GraphQLHttpClientOptions { EndPoint = new Uri(BackendConstants.GraphQLApiUrl), #if !DEBUG HttpMessageHandler = new ModernHttpClient.NativeMessageHandler() #endif }); static async Task<GraphQLResponse> AttemptAndRetry(Func<Task<GraphQLResponse>> action, int numRetries = 2) { var response = await Policy.Handle<Exception>().WaitAndRetryAsync(numRetries, pollyRetryAttempt).ExecuteAsync(action).ConfigureAwait(false); if (response.Errors != null && response.Errors.Count() > 1) throw new AggregateException(response.Errors.Select(x => new GraphQLException(x))); if (response.Errors != null && response.Errors.Count() is 1) throw new GraphQLException(response.Errors.First()); return response; static TimeSpan pollyRetryAttempt(int attemptNumber) => TimeSpan.FromSeconds(Math.Pow(2, attemptNumber)); } } }
37.754386
152
0.687732
[ "MIT" ]
gilbreis/DotNetGraphQL
Source/DotNetGraphQL.Mobile/Services/GraphQLService.cs
2,154
C#
 using System; namespace Samarium.PluginFramework.Plugin { using Samarium.PluginFramework.Command; using Samarium.PluginFramework.Rest; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Description; using System.Text; using System.Threading.Tasks; /// <summary> /// Defines the basic structure of the main class of a Samarium plugin. /// Every plugin for Samarium must contain a single point of entry where the object /// inherits this interface (more specifically the Plugin abstract class). /// </summary> public interface IPlugin { /// <summary> /// Attempts to get a command from this plugin. /// </summary> /// <param name="command">The command to retrieve.</param> /// <returns>The command.</returns> ICommand GetCommand(ICommand command); /// <summary> /// Attempts to get a command from this plugin. /// </summary> /// <param name="commandTag">The command to retrieve.</param> /// <returns>The command.</returns> ICommand GetCommand(string commandTag); /// <summary> /// Gets a value indicating whether the inheriting plugin contains /// a given command. /// </summary> /// <param name="command">A command to check against.</param> /// <returns><code >true</code> if the command was found in this plugin.</returns> bool HasCommand(ICommand command); /// <summary> /// Gets a value indicating whether the inheriting plugin contains a given command. /// </summary> /// <param name="commandTag">A command to check against.</param> /// <returns><code >true</code> if the command was found in this plugin.</returns> bool HasCommand(string commandTag); /// <summary> /// Gets or sets a value indicating whether a plugin will log to its respective log file or not. /// </summary> bool LogToFile { get; set; } /// <summary> /// Gets or sets a value indicating whether a plugin will log to the console or not. /// </summary> bool LogToConsole { get; set; } /// <summary> /// Method called by main system once the plugin has been successfully loaded. /// This method can then be used to initialise certain features that the plugin provides automatically, /// such as beginning a threaded operation, designed to live as long as the main system. /// </summary> void OnLoaded(); /// <summary> /// Plugin initialisation. /// Handles all plugin init routines and returns either one of two states. (See returns section) /// </summary> /// <returns> /// Returns <code >true</code> if plugin initialisation was successful, <code >false</code> otherwise. /// </returns> bool OnStart(); /// <summary> /// Plugin termination. /// Similar to <see cref="IDisposable.Dispose"/>. /// Frees resources and allows plugins (and thus the application) to cleany shut down. /// </summary> /// <returns><code >true</code> if plugin termination was successful. <code >false</code> otherwise.</returns> bool OnStop(); /// <summary> /// Gets the commands this plugin provides. /// </summary> List<ICommand> PluginCommands { get; } /// <summary> /// Gets the name of the plugin. /// Ideally has the name of the class inheriting this interface! /// </summary> string PluginName { get; } /// <summary> /// Retrieves the RESTful endpoints defined by this plugin which /// are then loaded in to the application's RESTful service. /// These endpoints MUST be defined before the plugin hits the <see cref="OnLoaded"/> method! /// </summary> List<IEndpointContainer> ServiceEndpointContainer { get; } } }
38.409524
118
0.611208
[ "BSD-3-Clause" ]
Beatsleigher/Samarium-PluginFramework
Samarium.PluginFramework/Source/Plugin/IPlugin.cs
4,035
C#
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class UnitTest { public List<Action> Tests = new List<Action>(){}; public UnitTest() { Tests.Add(Example0);Tests.Add(Example1);Tests.Add(Example2);Tests.Add(Example3);Tests.Add(Example4); } public void ManualTest(int low, int high) { Console.WriteLine("low:{0}", low); Console.WriteLine("high:{0}", high); int __result = new RabbitNumber().theCount(low, high); Console.WriteLine("__result:{0}", __result); } [TestMethod] public void Example0() { int low = 22; Console.WriteLine("low:{0}", low); int high = 22; Console.WriteLine("high:{0}", high); int __expected = 1; Console.WriteLine("__expected:{0}", __expected); int __result = new RabbitNumber().theCount(low, high); Console.WriteLine("__result:{0}", __result); Assert.AreEqual(__expected, __result); } [TestMethod] public void Example1() { int low = 484; Console.WriteLine("low:{0}", low); int high = 484; Console.WriteLine("high:{0}", high); int __expected = 0; Console.WriteLine("__expected:{0}", __expected); int __result = new RabbitNumber().theCount(low, high); Console.WriteLine("__result:{0}", __result); Assert.AreEqual(__expected, __result); } [TestMethod] public void Example2() { int low = 1; Console.WriteLine("low:{0}", low); int high = 58; Console.WriteLine("high:{0}", high); int __expected = 12; Console.WriteLine("__expected:{0}", __expected); int __result = new RabbitNumber().theCount(low, high); Console.WriteLine("__result:{0}", __result); Assert.AreEqual(__expected, __result); } [TestMethod] public void Example3() { int low = 58; Console.WriteLine("low:{0}", low); int high = 484; Console.WriteLine("high:{0}", high); int __expected = 24; Console.WriteLine("__expected:{0}", __expected); int __result = new RabbitNumber().theCount(low, high); Console.WriteLine("__result:{0}", __result); Assert.AreEqual(__expected, __result); } [TestMethod] public void Example4() { int low = 1000000000; Console.WriteLine("low:{0}", low); int high = 1000000000; Console.WriteLine("high:{0}", high); int __expected = 1; Console.WriteLine("__expected:{0}", __expected); int __result = new RabbitNumber().theCount(low, high); Console.WriteLine("__result:{0}", __result); Assert.AreEqual(__expected, __result); } }
31.188889
113
0.593872
[ "MIT" ]
Camypaper/TopCoder
workspace/SRM 484/RabbitNumberUnitTest.cs
2,807
C#
using CryptoExchange.Net.Converters; using Newtonsoft.Json; namespace Bitfinex.Net.Objects { [JsonConverter(typeof(ArrayConverter))] public class BitfinexMarginBase { [ArrayProperty(0)] public string Type { get; set; } [ArrayProperty(1), JsonConverter(typeof(ArrayConverter))] public BitfinexMarginBaseInfo Data { get; set; } } [JsonConverter(typeof(ArrayConverter))] public class BitfinexMarginBaseInfo { [ArrayProperty(0)] public decimal UserProfitLoss { get; set; } [ArrayProperty(1)] public decimal UserSwapsAmount { get; set; } [ArrayProperty(2)] public decimal MarginBalance { get; set; } [ArrayProperty(3)] public decimal MarginNet { get; set; } } }
24.875
65
0.640704
[ "MIT" ]
WSakhana/Bitfinex.Net
Bitfinex.Net/Objects/BitfinexMarginBase.cs
798
C#
using System; using System.Collections.Generic; using System.Linq; using Autofac; using System.Web.Http.Dependencies; namespace PME.Web { public class HttpDependencyResolver : DisposableObject, IDependencyResolver { private readonly ILifetimeScope _scope; private class PerRequestContainer : DisposableObject, IDependencyScope { private readonly ILifetimeScope _perRequestScope; public PerRequestContainer(ILifetimeScope perRequestScope) { _perRequestScope = perRequestScope; } public virtual IEnumerable<object> GetServices(Type serviceType) { if (!_perRequestScope.IsRegistered(serviceType)) { return Enumerable.Empty<object>(); } Type type = typeof(IEnumerable<>).MakeGenericType(new[] { serviceType }); return _perRequestScope.Resolve(type) as IEnumerable<object>; } public virtual object GetService(Type serviceType) { return _perRequestScope.ResolveOptional(serviceType); } public override void Dispose(bool disposing) { if (disposing) { _perRequestScope.Dispose(); } base.Dispose(disposing); } } public HttpDependencyResolver(ILifetimeScope scope) { _scope = scope; } public IDependencyScope BeginScope() { return new PerRequestContainer(_scope.BeginLifetimeScope()); } public virtual IEnumerable<object> GetServices(Type serviceType) { if (!_scope.IsRegistered(serviceType)) { return Enumerable.Empty<object>(); } var type = typeof(IEnumerable<>).MakeGenericType(new[] { serviceType }); return _scope.Resolve(type) as IEnumerable<object>; } public virtual object GetService(Type serviceType) { return _scope.ResolveOptional(serviceType); } } }
27.098765
89
0.571754
[ "MIT" ]
PrattMiller/codeChallenge
source/_Core/PME.Web/HttpDependencyResolver.cs
2,197
C#
using System.Collections.Generic; using System.Web.Http; namespace AwesomeApi1.Controllers { [ServiceRequestActionFilter] public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] {"value1", "value2", nameof(AwesomeApi1)}; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } } }
21.486486
75
0.506918
[ "MIT" ]
ctigeek/ExampleServiceFabric
src/AwesomeApi1/Controllers/ValuesController.cs
797
C#
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BeetleX.FastHttpApi.Data { public class DataContxt : IDataContext { private Dictionary<string, object> mProperties = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); public string this[string name] { get { string result; TryGetString(name, out result); return result; } } public void Clear() { mProperties.Clear(); } public void SetValue(string name, object value) { mProperties[name] = value; } protected bool GetProperty(string name, out object value) { return mProperties.TryGetValue(name, out value); } public bool TryGetBoolean(string name, out bool value) { object data; value = false; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Boolean) { string str = token.ToObject<string>(); return bool.TryParse((string)str, out value); } value = token.ToObject<bool>(); return true; } else return Boolean.TryParse((string)data, out value); } return false; } public bool TryGetDateTime(string name, out DateTime value) { object data; value = DateTime.Now; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Date) { string str = token.ToObject<string>(); return DateTime.TryParse((string)str, out value); } value = token.ToObject<DateTime>(); return true; } else return DateTime.TryParse((string)data, out value); } return false; } public bool TryGetDecimal(string name, out decimal value) { object data; value = 0; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Float) { string str = token.ToObject<string>(); return decimal.TryParse((string)str, out value); } value = token.ToObject<decimal>(); return true; } else return decimal.TryParse((string)data, out value); } return false; } public bool TryGetDouble(string name, out double value) { object data; value = 0; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Float) { string str = token.ToObject<string>(); return double.TryParse((string)str, out value); } value = token.ToObject<double>(); return true; } else return double.TryParse((string)data, out value); } return false; } public bool TryGetFloat(string name, out float value) { object data; value = 0; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Float) { string str = token.ToObject<string>(); return float.TryParse((string)str, out value); } value = token.ToObject<float>(); return true; } else return float.TryParse((string)data, out value); } return false; } public bool TryGetInt(string name, out int value) { object data; value = 0; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Integer) { string str = token.ToObject<string>(); return int.TryParse((string)str, out value); } value = token.ToObject<int>(); return true; } else return int.TryParse((string)data, out value); } return false; } public bool TryGetLong(string name, out long value) { object data; value = 0; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Integer) { string str = token.ToObject<string>(); return long.TryParse((string)str, out value); } value = token.ToObject<long>(); return true; } else return long.TryParse((string)data, out value); } return false; } public bool TryGetShort(string name, out short value) { object data; value = 0; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Integer) { string str = token.ToObject<string>(); return short.TryParse((string)str, out value); } value = token.ToObject<short>(); return true; } else return short.TryParse((string)data, out value); } return false; } public bool TryGetUInt(string name, out uint value) { object data; value = 0; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Integer) { string str = token.ToObject<string>(); return uint.TryParse((string)str, out value); } value = token.ToObject<uint>(); return true; } else return uint.TryParse((string)data, out value); } return false; } public bool TryGetULong(string name, out ulong value) { object data; value = 0; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Integer) { string str = token.ToObject<string>(); return ulong.TryParse((string)str, out value); } value = token.ToObject<ulong>(); return true; } else return ulong.TryParse((string)data, out value); } return false; } public bool TryGetUShort(string name, out ushort value) { object data; value = 0; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Integer) { string str = token.ToObject<string>(); return ushort.TryParse((string)str, out value); } value = token.ToObject<ushort>(); return true; } else return ushort.TryParse((string)data, out value); } return false; } public bool TryGetByte(string name, out byte value) { object data; value = 0; if (GetProperty(name, out data)) { if (data is JProperty token) { if (token.Type != JTokenType.Integer) { string str = token.ToObject<string>(); return byte.TryParse((string)str, out value); } value = token.ToObject<byte>(); return true; } else return byte.TryParse((string)data, out value); } return false; } public bool TryGetChar(string name, out char value) { object data; value = (char)0; if (GetProperty(name, out data)) { if (data is JToken token) value = token.ToObject<char>(); else return char.TryParse((string)data, out value); } return false; } public bool TryGetString(string name, out string value) { object data; value = null; if (GetProperty(name, out data)) { if (data is JToken token) value = token.ToObject<string>(); else value = (string)data; return true; } return false; } public object GetObject(string name, Type type) { object value; if (GetProperty(name, out value)) { if (value is JToken token) { JProperty jProperty = token as JProperty; if (jProperty != null) return jProperty.Value.ToObject(type); else return token.ToObject(type); } else { if (value is string) { if (type.IsEnum) return Enum.Parse(type, (string)value); else return Newtonsoft.Json.JsonConvert.DeserializeObject((string)value, type); } return value; } } return null; } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (var item in mProperties) sb.AppendFormat("{0}={1}\r\n", item.Key, item.Value); return sb.ToString(); } public IDictionary<string, object> Copy() { Dictionary<string, object> result = new Dictionary<string, object>(); foreach (var item in mProperties) result[item.Key] = item.Value; return result; } } }
31.557029
122
0.412373
[ "Apache-2.0" ]
5118234/FastHttpApi
src/Data/DataContext.cs
11,899
C#
// <copyright file="DefaultBenchmarkBase.cs" company="Allan Hardy"> // Copyright (c) Allan Hardy. All rights reserved. // </copyright> using App.Metrics.Benchmarks.Configs; using App.Metrics.Benchmarks.Fixtures; using BenchmarkDotNet.Attributes; namespace App.Metrics.Benchmarks { [Config(typeof(DefaultConfig))] public abstract class DefaultBenchmarkBase { protected MetricsCoreTestFixture Fixture { get; private set; } [GlobalSetup] public virtual void Setup() { Fixture = new MetricsCoreTestFixture(); } } }
26.454545
70
0.690722
[ "Apache-2.0" ]
geffzhang/AppMetrics
benchmarks/App.Metrics.Benchmarks/DefaultBenchmarkBase.cs
584
C#
using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http.Results; using NSubstitute; using Sitecore.Hypermedia.Controllers; using Sitecore.Hypermedia.Model; using Sitecore.Hypermedia.Services; using Sitecore.Workflows; using Xunit; namespace Sitecore.Hypermedia.UnitTests.Controllers { public class WorkflowControllerTest { [Theory, DefaultAutoData] public void GetReturnsEmptyListIfNothingFound( IWorkflowService service, HttpRequestMessage request) { var sut = new WorkflowController(service) { Request = request }; var result = sut.Get(); Assert.Empty(result); } [Theory, DefaultAutoData] public void GetReturnsWorkflowListIfFound( IWorkflowService service, HttpRequestMessage request, IEnumerable<IWorkflow> workflows) { service.GetWorkflows().Returns(workflows); var sut = new WorkboxController(service) { Request = request }; var result = sut.Get(); Assert.True(result.ToList().Count == 3); } [Theory, DefaultAutoData] public void GetByUnknownWorkflowIdReturnsNotFoundResult( IWorkflowService service, string workflowId) { service.GetWorkflow(workflowId) .ReturnsForAnyArgs(Arg.Any<IWorkflow>()); var sut = new WorkflowController(service); var result = sut.Get(workflowId); Assert.IsType<NotFoundResult>(result); } [Theory, DefaultAutoData] public void GetByKnownWorkflowIdReturnsOkResult( IWorkflowService service, string workflowId, IWorkflow workflow, HttpRequestMessage request) { service.GetWorkflow(workflowId).Returns(workflow); var sut = new WorkflowController(service) { Request = request }; var result = sut.Get(workflowId); Assert.IsType<OkNegotiatedContentResult<WorkflowModel>>(result); } [Theory, DefaultAutoData] public void GetStatesReturnsEmptyListIfNoStatesFound( IWorkflowService service, string workflowId) { service.GetWorkflowStates(workflowId) .ReturnsForAnyArgs(Arg.Any<IEnumerable<WorkflowState>>()); var sut = new WorkflowController(service); var result = sut.GetStates(workflowId); Assert.Empty(result); } [Theory, DefaultAutoData] public void GetStatesReturnsValidStatesIfFound( HttpRequestMessage request, IWorkflowService service, string workflowId, IEnumerable<WorkflowState> states) { service.GetWorkflowStates(workflowId).Returns(states); var sut = new WorkflowController(service) { Request = request }; var actual = sut.GetStates(workflowId); Assert.Equal(3, actual.Count()); } } }
35.954545
77
0.608723
[ "MIT" ]
sergeyshushlyapin/SCH
test/Sitecore.Hypermedia.UnitTests/Controllers/WorkflowControllerTest.cs
3,166
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: Bots/Protos/command.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Protos.Expert.Command { /// <summary>Holder for reflection information generated from Bots/Protos/command.proto</summary> public static partial class CommandReflection { #region Descriptor /// <summary>File descriptor for Bots/Protos/command.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CommandReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChlCb3RzL1Byb3Rvcy9jb21tYW5kLnByb3RvEhVwcm90b3MuZXhwZXJ0LmNv", "bW1hbmQiEgoQR2V0TWFwRGltZW5zaW9ucyI3ChZHZXRNYXBEaW1lbnNpb25z", "UmVzdWx0Eg0KBXdpZHRoGAEgASgFEg4KBmhlaWdodBgCIAEoBSIKCghHZXRU", "aWxlcyI8Cg5HZXRUaWxlc1Jlc3VsdBIqCgV0aWxlcxgDIAMoCzIbLnByb3Rv", "cy5leHBlcnQuY29tbWFuZC5UaWxlIlEKBFRpbGUSCQoBeBgBIAEoBRIJCgF5", "GAIgASgFEg4KBmhlaWdodBgDIAEoBRIPCgd0ZXJyYWluGAQgASgFEhIKCnZp", "c2liaWxpdHkYBSABKAUiCgoIR2V0VW5pdHMiPAoOR2V0VW5pdHNSZXN1bHQS", "KgoFdW5pdHMYASADKAsyGy5wcm90b3MuZXhwZXJ0LmNvbW1hbmQuVW5pdCJi", "CgRVbml0EhAKCGVudGl0eUlkGAEgASgFEg4KBnVuaXRJZBgCIAEoBRISCgp2", "aXNpYmlsaXR5GAMgASgFEhEKCXBvc2l0aW9uWBgEIAEoBRIRCglwb3NpdGlv", "blkYBSABKAViBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Protos.Expert.Command.GetMapDimensions), global::Protos.Expert.Command.GetMapDimensions.Parser, null, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Protos.Expert.Command.GetMapDimensionsResult), global::Protos.Expert.Command.GetMapDimensionsResult.Parser, new[]{ "Width", "Height" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Protos.Expert.Command.GetTiles), global::Protos.Expert.Command.GetTiles.Parser, null, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Protos.Expert.Command.GetTilesResult), global::Protos.Expert.Command.GetTilesResult.Parser, new[]{ "Tiles" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Protos.Expert.Command.Tile), global::Protos.Expert.Command.Tile.Parser, new[]{ "X", "Y", "Height", "Terrain", "Visibility" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Protos.Expert.Command.GetUnits), global::Protos.Expert.Command.GetUnits.Parser, null, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Protos.Expert.Command.GetUnitsResult), global::Protos.Expert.Command.GetUnitsResult.Parser, new[]{ "Units" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Protos.Expert.Command.Unit), global::Protos.Expert.Command.Unit.Parser, new[]{ "EntityId", "UnitId", "Visibility", "PositionX", "PositionY" }, null, null, null, null) })); } #endregion } #region Messages public sealed partial class GetMapDimensions : pb::IMessage<GetMapDimensions> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GetMapDimensions> _parser = new pb::MessageParser<GetMapDimensions>(() => new GetMapDimensions()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetMapDimensions> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Protos.Expert.Command.CommandReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetMapDimensions() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetMapDimensions(GetMapDimensions other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetMapDimensions Clone() { return new GetMapDimensions(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetMapDimensions); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetMapDimensions other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetMapDimensions other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif } public sealed partial class GetMapDimensionsResult : pb::IMessage<GetMapDimensionsResult> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GetMapDimensionsResult> _parser = new pb::MessageParser<GetMapDimensionsResult>(() => new GetMapDimensionsResult()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetMapDimensionsResult> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Protos.Expert.Command.CommandReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetMapDimensionsResult() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetMapDimensionsResult(GetMapDimensionsResult other) : this() { width_ = other.width_; height_ = other.height_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetMapDimensionsResult Clone() { return new GetMapDimensionsResult(this); } /// <summary>Field number for the "width" field.</summary> public const int WidthFieldNumber = 1; private int width_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Width { get { return width_; } set { width_ = value; } } /// <summary>Field number for the "height" field.</summary> public const int HeightFieldNumber = 2; private int height_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Height { get { return height_; } set { height_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetMapDimensionsResult); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetMapDimensionsResult other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Width != other.Width) return false; if (Height != other.Height) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Width != 0) hash ^= Width.GetHashCode(); if (Height != 0) hash ^= Height.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Width != 0) { output.WriteRawTag(8); output.WriteInt32(Width); } if (Height != 0) { output.WriteRawTag(16); output.WriteInt32(Height); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Width != 0) { output.WriteRawTag(8); output.WriteInt32(Width); } if (Height != 0) { output.WriteRawTag(16); output.WriteInt32(Height); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Width != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Width); } if (Height != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Height); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetMapDimensionsResult other) { if (other == null) { return; } if (other.Width != 0) { Width = other.Width; } if (other.Height != 0) { Height = other.Height; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { Width = input.ReadInt32(); break; } case 16: { Height = input.ReadInt32(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { Width = input.ReadInt32(); break; } case 16: { Height = input.ReadInt32(); break; } } } } #endif } public sealed partial class GetTiles : pb::IMessage<GetTiles> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GetTiles> _parser = new pb::MessageParser<GetTiles>(() => new GetTiles()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetTiles> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Protos.Expert.Command.CommandReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetTiles() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetTiles(GetTiles other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetTiles Clone() { return new GetTiles(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetTiles); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetTiles other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetTiles other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif } public sealed partial class GetTilesResult : pb::IMessage<GetTilesResult> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GetTilesResult> _parser = new pb::MessageParser<GetTilesResult>(() => new GetTilesResult()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetTilesResult> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Protos.Expert.Command.CommandReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetTilesResult() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetTilesResult(GetTilesResult other) : this() { tiles_ = other.tiles_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetTilesResult Clone() { return new GetTilesResult(this); } /// <summary>Field number for the "tiles" field.</summary> public const int TilesFieldNumber = 3; private static readonly pb::FieldCodec<global::Protos.Expert.Command.Tile> _repeated_tiles_codec = pb::FieldCodec.ForMessage(26, global::Protos.Expert.Command.Tile.Parser); private readonly pbc::RepeatedField<global::Protos.Expert.Command.Tile> tiles_ = new pbc::RepeatedField<global::Protos.Expert.Command.Tile>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Protos.Expert.Command.Tile> Tiles { get { return tiles_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetTilesResult); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetTilesResult other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!tiles_.Equals(other.tiles_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= tiles_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else tiles_.WriteTo(output, _repeated_tiles_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { tiles_.WriteTo(ref output, _repeated_tiles_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += tiles_.CalculateSize(_repeated_tiles_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetTilesResult other) { if (other == null) { return; } tiles_.Add(other.tiles_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 26: { tiles_.AddEntriesFrom(input, _repeated_tiles_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 26: { tiles_.AddEntriesFrom(ref input, _repeated_tiles_codec); break; } } } } #endif } public sealed partial class Tile : pb::IMessage<Tile> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Tile> _parser = new pb::MessageParser<Tile>(() => new Tile()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Tile> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Protos.Expert.Command.CommandReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Tile() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Tile(Tile other) : this() { x_ = other.x_; y_ = other.y_; height_ = other.height_; terrain_ = other.terrain_; visibility_ = other.visibility_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Tile Clone() { return new Tile(this); } /// <summary>Field number for the "x" field.</summary> public const int XFieldNumber = 1; private int x_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int X { get { return x_; } set { x_ = value; } } /// <summary>Field number for the "y" field.</summary> public const int YFieldNumber = 2; private int y_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Y { get { return y_; } set { y_ = value; } } /// <summary>Field number for the "height" field.</summary> public const int HeightFieldNumber = 3; private int height_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Height { get { return height_; } set { height_ = value; } } /// <summary>Field number for the "terrain" field.</summary> public const int TerrainFieldNumber = 4; private int terrain_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Terrain { get { return terrain_; } set { terrain_ = value; } } /// <summary>Field number for the "visibility" field.</summary> public const int VisibilityFieldNumber = 5; private int visibility_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Visibility { get { return visibility_; } set { visibility_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Tile); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Tile other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (X != other.X) return false; if (Y != other.Y) return false; if (Height != other.Height) return false; if (Terrain != other.Terrain) return false; if (Visibility != other.Visibility) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (X != 0) hash ^= X.GetHashCode(); if (Y != 0) hash ^= Y.GetHashCode(); if (Height != 0) hash ^= Height.GetHashCode(); if (Terrain != 0) hash ^= Terrain.GetHashCode(); if (Visibility != 0) hash ^= Visibility.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (X != 0) { output.WriteRawTag(8); output.WriteInt32(X); } if (Y != 0) { output.WriteRawTag(16); output.WriteInt32(Y); } if (Height != 0) { output.WriteRawTag(24); output.WriteInt32(Height); } if (Terrain != 0) { output.WriteRawTag(32); output.WriteInt32(Terrain); } if (Visibility != 0) { output.WriteRawTag(40); output.WriteInt32(Visibility); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (X != 0) { output.WriteRawTag(8); output.WriteInt32(X); } if (Y != 0) { output.WriteRawTag(16); output.WriteInt32(Y); } if (Height != 0) { output.WriteRawTag(24); output.WriteInt32(Height); } if (Terrain != 0) { output.WriteRawTag(32); output.WriteInt32(Terrain); } if (Visibility != 0) { output.WriteRawTag(40); output.WriteInt32(Visibility); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (X != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(X); } if (Y != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Y); } if (Height != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Height); } if (Terrain != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Terrain); } if (Visibility != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Visibility); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Tile other) { if (other == null) { return; } if (other.X != 0) { X = other.X; } if (other.Y != 0) { Y = other.Y; } if (other.Height != 0) { Height = other.Height; } if (other.Terrain != 0) { Terrain = other.Terrain; } if (other.Visibility != 0) { Visibility = other.Visibility; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { X = input.ReadInt32(); break; } case 16: { Y = input.ReadInt32(); break; } case 24: { Height = input.ReadInt32(); break; } case 32: { Terrain = input.ReadInt32(); break; } case 40: { Visibility = input.ReadInt32(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { X = input.ReadInt32(); break; } case 16: { Y = input.ReadInt32(); break; } case 24: { Height = input.ReadInt32(); break; } case 32: { Terrain = input.ReadInt32(); break; } case 40: { Visibility = input.ReadInt32(); break; } } } } #endif } public sealed partial class GetUnits : pb::IMessage<GetUnits> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GetUnits> _parser = new pb::MessageParser<GetUnits>(() => new GetUnits()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetUnits> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Protos.Expert.Command.CommandReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUnits() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUnits(GetUnits other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUnits Clone() { return new GetUnits(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetUnits); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetUnits other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetUnits other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif } public sealed partial class GetUnitsResult : pb::IMessage<GetUnitsResult> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GetUnitsResult> _parser = new pb::MessageParser<GetUnitsResult>(() => new GetUnitsResult()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetUnitsResult> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Protos.Expert.Command.CommandReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUnitsResult() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUnitsResult(GetUnitsResult other) : this() { units_ = other.units_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUnitsResult Clone() { return new GetUnitsResult(this); } /// <summary>Field number for the "units" field.</summary> public const int UnitsFieldNumber = 1; private static readonly pb::FieldCodec<global::Protos.Expert.Command.Unit> _repeated_units_codec = pb::FieldCodec.ForMessage(10, global::Protos.Expert.Command.Unit.Parser); private readonly pbc::RepeatedField<global::Protos.Expert.Command.Unit> units_ = new pbc::RepeatedField<global::Protos.Expert.Command.Unit>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Protos.Expert.Command.Unit> Units { get { return units_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetUnitsResult); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetUnitsResult other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!units_.Equals(other.units_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= units_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else units_.WriteTo(output, _repeated_units_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { units_.WriteTo(ref output, _repeated_units_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += units_.CalculateSize(_repeated_units_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetUnitsResult other) { if (other == null) { return; } units_.Add(other.units_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { units_.AddEntriesFrom(input, _repeated_units_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { units_.AddEntriesFrom(ref input, _repeated_units_codec); break; } } } } #endif } public sealed partial class Unit : pb::IMessage<Unit> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Unit> _parser = new pb::MessageParser<Unit>(() => new Unit()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Unit> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Protos.Expert.Command.CommandReflection.Descriptor.MessageTypes[7]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Unit() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Unit(Unit other) : this() { entityId_ = other.entityId_; unitId_ = other.unitId_; visibility_ = other.visibility_; positionX_ = other.positionX_; positionY_ = other.positionY_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Unit Clone() { return new Unit(this); } /// <summary>Field number for the "entityId" field.</summary> public const int EntityIdFieldNumber = 1; private int entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "unitId" field.</summary> public const int UnitIdFieldNumber = 2; private int unitId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int UnitId { get { return unitId_; } set { unitId_ = value; } } /// <summary>Field number for the "visibility" field.</summary> public const int VisibilityFieldNumber = 3; private int visibility_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Visibility { get { return visibility_; } set { visibility_ = value; } } /// <summary>Field number for the "positionX" field.</summary> public const int PositionXFieldNumber = 4; private int positionX_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int PositionX { get { return positionX_; } set { positionX_ = value; } } /// <summary>Field number for the "positionY" field.</summary> public const int PositionYFieldNumber = 5; private int positionY_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int PositionY { get { return positionY_; } set { positionY_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Unit); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Unit other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (EntityId != other.EntityId) return false; if (UnitId != other.UnitId) return false; if (Visibility != other.Visibility) return false; if (PositionX != other.PositionX) return false; if (PositionY != other.PositionY) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (EntityId != 0) hash ^= EntityId.GetHashCode(); if (UnitId != 0) hash ^= UnitId.GetHashCode(); if (Visibility != 0) hash ^= Visibility.GetHashCode(); if (PositionX != 0) hash ^= PositionX.GetHashCode(); if (PositionY != 0) hash ^= PositionY.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (EntityId != 0) { output.WriteRawTag(8); output.WriteInt32(EntityId); } if (UnitId != 0) { output.WriteRawTag(16); output.WriteInt32(UnitId); } if (Visibility != 0) { output.WriteRawTag(24); output.WriteInt32(Visibility); } if (PositionX != 0) { output.WriteRawTag(32); output.WriteInt32(PositionX); } if (PositionY != 0) { output.WriteRawTag(40); output.WriteInt32(PositionY); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (EntityId != 0) { output.WriteRawTag(8); output.WriteInt32(EntityId); } if (UnitId != 0) { output.WriteRawTag(16); output.WriteInt32(UnitId); } if (Visibility != 0) { output.WriteRawTag(24); output.WriteInt32(Visibility); } if (PositionX != 0) { output.WriteRawTag(32); output.WriteInt32(PositionX); } if (PositionY != 0) { output.WriteRawTag(40); output.WriteInt32(PositionY); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (EntityId != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(EntityId); } if (UnitId != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(UnitId); } if (Visibility != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Visibility); } if (PositionX != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PositionX); } if (PositionY != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PositionY); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Unit other) { if (other == null) { return; } if (other.EntityId != 0) { EntityId = other.EntityId; } if (other.UnitId != 0) { UnitId = other.UnitId; } if (other.Visibility != 0) { Visibility = other.Visibility; } if (other.PositionX != 0) { PositionX = other.PositionX; } if (other.PositionY != 0) { PositionY = other.PositionY; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { EntityId = input.ReadInt32(); break; } case 16: { UnitId = input.ReadInt32(); break; } case 24: { Visibility = input.ReadInt32(); break; } case 32: { PositionX = input.ReadInt32(); break; } case 40: { PositionY = input.ReadInt32(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { EntityId = input.ReadInt32(); break; } case 16: { UnitId = input.ReadInt32(); break; } case 24: { Visibility = input.ReadInt32(); break; } case 32: { PositionX = input.ReadInt32(); break; } case 40: { PositionY = input.ReadInt32(); break; } } } } #endif } #endregion } #endregion Designer generated code
31.866258
223
0.648185
[ "MIT" ]
01010100b/AoE2Lib
AoE2Lib/Bots/Protos/Command.cs
51,942
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Foundation; using UIKit; namespace Xamarin.Essentials { public static partial class AppActions { internal const string Type = "XE_APP_ACTION_TYPE"; internal static bool PlatformIsSupported => Platform.HasOSVersion(9, 0); static Task<IEnumerable<AppAction>> PlatformGetAsync() { if (!IsSupported) throw new FeatureNotSupportedException(); return Task.FromResult(UIApplication.SharedApplication.ShortcutItems.Select(s => s.ToAppAction())); } static Task PlatformSetAsync(IEnumerable<AppAction> actions) { if (!IsSupported) throw new FeatureNotSupportedException(); UIApplication.SharedApplication.ShortcutItems = actions.Select(a => a.ToShortcutItem()).ToArray(); return Task.CompletedTask; } internal static AppAction ToAppAction(this UIApplicationShortcutItem shortcutItem) { string id = null; if (shortcutItem.UserInfo.TryGetValue((NSString)"id", out var idObj)) id = idObj?.ToString(); string icon = null; if (shortcutItem.UserInfo.TryGetValue((NSString)"icon", out var iconObj)) icon = iconObj?.ToString(); return new AppAction(id, shortcutItem.LocalizedTitle, shortcutItem.LocalizedSubtitle, icon); } static UIApplicationShortcutItem ToShortcutItem(this AppAction action) { var keys = new List<NSString>(); var values = new List<NSObject>(); // id keys.Add((NSString)"id"); values.Add((NSString)action.Id); // icon if (!string.IsNullOrEmpty(action.Icon)) { keys.Add((NSString)"icon"); values.Add((NSString)action.Icon); } return new UIApplicationShortcutItem( AppActions.Type, action.Title, action.Subtitle, action.Icon != null ? UIApplicationShortcutIcon.FromTemplateImageName(action.Icon) : null, new NSDictionary<NSString, NSObject>(keys.ToArray(), values.ToArray())); } } }
26.722222
102
0.726611
[ "MIT" ]
dhindrik/maui
src/Essentials/src/Xamarin.Essentials/AppActions/AppActions.ios.cs
1,926
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; using Aop.Api.Domain; namespace Aop.Api.Response { /// <summary> /// AlipayBossOrderDiagnosisGetResponse. /// </summary> public class AlipayBossOrderDiagnosisGetResponse : AopResponse { /// <summary> /// 诊断模型 /// </summary> [XmlArray("diagnosis_result")] [XmlArrayItem("diagnosis_info")] public List<DiagnosisInfo> DiagnosisResult { get; set; } } }
24.857143
67
0.622605
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Response/AlipayBossOrderDiagnosisGetResponse.cs
530
C#
using System; using System.Runtime.InteropServices; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp.Core { internal static unsafe class UnSafeNativeMethods { private const string libgit2 = "git2"; [DllImport(libgit2)] internal static extern int git_reference_list(out git_strarray array, RepositorySafeHandle repo, GitReferenceType flags); [DllImport(libgit2)] internal static extern int git_remote_list(out git_strarray array, RepositorySafeHandle repo); [DllImport(libgit2)] internal static extern int git_tag_list(out git_strarray array, RepositorySafeHandle repo); [DllImport(libgit2)] internal static extern void git_strarray_free(ref git_strarray array); #region Nested type: git_strarray internal struct git_strarray { public sbyte** strings; public UIntPtr size; } #endregion } }
28.029412
129
0.69255
[ "MIT" ]
improvedk/libgit2sharp
LibGit2Sharp/Core/UnSafeNativeMethods.cs
955
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""c0d21ef9ba207c335d8347e5172fce1d:2778""}]")] public class MusicOnHoldSourceRead21ExternalSource { private BroadWorksConnector.Ocip.Models.AccessDeviceEndpointWithPortNumberRead _accessDeviceEndpoint; [XmlElement(ElementName = "accessDeviceEndpoint", IsNullable = false, Namespace = "")] [Group(@"c0d21ef9ba207c335d8347e5172fce1d:2778")] public BroadWorksConnector.Ocip.Models.AccessDeviceEndpointWithPortNumberRead AccessDeviceEndpoint { get => _accessDeviceEndpoint; set { AccessDeviceEndpointSpecified = true; _accessDeviceEndpoint = value; } } [XmlIgnore] protected bool AccessDeviceEndpointSpecified { get; set; } } }
30.973684
130
0.680544
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/MusicOnHoldSourceRead21ExternalSource.cs
1,177
C#
// ReSharper disable once RedundantUsingDirective // Used to warn the player in big red letters in debug mode using System.Linq; using Content.Server.Administration; using Content.Shared.Administration; using Robust.Server.Player; using Robust.Shared.Console; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Timing; using Robust.Shared.Utility; namespace Content.Server.GameTicking.Commands { [AdminCommand(AdminFlags.Server | AdminFlags.Mapping)] class MappingCommand : IConsoleCommand { public string Command => "mapping"; public string Description => "Creates and teleports you to a new uninitialized map for mapping."; public string Help => $"Usage: {Command} <mapname> / {Command} <id> <mapname>"; public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; if (player == null) { shell.WriteLine("Only players can use this command"); return; } #if DEBUG shell.WriteError("WARNING: The server is using a debug build. You are risking losing your changes."); #endif var mapManager = IoCManager.Resolve<IMapManager>(); int mapId; string mapName; switch (args.Length) { case 1: if (player.AttachedEntity == null) { shell.WriteError("The map name argument cannot be omitted if you have no entity."); return; } mapId = (int) mapManager.NextMapId(); mapName = args[0]; break; case 2: if (!int.TryParse(args[0], out var id)) { shell.WriteError($"{args[0]} is not a valid integer."); return; } mapId = id; mapName = args[1]; break; default: shell.WriteLine(Help); return; } if (mapManager.MapExists(new MapId(mapId))) { shell.WriteLine($"Map {mapId} already exists"); return; } shell.ExecuteCommand("sudo cvar events.enabled false"); shell.ExecuteCommand($"addmap {mapId} false"); shell.ExecuteCommand($"loadbp {mapId} \"{CommandParsing.Escape(mapName)}\" true"); if (player.AttachedEntity?.Prototype?.ID != "AdminObserver") shell.ExecuteCommand("aghost"); shell.ExecuteCommand($"tp 0 0 {mapId}"); shell.RemoteExecuteCommand("showmarkers"); var newGrid = mapManager.GetAllGrids().OrderByDescending(g => (int) g.Index).First(); var pauseManager = IoCManager.Resolve<IPauseManager>(); pauseManager.SetMapPaused(newGrid.ParentMapId, true); shell.WriteLine($"Created unloaded map from file {mapName} with id {mapId}. Use \"savebp {newGrid.Index} foo.yml\" to save the new grid as a map."); } } }
35.195652
160
0.551266
[ "MIT" ]
Filatelele/space-station-14
Content.Server/GameTicking/Commands/MappingCommand.cs
3,238
C#
using System.Collections.Generic; using System.Xml.Serialization; using Alipay.AopSdk.Core.Domain; namespace Alipay.AopSdk.Core.Response { /// <summary> /// AlipayMarketingCardBenefitQueryResponse. /// </summary> public class AlipayMarketingCardBenefitQueryResponse : AopResponse { /// <summary> /// 会员卡模板外部权益列表 /// </summary> [XmlArray("mcard_template_benefit_query")] [XmlArrayItem("mcard_template_benefit_query")] public List<McardTemplateBenefitQuery> McardTemplateBenefitQuery { get; set; } } }
28.65
86
0.692845
[ "MIT" ]
leixf2005/Alipay.AopSdk.Core
Alipay.AopSdk.Core/Response/AlipayMarketingCardBenefitQueryResponse.cs
595
C#
using System; using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; namespace GraphQL.ApolloStudio { // https://josef.codes/custom-dictionary-string-object-jsonconverter-for-system-text-json/ public class DictionaryStringObjectJsonConverter : JsonConverter<Dictionary<string, object?>> { public override Dictionary<string, object?> Read(ref Utf8JsonReader reader, Type? typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartObject) { throw new JsonException($"JsonTokenType was of type {reader.TokenType}, only objects are supported"); } var dictionary = new Dictionary<string, object?>(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return dictionary; } if (reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException("JsonTokenType was not PropertyName"); } var propertyName = reader.GetString(); if (string.IsNullOrWhiteSpace(propertyName)) { throw new JsonException("Failed to get property name"); } reader.Read(); dictionary.Add(propertyName, ExtractValue(ref reader, options)); } return dictionary; } public override void Write(Utf8JsonWriter writer, Dictionary<string, object?> value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value, options); } private object? ExtractValue(ref Utf8JsonReader reader, JsonSerializerOptions options) { switch (reader.TokenType) { case JsonTokenType.String: if (reader.TryGetDateTime(out var date)) { return date; } return reader.GetString(); case JsonTokenType.False: return false; case JsonTokenType.True: return true; case JsonTokenType.Null: return null; case JsonTokenType.Number: if (reader.TryGetInt64(out var result)) { return result; } return reader.GetDecimal(); case JsonTokenType.StartObject: return Read(ref reader, null, options); case JsonTokenType.StartArray: var list = new List<object?>(); while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) { list.Add(ExtractValue(ref reader, options)); } return list; default: throw new JsonException($"'{reader.TokenType}' is not supported"); } } } }
35.730337
135
0.521698
[ "MIT" ]
mattjhosking/graphql-dotnet-apollo-studio
GraphQL.ApolloStudio/DictionaryStringObjectJsonConverter.cs
3,180
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TerrainFunction { // Palette static Color32 seaColorBottom = new Color32(0, 0, 28, 255); static Color32 seaColorTop = new Color32(0, 0, 255, 255); // As measured from sea level const float BeachLevel = 0.15f; ContourParameter contourParameter; TerrainParameter terrainParameter; float[,] contourLinesX; float[,] contourLinesZ; public float[,] VertexElevations { get; set; } public Color32[,] TileColors { get; set; } float minElevation, maxElevation; float Evaluate (float x) { float y = contourParameter.weight1 * (contourParameter.amplitude1 * Mathf.Sin (contourParameter.frequency1 * (x + contourParameter.offset1))) + contourParameter.weight2 * (contourParameter.amplitude2 * Mathf.Sin (contourParameter.frequency2 * (x + contourParameter.offset2))) + contourParameter.weight3 * (contourParameter.amplitude3 * Mathf.Sin (contourParameter.frequency3 * (x + contourParameter.offset3))) + contourParameter.weight4 * (contourParameter.amplitude4 * Mathf.Sin (contourParameter.frequency4 * (x + contourParameter.offset4))); return y; } static float CubicInterpolate( float y0,float y1, float y2,float y3, float mu) { // http://paulbourke.net/miscellaneous/interpolation/ float a0, a1, a2, a3, mu2; mu2 = mu * mu; // a0 = y3 - y2 - y0 + y1; // a1 = y0 - y1 - a0; // a2 = y2 - y0; // a3 = y1; // Catmull-Rom spline a0 = -0.5f*y0 + 1.5f*y1 - 1.5f*y2 + 0.5f*y3; a1 = y0 - 2.5f*y1 + 2f*y2 - 0.5f*y3; a2 = -0.5f*y0 + 0.5f*y2; a3 = y1; return (a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3); } void randomiseContour() { contourParameter.amplitude1 = Random.value; contourParameter.frequency1 = 1; contourParameter.offset1 = Random.value * Mathf.PI * 2; contourParameter.amplitude2 = Random.value; contourParameter.frequency2 = 2; contourParameter.offset2 = Random.value * Mathf.PI * 2; contourParameter.amplitude3 = Random.value; contourParameter.frequency3 = 4; contourParameter.offset3 = Random.value * Mathf.PI * 2; contourParameter.amplitude4 = Random.value; contourParameter.frequency4 = 8; contourParameter.offset4 = Random.value * Mathf.PI * 2; } void CreateContours() { int NofPoints = terrainParameter.nofTiles + 1; float x0 = -Mathf.PI; float z0 = -Mathf.PI; float dx = (2f * Mathf.PI) / terrainParameter.nofTiles; float dz = dx; int nofContourLines = terrainParameter.nofPatches + 1; contourParameter.weight1 = terrainParameter.weight1; contourParameter.weight2 = terrainParameter.weight2; contourParameter.weight3 = terrainParameter.weight3; contourParameter.weight4 = terrainParameter.weight4; // Contour lines X contourLinesX = new float[nofContourLines, NofPoints]; for (int p = 0; p < nofContourLines - 1; ++p) { randomiseContour (); float x = x0; for (int u = 0; u < NofPoints; ++u) { contourLinesX [p, u] = Evaluate (x); x += dx; } // x } // Contour lines Z contourLinesZ = new float [nofContourLines, NofPoints]; for (int o = 0; o < nofContourLines - 1; ++o) { randomiseContour (); float z = z0; for (int v = 0; v < NofPoints; ++v) { contourLinesZ [o, v] = Evaluate (z); z += dz; } // z } // Last contour line identical to first one for (int u = 0; u < NofPoints; ++u) { contourLinesX [nofContourLines - 1, u] = contourLinesX [0, u]; } // Last contour line identical to first one for (int v = 0; v < NofPoints; ++v) { contourLinesZ [nofContourLines - 1, v] = contourLinesZ [0, v]; } } void Elevate() { int nofPoints = terrainParameter.nofTiles + 1; float[,] vertexElevations = new float[nofPoints, nofPoints]; int nofTilesPerPatch = terrainParameter.nofTiles / terrainParameter.nofPatches; int nofContourLines = terrainParameter.nofPatches + 1; maxElevation = float.MinValue; minElevation = float.MaxValue; // Interpolate contour lines across X- and Z-direction (Y is up) for (int p = 0; p < terrainParameter.nofPatches; ++p) { for (int v = p * nofTilesPerPatch; v < p * nofTilesPerPatch + nofTilesPerPatch; ++v) { for (int o = 0; o < terrainParameter.nofPatches; ++o) { float t = (float)(v % nofTilesPerPatch) / (float)nofTilesPerPatch; for (int u = o * nofTilesPerPatch; u < o * nofTilesPerPatch + nofTilesPerPatch; ++u) { float s = (float)(u % nofTilesPerPatch) / (float)nofTilesPerPatch; int p1 = ((p - 1) % nofContourLines + nofContourLines) % nofContourLines; float y1 = CubicInterpolate (contourLinesX [p1, u], contourLinesX [p, u], contourLinesX [p + 1, u], contourLinesX [(p + 2) % nofContourLines, u], t); p1 = ((o - 1) % nofContourLines + nofContourLines) % nofContourLines; float y2 = CubicInterpolate (contourLinesZ [p1, v], contourLinesZ [o, v], contourLinesZ [o + 1, v], contourLinesZ [(o + 2) % nofContourLines, v], s); float y = y1 + y2; vertexElevations [u, v] = y; if (y > maxElevation) { maxElevation = y; } else if (y < minElevation) { minElevation = y; } } } } } // Border lines for (int u = 0; u < nofPoints; ++u) { vertexElevations [u, nofPoints - 1] = vertexElevations [u, 0]; } for (int v = 0; v < nofPoints; ++v) { vertexElevations [nofPoints - 1, v] = vertexElevations [0, v]; } this.VertexElevations = vertexElevations; } void Normalise() { int nofPoints = terrainParameter.nofTiles + 1; if (minElevation < -1.0f || maxElevation > 1.0f) { float[,] vertexElevations = this.VertexElevations; float max = Mathf.Max (Mathf.Abs (minElevation), Mathf.Abs (maxElevation)); for (int v = 0; v < nofPoints; ++v) { for (int u = 0; u < nofPoints; ++u) { vertexElevations [u, v] /= max; } } this.VertexElevations = vertexElevations; } } float Elevation (int s, int t) { float[,] vertexElevations = VertexElevations; float sum = vertexElevations [s, t] + vertexElevations [(s + 1) % terrainParameter.nofTiles, t] + vertexElevations [(s + 1) % terrainParameter.nofTiles, (t + 1) % terrainParameter.nofTiles] + vertexElevations [s, (t + 1) % terrainParameter.nofTiles]; return sum / 4f; } void Colorise() { Color32[,] tileColors = new Color32[terrainParameter.nofTiles, terrainParameter.nofTiles]; float[,] vertexElevations = this.VertexElevations; float difference = maxElevation - minElevation; for (int t = 0; t < terrainParameter.nofTiles; ++t) { for (int s = 0; s < terrainParameter.nofTiles; ++s) { if (vertexElevations [s, t] < terrainParameter.seaLevel) { // Sea float d = ((Elevation (s, t) - minElevation) / difference) / ((terrainParameter.seaLevel + 1.0f) / 2.0f); tileColors [s, t] = Color32.Lerp (seaColorBottom, seaColorTop, d); } else if (vertexElevations [s, t] < terrainParameter.seaLevel + BeachLevel) { // Beach tileColors [s, t] = Random.ColorHSV(0.15f, 0.16f, 1.0f, 1.0f, 1.0f, 1.0f); } else { // Land tileColors [s, t] = Random.ColorHSV(0.31f, 0.35f, 1.0f, 1.0f, 0.9f, 1.0f); } } } this.TileColors = tileColors; } public void Create(TerrainParameter terrainParameter) { this.terrainParameter = terrainParameter; CreateContours(); Elevate(); Normalise(); Colorise(); } }
29.661355
143
0.650504
[ "MIT" ]
till213/WorldDomination
Assets/Scripts/TerrainFunction.cs
7,447
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IWorkbookChartAxisFormatRequest. /// </summary> public partial interface IWorkbookChartAxisFormatRequest : IBaseRequest { /// <summary> /// Creates the specified WorkbookChartAxisFormat using PUT. /// </summary> /// <param name="workbookChartAxisFormatToCreate">The WorkbookChartAxisFormat to create.</param> /// <returns>The created WorkbookChartAxisFormat.</returns> System.Threading.Tasks.Task<WorkbookChartAxisFormat> CreateAsync(WorkbookChartAxisFormat workbookChartAxisFormatToCreate); /// <summary> /// Creates the specified WorkbookChartAxisFormat using PUT. /// </summary> /// <param name="workbookChartAxisFormatToCreate">The WorkbookChartAxisFormat to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookChartAxisFormat.</returns> System.Threading.Tasks.Task<WorkbookChartAxisFormat> CreateAsync(WorkbookChartAxisFormat workbookChartAxisFormatToCreate, CancellationToken cancellationToken); /// <summary> /// Deletes the specified WorkbookChartAxisFormat. /// </summary> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(); /// <summary> /// Deletes the specified WorkbookChartAxisFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken); /// <summary> /// Gets the specified WorkbookChartAxisFormat. /// </summary> /// <returns>The WorkbookChartAxisFormat.</returns> System.Threading.Tasks.Task<WorkbookChartAxisFormat> GetAsync(); /// <summary> /// Gets the specified WorkbookChartAxisFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookChartAxisFormat.</returns> System.Threading.Tasks.Task<WorkbookChartAxisFormat> GetAsync(CancellationToken cancellationToken); /// <summary> /// Updates the specified WorkbookChartAxisFormat using PATCH. /// </summary> /// <param name="workbookChartAxisFormatToUpdate">The WorkbookChartAxisFormat to update.</param> /// <returns>The updated WorkbookChartAxisFormat.</returns> System.Threading.Tasks.Task<WorkbookChartAxisFormat> UpdateAsync(WorkbookChartAxisFormat workbookChartAxisFormatToUpdate); /// <summary> /// Updates the specified WorkbookChartAxisFormat using PATCH. /// </summary> /// <param name="workbookChartAxisFormatToUpdate">The WorkbookChartAxisFormat to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookChartAxisFormat.</returns> System.Threading.Tasks.Task<WorkbookChartAxisFormat> UpdateAsync(WorkbookChartAxisFormat workbookChartAxisFormatToUpdate, CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IWorkbookChartAxisFormatRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWorkbookChartAxisFormatRequest Select(string value); } }
48.922222
167
0.657279
[ "MIT" ]
MIchaelMainer/GraphAPI
src/Microsoft.Graph/Requests/Generated/IWorkbookChartAxisFormatRequest.cs
4,403
C#
using System.Collections.Generic; using System.Threading.Tasks; using JetBrains.Annotations; using JoinRpg.DataModel; namespace JoinRpg.Services.Interfaces { public interface IFieldSetupService { Task UpdateFieldParams(UpdateFieldRequest request); Task<ProjectField> DeleteField(int projectId, int projectFieldId); Task DeleteField(ProjectField field); Task AddField(CreateFieldRequest request); Task CreateFieldValueVariant(CreateFieldValueVariantRequest request); Task UpdateFieldValueVariant(UpdateFieldValueVariantRequest request); Task<ProjectFieldDropdownValue> DeleteFieldValueVariant(int projectId, int projectFieldId, int valueId); Task MoveField(int projectid, int projectcharacterfieldid, short direction); Task MoveFieldVariant(int projectid, int projectFieldId, int projectFieldVariantId, short direction); Task CreateFieldValueVariants(int projectId, int projectFieldId, [NotNull] string valuesToAdd); Task MoveFieldAfter(int projectId, int projectFieldId, int? afterFieldId); } public abstract class FieldRequestBase { protected FieldRequestBase(int projectId, string name, string fieldHint, bool canPlayerEdit, bool canPlayerView, bool isPublic, MandatoryStatus mandatoryStatus, IReadOnlyCollection<int> showForGroups, bool validForNpc, bool includeInPrint, bool showForUnapprovedClaims, int price, string masterFieldHint, string programmaticValue) { ProjectId = projectId; Name = name; FieldHint = fieldHint; CanPlayerEdit = canPlayerEdit; CanPlayerView = canPlayerView; IsPublic = isPublic; MandatoryStatus = mandatoryStatus; ShowForGroups = showForGroups; ValidForNpc = validForNpc; IncludeInPrint = includeInPrint; ShowForUnapprovedClaims = showForUnapprovedClaims; Price = price; MasterFieldHint = masterFieldHint; ProgrammaticValue = programmaticValue; } public int ProjectId { get; } public string Name { get; } public string FieldHint { get; } public bool CanPlayerEdit { get; } public bool CanPlayerView { get; } public bool IsPublic { get; } public MandatoryStatus MandatoryStatus { get; } public IReadOnlyCollection<int> ShowForGroups { get; } public bool ValidForNpc { get; } public bool IncludeInPrint { get; } public bool ShowForUnapprovedClaims { get; } public int Price { get; } public string MasterFieldHint { get; } public string ProgrammaticValue { get; } } public sealed class CreateFieldRequest : FieldRequestBase { public ProjectFieldType FieldType { get; } public FieldBoundTo FieldBoundTo { get; } /// <inheritdoc /> public CreateFieldRequest(int projectId, ProjectFieldType fieldType, string name, string fieldHint, bool canPlayerEdit, bool canPlayerView, bool isPublic, FieldBoundTo fieldBoundTo, MandatoryStatus mandatoryStatus, IReadOnlyCollection<int> showForGroups, bool validForNpc, bool includeInPrint, bool showForUnapprovedClaims, int price, string masterFieldHint, string programmaticValue) : base(projectId, name, fieldHint, canPlayerEdit, canPlayerView, isPublic, mandatoryStatus, showForGroups, validForNpc, includeInPrint, showForUnapprovedClaims, price, masterFieldHint, programmaticValue) { FieldType = fieldType; FieldBoundTo = fieldBoundTo; } } public sealed class UpdateFieldRequest : FieldRequestBase { /// <inheritdoc /> public UpdateFieldRequest(int projectId, string name, string fieldHint, bool canPlayerEdit, bool canPlayerView, bool isPublic, MandatoryStatus mandatoryStatus, IReadOnlyCollection<int> showForGroups, bool validForNpc, bool includeInPrint, bool showForUnapprovedClaims, int price, string masterFieldHint, int projectFieldId, string programmaticValue) : base(projectId, name, fieldHint, canPlayerEdit, canPlayerView, isPublic, mandatoryStatus, showForGroups, validForNpc, includeInPrint, showForUnapprovedClaims, price, masterFieldHint, programmaticValue) { ProjectFieldId = projectFieldId; } public int ProjectFieldId { get; } } public abstract class FieldValueVariantRequestBase { public int ProjectId { get; } public int ProjectFieldId { get; } public string Label { get; } public string Description { get; } public string MasterDescription { get; } public string ProgrammaticValue { get; } public int Price { get; } public bool PlayerSelectable { get; } protected FieldValueVariantRequestBase(int projectId, string label, string description, int projectFieldId, string masterDescription, string programmaticValue, int price, bool playerSelectable) { ProjectId = projectId; Label = label; Description = description; ProjectFieldId = projectFieldId; MasterDescription = masterDescription; ProgrammaticValue = programmaticValue; Price = price; PlayerSelectable = playerSelectable; } } public class UpdateFieldValueVariantRequest : FieldValueVariantRequestBase { public UpdateFieldValueVariantRequest(int projectId, int projectFieldDropdownValueId, string label, string description, int projectFieldId, string masterDescription, string programmaticValue, int price, bool playerSelectable) : base(projectId, label, description, projectFieldId, masterDescription, programmaticValue, price, playerSelectable) { ProjectFieldDropdownValueId = projectFieldDropdownValueId; } public int ProjectFieldDropdownValueId { get; } } public class CreateFieldValueVariantRequest : FieldValueVariantRequestBase { public CreateFieldValueVariantRequest(int projectId, string label, string description, int projectFieldId, string masterDescription, string programmaticValue, int price, bool playerSelectable) : base(projectId, label, description, projectFieldId, masterDescription, programmaticValue, price, playerSelectable) { } } }
31.301205
84
0.584809
[ "MIT" ]
FulcrumVlsM/joinrpg-net
JoinRpg.Services.Interfaces/IFieldSetupService.cs
7,794
C#
//==================================================================================================================== // Copyright (c) 2013 IdeaBlade //==================================================================================================================== // 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. //==================================================================================================================== // USE OF THIS SOFTWARE IS GOVERENED BY THE LICENSING TERMS WHICH CAN BE FOUND AT // http://cocktail.ideablade.com/licensing //==================================================================================================================== using System; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; namespace DomainModel { [DataContract(IsReference = true)] public abstract class EntityBase { [DataMember] [ConcurrencyCheck] public int RowVersion { get; internal set; } } [DataContract(IsReference = true)] public abstract class AuditEntityBase : EntityBase { [DataMember] public DateTime Created { get; set; } [DataMember] public string CreatedUser { get; set; } [DataMember] public DateTime Modified { get; set; } [DataMember] public string ModifyUser { get; set; } } }
42.952381
120
0.51663
[ "MIT" ]
rmarmer1/Breeze
Samples/TempHire/DomainModel/EntityBase.cs
1,806
C#
// // GenericEqualityComparer.cs // // Author: // Jim Borden <jim.borden@couchbase.com> // // Copyright (c) 2015 Couchbase, 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. // using System; using System.Collections.Generic; namespace Couchbase.Lite { /// <summary> /// A simple equality comparer that just calls default functions /// </summary> [Serializable] public sealed class GenericEqualityComparer <T> : EqualityComparer <T> where T : IEquatable <T> { #pragma warning disable 1591 public override int GetHashCode (T obj) { if (obj == null) { return 0; } return obj.GetHashCode (); } public override bool Equals (T x, T y) { if (x == null) { return y == null; } return x.Equals (y); } #pragma warning restore 1591 } }
26.232143
101
0.62015
[ "Apache-2.0" ]
APXLabs/couchbase-lite-net
src/Couchbase.Lite.Shared/Util/GenericEqualityComparer.cs
1,471
C#
// Copyright 2020 New Relic, Inc. All rights reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Threading.Tasks; using NewRelic.Agent.Extensions.Providers.Wrapper; using NewRelic.Agent.Extensions.Parsing; using NewRelic.Agent.Api; namespace NewRelic.Providers.Wrapper.MongoDb26 { public class MongoCollectionImplWrapper : IWrapper { private const string WrapperName = "MongoCollectionImplWrapper"; public bool IsTransactionRequired => true; public CanWrapResponse CanWrap(InstrumentedMethodInfo methodInfo) { return new CanWrapResponse(WrapperName.Equals(methodInfo.RequestedWrapperName)); } public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction) { var operation = instrumentedMethodCall.MethodCall.Method.MethodName; var caller = instrumentedMethodCall.MethodCall.InvocationTarget; var collectionNamespace = MongoDbHelper.GetCollectionNamespacePropertyFromGeneric(caller); var model = MongoDbHelper.GetCollectionName(collectionNamespace); var database = MongoDbHelper.GetDatabaseFromGeneric(caller); ConnectionInfo connectionInfo = MongoDbHelper.GetConnectionInfoFromDatabase(database); var segment = transaction.StartDatastoreSegment(instrumentedMethodCall.MethodCall, new ParsedSqlStatement(DatastoreVendor.MongoDB, model, operation), isLeaf: true, connectionInfo: connectionInfo); if (!operation.EndsWith("Async", StringComparison.OrdinalIgnoreCase)) { return Delegates.GetDelegateFor(segment); } return Delegates.GetAsyncDelegateFor<Task>(agent, segment, true); } } }
40.130435
148
0.728602
[ "Apache-2.0" ]
JoshuaColeman/newrelic-dotnet-agent
src/Agent/NewRelic/Agent/Extensions/Providers/Wrapper/MongoDb26/MongoCollectionImplWrapper.cs
1,846
C#
#pragma checksum "/Users/christian/Desktop/repos/OSX .Net Core App/Views/Shared/Error.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "583387379a597938339285f5a623245873b0a91c" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared_Error), @"mvc.1.0.view", @"/Views/Shared/Error.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Shared/Error.cshtml", typeof(AspNetCore.Views_Shared_Error))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "/Users/christian/Desktop/repos/OSX .Net Core App/Views/_ViewImports.cshtml" using OSX_.Net_Core_App; #line default #line hidden #line 2 "/Users/christian/Desktop/repos/OSX .Net Core App/Views/_ViewImports.cshtml" using OSX_.Net_Core_App.Models; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"583387379a597938339285f5a623245873b0a91c", @"/Views/Shared/Error.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"71adc358eb37d62b8408b25763e94e2e7e72366f", @"/Views/_ViewImports.cshtml")] public class Views_Shared_Error : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<ErrorViewModel> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #line 2 "/Users/christian/Desktop/repos/OSX .Net Core App/Views/Shared/Error.cshtml" ViewData["Title"] = "Error"; #line default #line hidden BeginContext(64, 120, true); WriteLiteral("\r\n<h1 class=\"text-danger\">Error.</h1>\r\n<h2 class=\"text-danger\">An error occurred while processing your request.</h2>\r\n\r\n"); EndContext(); #line 9 "/Users/christian/Desktop/repos/OSX .Net Core App/Views/Shared/Error.cshtml" if (Model.ShowRequestId) { #line default #line hidden BeginContext(214, 52, true); WriteLiteral(" <p>\r\n <strong>Request ID:</strong> <code>"); EndContext(); BeginContext(267, 15, false); #line 12 "/Users/christian/Desktop/repos/OSX .Net Core App/Views/Shared/Error.cshtml" Write(Model.RequestId); #line default #line hidden EndContext(); BeginContext(282, 19, true); WriteLiteral("</code>\r\n </p>\r\n"); EndContext(); #line 14 "/Users/christian/Desktop/repos/OSX .Net Core App/Views/Shared/Error.cshtml" } #line default #line hidden BeginContext(304, 562, true); WriteLiteral(@" <h3>Development Mode</h3> <p> Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred. </p> <p> <strong>Development environment should not be enabled in deployed applications</strong>, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>, and restarting the application. </p> "); EndContext(); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ErrorViewModel> Html { get; private set; } } } #pragma warning restore 1591
48.923913
382
0.721395
[ "MIT" ]
chris-cata/dotnet-lab
src/obj/Debug/netcoreapp2.1/Razor/Views/Shared/Error.g.cshtml.cs
4,501
C#
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.4 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ using System; using System.Runtime.InteropServices; namespace Noesis { public class Int16KeyFrame : Freezable { internal new static Int16KeyFrame CreateProxy(IntPtr cPtr, bool cMemoryOwn) { return new Int16KeyFrame(cPtr, cMemoryOwn); } internal Int16KeyFrame(IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) { } internal static HandleRef getCPtr(Int16KeyFrame obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } protected Int16KeyFrame() { } public static DependencyProperty KeyTimeProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.Int16KeyFrame_KeyTimeProperty_get(); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public static DependencyProperty ValueProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.Int16KeyFrame_ValueProperty_get(); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public KeyTime KeyTime { set { NoesisGUI_PINVOKE.Int16KeyFrame_KeyTime_set(swigCPtr, ref value); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif } get { IntPtr ret = NoesisGUI_PINVOKE.Int16KeyFrame_KeyTime_get(swigCPtr); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif if (ret != IntPtr.Zero) { return Marshal.PtrToStructure<KeyTime>(ret); } else { return new KeyTime(); } } } public short Value { set { NoesisGUI_PINVOKE.Int16KeyFrame_Value_set(swigCPtr, value); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif } get { short ret = NoesisGUI_PINVOKE.Int16KeyFrame_Value_get(swigCPtr); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return ret; } } new internal static IntPtr GetStaticType() { IntPtr ret = NoesisGUI_PINVOKE.Int16KeyFrame_GetStaticType(); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return ret; } } }
31.137255
114
0.683249
[ "MIT" ]
suggestbot-wearable-text-entry-system/SuggestBot_GazeAssistedTyping
Assets/Plugins/NoesisGUI/Scripts/Proxies/Int16KeyFrame.cs
3,176
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace Services.Analytics.Models { public partial class ZetronContext : DbContext { public virtual DbSet<ZetronMstIncidents> ZetronMstIncidents { get; set; } public virtual DbSet<ZetronTrnFrames> ZetronTrnFrames { get; set; } public virtual DbSet<ZetronTrnFrameTags> ZetronTrnFrameTags { get; set; } public virtual DbSet<ZetronTrnMediaDetails> ZetronTrnMediaDetails { get; set; } public virtual DbSet<Tags> TagSummary { get; set; } public virtual DbSet<ZetronTrnDroneLocations> ZetronTrnDroneLocations { get; set; } public ZetronContext(DbContextOptions<ZetronContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<ZetronMstIncidents>(entity => { entity.HasKey(e => e.IncidentId); entity.Property(e => e.IncidentId).HasColumnName("IncidentID"); entity.Property(e => e.Description) .HasMaxLength(255) .IsUnicode(false); entity.Property(e => e.Location) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.ReportedOn).HasColumnType("datetime"); entity.Property(e => e.Title) .IsRequired() .HasMaxLength(255) .IsUnicode(false); }); modelBuilder.Entity<ZetronTrnFrames>(entity => { entity.HasKey(e => e.FrameId); entity.Property(e => e.FrameId).HasColumnName("FrameID"); entity.Property(e => e.FrameTime).HasColumnType("datetime"); entity.Property(e => e.MediaId).HasColumnName("MediaID"); entity.HasOne(d => d.Media) .WithMany(p => p.ZetronTrnFrames) .HasForeignKey(d => d.MediaId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_ZetronTrnFrames_ZetronTrnMediaDetails"); }); modelBuilder.Entity<ZetronTrnFrameTags>(entity => { entity.HasKey(e => e.TagId); entity.Property(e => e.TagId).HasColumnName("TagID"); entity.Property(e => e.FrameId).HasColumnName("FrameID"); entity.Property(e => e.Tag) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.HasOne(d => d.Frame) .WithMany(p => p.ZetronTrnFrameTags) .HasForeignKey(d => d.FrameId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_ZetronTrnFrameTags_ZetronTrnFrames"); }); modelBuilder.Entity<ZetronTrnMediaDetails>(entity => { entity.HasKey(e => e.MediaId); entity.Property(e => e.MediaId).HasColumnName("MediaID"); entity.Property(e => e.IncidentId).HasColumnName("IncidentID"); entity.Property(e => e.MediaUrl) .IsRequired() .HasColumnName("MediaURL") .IsUnicode(false); entity.Property(e => e.MediaSummaryUrl) .HasColumnName("MediaSummaryURL") .IsUnicode(false); entity.Property(e => e.Name) .HasColumnName("Name") .IsUnicode(false); entity.Property(e => e.PostedBy) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.PostedIon) .HasColumnName("PostedIOn") .HasColumnType("datetime"); entity.HasOne(d => d.Incident) .WithMany(p => p.ZetronTrnMediaDetails) .HasForeignKey(d => d.IncidentId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_ZetronTrnMediaDetails_ZetronMstIncidents"); }); modelBuilder.Entity<ZetronTrnDroneLocations>(entity => { entity.HasKey(e => e.LocationID); entity.Property(e => e.LocationID).HasColumnName("LocationID"); entity.Property(e => e.MediaID).HasColumnName("MediaID"); entity.Property(e => e.Temperature) .HasColumnName("Temperature") .HasColumnType("decimal"); entity.Property(e => e.Humidity) .HasColumnName("Humidity") .HasColumnType("decimal"); entity.Property(e => e.WindSpeed) .HasColumnName("WindSpeed") .HasColumnType("decimal"); entity.Property(e => e.DewPoint) .HasColumnName("DewPoint") .HasColumnType("decimal"); entity.Property(e => e.Summary) .HasColumnName("Summary") .IsUnicode(false); entity.Property(e => e.WindDirection) .HasColumnName("WindDirection") .IsUnicode(false); entity.Property(e => e.Longitude) .HasColumnName("Longitude") .HasColumnType("decimal"); entity.Property(e => e.Latitude) .HasColumnName("Latitude") .HasColumnType("decimal"); entity.HasOne(d => d.Media) .WithMany(p => p.ZetronTrnDroneLocations) .HasForeignKey(d => d.MediaID) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_ZetronTrnDroneLocations_ZetronTrnMediaDetails"); }); } } }
36.845238
91
0.516317
[ "MIT" ]
loganathanav/Cognitive-Services
Web Services/Services.Analytics/Services.Analytics/Models/ZetronContext.cs
6,192
C#
// Copyright (c) 2018 Alexander Bogomoletz // // 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 UnityEditor; using UnityEngine; namespace Yamly.UnityEditor { public static class YamlyEditorPrefs { private const string IsAssemblyBuildPendingKey = "{FBC14339-7B8D-4D00-9CAF-3EAAD8D2CD75}"; private const string AssetsImportContextKey = "{912CECC2-21F9-4A5C-8C39-4F72867076C8}"; public static bool IsAssemblyBuildPending { get { return EditorPrefs.GetBool(IsAssemblyBuildPendingKey, false); } internal set { EditorPrefs.SetBool(IsAssemblyBuildPendingKey, value); } } public static bool IsAssetsImportPending => !string.IsNullOrEmpty(EditorPrefs.GetString(AssetsImportContextKey, null)); internal static YamlyPostprocessAssetsContext AssetImportContext { get { var json = EditorPrefs.GetString(AssetsImportContextKey, null); return string.IsNullOrEmpty(json) ? null : JsonUtility.FromJson<YamlyPostprocessAssetsContext>(json); } set { var json = value == null ? null : JsonUtility.ToJson(value); EditorPrefs.SetString(AssetsImportContextKey, json); } } public static void Clear() { EditorPrefs.DeleteKey(IsAssemblyBuildPendingKey); EditorPrefs.DeleteKey(AssetsImportContextKey); } } }
41.311475
127
0.695635
[ "MIT" ]
incoboggart/Yamly
TestUnityProjects/Empty/Assets/Yamly/Editor/UnityEditor/YamlyEditorPrefs.cs
2,522
C#
using FubuMVC.Core.View.Model; using FubuMVC.Razor.RazorModel; using FubuTestingSupport; using NUnit.Framework; using Rhino.Mocks; namespace FubuMVC.Razor.Tests.RazorModel { [TestFixture] public class LayoutAttacherTester : InteractionContext<MasterAttacher<IRazorTemplate>> { private AttachRequest<IRazorTemplate> _request; private ViewDescriptor<IRazorTemplate> _viewDescriptor; private Parsing _parsing; private IRazorTemplate _template; protected override void beforeEach() { _template = new Template("b/a.cshtml", "b", "c"); _template.Descriptor = _viewDescriptor = new ViewDescriptor<IRazorTemplate>(_template) { ViewModel = typeof (ProductModel) }; _parsing = new Parsing { Master = "application", ViewModelType = _viewDescriptor.ViewModel.FullName }; _request = new AttachRequest<IRazorTemplate> { Template = _template, Logger = MockFor<ITemplateLogger>() }; MockFor<IParsingRegistrations<IRazorTemplate>>().Expect(x => x.ParsingFor(_template)).Return(_parsing); } [Test] public void if_template_is_valid_for_attachment_then_attacher_is_applied() { ClassUnderTest.CanAttach(_request).ShouldBeTrue(); } [Test] public void if_explicit_empty_master_then_binder_is_not_applied() { _parsing.Master = string.Empty; ClassUnderTest.CanAttach(_request).ShouldBeFalse(); } [Test] public void if_descriptor_is_not_viewdescriptor_then_binder_is_not_applied() { _template.Descriptor = new NulloDescriptor(); ClassUnderTest.CanAttach(_request).ShouldBeFalse(); } [Test] public void if_view_model_type_is_null_and_master_is_invalid_then_binder_is_not_applied_1() { _viewDescriptor.ViewModel = null; _parsing.Master = null; ClassUnderTest.CanAttach(_request).ShouldBeFalse(); } [Test] public void if_view_model_type_is_null_and_master_is_invalid_then_binder_is_not_applied_2() { _viewDescriptor.ViewModel = null; _parsing.Master = ""; ClassUnderTest.CanAttach(_request).ShouldBeFalse(); } [Test] public void if_master_is_already_set_binder_is_not_applied() { _viewDescriptor.Master = MockFor<IRazorTemplate>(); ClassUnderTest.CanAttach(_request).ShouldBeFalse(); } [Test] public void does_not_bind_partials() { _request.Template = new Template("b/_partial.cshtml", "b", "c"); ClassUnderTest.CanAttach(_request).ShouldBeFalse(); } [Test] public void when_master_is_not_set_fallback_is_used_by_locator() { _parsing.Master = null; ClassUnderTest.Attach(_request); MockFor<ISharedTemplateLocator<IRazorTemplate>>() .AssertWasCalled(x => x.LocateMaster(ClassUnderTest.MasterName, _template)); } [Test] public void when_master_is_set_it_is_used_by_locator() { ClassUnderTest.Attach(_request); MockFor<ISharedTemplateLocator<IRazorTemplate>>() .AssertWasCalled(x => x.LocateMaster(_parsing.Master, _template)); } [Test] public void when_no_master_is_found_it_is_logged() { ClassUnderTest.Attach(_request); verify_log_contains("not found"); } [Test] public void when_master_is_found_it_is_set_on_view_descriptor() { master_is_found(); ClassUnderTest.Attach(_request); _viewDescriptor.Master.ShouldEqual(MockFor<IRazorTemplate>()); } [Test] public void when_master_is_found_it_is_logged() { master_is_found(); ClassUnderTest.Attach(_request); verify_log_contains("found at"); } [Test] public void if_template_is_default_master_and_layout_is_itself_then_attacher_is_not_applied() { ((ITemplateFile)_template).FilePath = "One/Shared/" + _parsing.Master + ".cshtml"; ClassUnderTest.CanAttach(_request).ShouldBeFalse(); } private void verify_log_contains(string snippet) { MockFor<ITemplateLogger>() .AssertWasCalled(x => x.Log(Arg<IRazorTemplate>.Is.Equal(_template), Arg<string>.Matches(s => s.Contains(snippet)))); } private void master_is_found() { MockFor<ISharedTemplateLocator<IRazorTemplate>>() .Stub(x => x.LocateMaster(_parsing.Master, _template)) .Return(MockFor<IRazorTemplate>()); } } }
32.941558
145
0.606544
[ "Apache-2.0" ]
ketiko/fubumvc
src/FubuMVC.Razor.Tests/RazorModel/LayoutAttacherTester.cs
5,075
C#
using System.Collections.Generic; using HotReloading.Syntax; namespace HotReloading.Core { public class CodeChange { public List<Method> Methods { get; set; } = new List<Method>(); } }
20.6
71
0.679612
[ "MIT" ]
andreinitescu/HotReloading
Core/HotReloading.Core/CodeChange.cs
208
C#
// Copyright (c) Aksio Insurtech. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text.Json.Nodes; namespace Aksio.Cratis.Events.Store; /// <summary> /// Defines the system for working with event sequences. /// </summary> public interface IEventSequences { /// <summary> /// Append a single event to the event store. /// </summary> /// <param name="eventSequenceId">The <see cref="EventSequenceId"/> representing the event sequence to append to.</param> /// <param name="sequenceNumber">The unique <see cref="EventSequenceNumber">sequence number</see> within the event sequence.</param> /// <param name="eventSourceId">The <see cref="EventSourceId"/> to append for.</param> /// <param name="eventType">The <see cref="EventType">type of event</see> to append.</param> /// <param name="validFrom">Optional date and time for when the compensation is valid from. </param> /// <param name="content">The JSON payload of the event.</param> /// <returns>Awaitable <see cref="Task"/>.</returns> Task Append(EventSequenceId eventSequenceId, EventSequenceNumber sequenceNumber, EventSourceId eventSourceId, EventType eventType, DateTimeOffset validFrom, JsonObject content); /// <summary> /// Compensate a single event to the event store. /// </summary> /// <param name="eventSequenceId">The <see cref="EventSequenceId"/> representing the event sequence to append to.</param> /// <param name="sequenceNumber">The unique <see cref="EventSequenceNumber">sequence number</see> within the event sequence.</param> /// <param name="eventType">The <see cref="EventType">type of event</see> to append.</param> /// <param name="validFrom">Optional date and time for when the compensation is valid from. </param> /// <param name="content">The JSON payload of the event.</param> /// <returns>Awaitable <see cref="Task"/>.</returns> Task Compensate(EventSequenceId eventSequenceId, EventSequenceNumber sequenceNumber, EventType eventType, DateTimeOffset validFrom, JsonObject content); }
59.472222
181
0.71929
[ "MIT" ]
aksio-insurtech/Cratis
Source/Kernel/Store/Shared/IEventSequences.cs
2,141
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http; using Microsoft.Rest.Serialization; using Microsoft.CognitiveServices.ContentModerator.Models; using Microsoft.CognitiveServices.ContentModerator; using System.Threading; using System.IO; using System.Configuration; using System.Reflection; //using d = System.Drawing; using ContentModeratorTests.Data; using Newtonsoft.Json; using Xunit; namespace ContentModeratorTests.Helpers { public class Utilities { public Utilities(){} public void WaitUntilCompleted(Task tsk) { while (!tsk.IsCompleted) Thread.Sleep(1000); } public static string GetCorrectedDeploymentDirectory(string path) { if (path.Contains("TestResults")) { int startIndex = path.IndexOf("TestResults"), LastIndex = path.IndexOf(@"\Out"); LastIndex = LastIndex==-1?path.IndexOf(@"\out"):LastIndex; string sToReplace = path.Substring(startIndex + 11, LastIndex +4 - startIndex - 11); path = path.Replace(sToReplace, "").Replace("TestResults", @"CMTests"); } return path; } public static Stream GenerateStreamFromString(string s) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(s); writer.Flush(); stream.Position = 0; return stream; } private static void SetObjectProperty(string propertyName, string value, object obj) { PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName); // make sure object has the property we are after if (propertyInfo != null) { propertyInfo.SetValue(obj, value, null); } } public static string GetContentTypeByFile(string filenameWithExtension) { try { string contentType = MIMETypes.IMAGE_JPEG.GetDescription(); if(filenameWithExtension.Contains(".jpg") || filenameWithExtension.Contains(".jpeg")) contentType = MIMETypes.IMAGE_JPEG.GetDescription(); if (filenameWithExtension.Contains(".bmp")) contentType = MIMETypes.IMAGE_BMP.GetDescription(); if (filenameWithExtension.Contains(".gif")) contentType = MIMETypes.IMAGE_GIF.GetDescription(); if (filenameWithExtension.Contains(".png")) contentType = MIMETypes.IMAGE_PNG.GetDescription(); if (filenameWithExtension.Contains(".tif") || filenameWithExtension.Contains(".tiff")) contentType = "image\tiff"; return contentType; } catch (Exception e) { throw new Exception("Unable to file content Type"); } } public static string GetDirectoryByFile(string fileName) => fileName.Contains("128px") ? @"TestDataSources\LT128pxImages\" : (fileName.Contains("4MB") ? @"TestDataSources\GT4MBImages\" : @"TestDataSources\NormalImages\"); public static bool VerifyImageListContents(Body expected, ImageList actual) { try { return expected.Name.Equals(actual.Name, StringComparison.InvariantCultureIgnoreCase) && expected.Metadata.KeyOne.Equals(actual.Metadata.KeyOne, StringComparison.InvariantCultureIgnoreCase) && expected.Metadata.KeyTwo.Equals(actual.Metadata.KeyTwo, StringComparison.InvariantCultureIgnoreCase); } catch (Exception e) { throw new Exception("Unable to verify Image list correctness. Error:" + e.InnerException.Message); } } public static bool VerifyImageListContents(ImageList expected, ImageList actual) { try { return expected.Id == Convert.ToDouble(actual.Id) && expected.Name.Equals(actual.Name, StringComparison.InvariantCultureIgnoreCase) && expected.Metadata.KeyOne.Equals(actual.Metadata.KeyOne, StringComparison.InvariantCultureIgnoreCase) && expected.Metadata.KeyTwo.Equals(actual.Metadata.KeyTwo, StringComparison.InvariantCultureIgnoreCase); } catch (Exception e) { throw new Exception("Unable to verify Image list correctness. Error:" + e.InnerException.Message); } } public static bool VerifyTermListContents(Body expected, TermList actual) { try { return expected.Name.Equals(actual.Name, StringComparison.InvariantCultureIgnoreCase) && expected.Metadata.KeyOne.Equals(actual.Metadata.KeyOne, StringComparison.InvariantCultureIgnoreCase) && expected.Metadata.KeyTwo.Equals(actual.Metadata.KeyTwo, StringComparison.InvariantCultureIgnoreCase); } catch (Exception e) { throw new Exception("Unable to verify Term list correctness. Error:" + e.InnerException.Message); } } public static bool VerifyTermListContents(TermList expected, TermList actual) { try { return expected.Id == Convert.ToDouble(actual.Id) && expected.Name.Equals(actual.Name, StringComparison.InvariantCultureIgnoreCase) && expected.Metadata.KeyOne.Equals(actual.Metadata.KeyOne, StringComparison.InvariantCultureIgnoreCase) && expected.Metadata.KeyTwo.Equals(actual.Metadata.KeyTwo, StringComparison.InvariantCultureIgnoreCase); } catch (Exception e) { throw new Exception("Unable to verify Term list correctness. Error:" + e.InnerException.Message); } } public static bool VerifyRefreshIndex(RefreshIndex b, bool isContentId = true, bool isTrackingid = true, bool isStatus = true, bool isAdvancedInfo = false) { bool isExpected = false; try { if (isContentId == (b.ContentSourceId != null)) if (isTrackingid == (b.TrackingId != null)) if (isStatus == (b.Status.Code == 3000)) if (isAdvancedInfo == (b.AdvancedInfo.Count != 0)) isExpected = true; return isExpected; } catch (Exception e) { throw new Exception("Unable to verify Status object. Error:" + e.InnerException.Message); } } public static bool VerifyEvaluate(Evaluate eval, bool isCacheImage = false) { string error = ""; try { if (eval.AdultClassificationScore == null || eval.AdultClassificationScore == 0.0) error = "Adult Classification Score is null or 0.0"; if (eval.IsImageAdultClassified == null ) error += "IsImageAdultClassification is null "; if (eval.RacyClassificationScore == null || eval.RacyClassificationScore == 0.0) error += "RacyClassificationScore is null or 0.0 "; if (eval.IsImageRacyClassified == null) error += "IsImageRacyClassified is null "; if (eval.Result == null) error += "Result is null "; if (!VerifyStatus(eval.Status)) error += TestBase.ErrorMessage; if (eval.TrackingId == null) error += "TrackingId is null "; if (eval.AdvancedInfo == null) error += "Advanced Info is null "; if (isCacheImage) VerifyCacheId(isCacheImage, eval.CacheID); TestBase.ErrorMessage = error; return string.IsNullOrEmpty(TestBase.ErrorMessage); } catch (Exception e) { TestBase.ErrorMessage += "Unable to verify the Evaulate Result. Error:" + e.InnerException.Message; return false; } } public static bool VerifyFoundFaces(FoundFaces ff, bool isCacheImage = false) { string error = ""; try { if (isCacheImage) VerifyCacheId(isCacheImage, ff.CacheId); if (ff.Faces == null) error = "Faces object is null "; if (ff.Count == null) error += "No faces detected"; if (ff.Result == null) error += "Result is null"; if (!VerifyStatus(ff.Status)) error += TestBase.ErrorMessage; if (ff.TrackingId == null) error += "TrackingId is null"; if (ff.AdvancedInfo == null) error += "Advanced Info is null"; TestBase.ErrorMessage = error; return string.IsNullOrEmpty(TestBase.ErrorMessage); } catch (Exception e) { TestBase.ErrorMessage += "Unable to verify the Find Faces Result. Error:" + e.InnerException.Message; return false; } } public static bool VerifyOCR(OCR ocr, bool isCacheImage = false,bool isEnhanced = false) { string error = ""; try { if (isCacheImage) VerifyCacheId(isCacheImage, ocr.CacheId); if (ocr.Candidates == null) error += "Candidates object is null "; if (isEnhanced) if (ocr.Candidates.Count <= 0) error += "Candidate(s) details not populated."; if (ocr.Language == null) error += "Language is null "; if (ocr.Metadata == null) error += "Metadata is null"; if (!VerifyStatus(ocr.Status)) error += TestBase.ErrorMessage; if (ocr.Text == null) error += "Text is null"; if (ocr.TrackingId == null) error += "Trackingid are null"; TestBase.ErrorMessage = error; return string.IsNullOrEmpty(TestBase.ErrorMessage); } catch (Exception e) { TestBase.ErrorMessage += "Unable to verify the Evaulate Result. Error:" + e.InnerException.Message; return false; } } public static bool VerifyMatchResponse(MatchResponse mat, bool isCacheImage = false) { string error = ""; try { if (isCacheImage) VerifyCacheId(isCacheImage, mat.CacheID); if (mat.IsMatch == null) error += "IsMatch is null"; if (mat.Matches == null) error += "Matches object is null"; else { foreach (Match m in mat.Matches) { if (m.MatchId == null) error += "MatchId is null"; if (m.Score == null) error += "Score is null"; if (m.Source == null) error += "Source is null"; if (m.MatchId == null) error += "MatchId is null"; } } if (!VerifyStatus(mat.Status)) error += TestBase.ErrorMessage; if (mat.TrackingId == null) error += "Trackingid is null"; TestBase.ErrorMessage = error; return string.IsNullOrEmpty(TestBase.ErrorMessage); } catch (Exception e) { TestBase.ErrorMessage += "Unable to verify the Match response . Error:" + e.InnerException.Message; return false; } } public static bool VerifyDetectLanguage(DetectedLanguage dl) { string error = ""; try { if (dl.DetectedLanguageProperty == null) error += "Detected Language is null"; if (!VerifyStatus(dl.Status)) error += TestBase.ErrorMessage; if (dl.TrackingId == null) error += "Trackingid is null"; TestBase.ErrorMessage = error; return string.IsNullOrEmpty(error); } catch (Exception e) { TestBase.ErrorMessage += "Unable to verify the detect language response . Error:" + e.InnerException.Message; return false; } } public static bool VerifyScreenText(Screen s,bool isAutoCorrect = false, bool isPII = false, bool isClassify = false) { string error = ""; try { //if (s.Misrepresentation == null) // error += " Misrepresentation is null"; if (isAutoCorrect) { if (s.NormalizedText.Equals(s.OriginalText, StringComparison.InvariantCultureIgnoreCase)) error += " Autocorrect did not happen."; if (string.IsNullOrEmpty(s.AutoCorrectedText)) error += " Autocorrected Text property is null or empty"; } if (isPII) if (s.PII == null) error += " PII is null"; else { if (s.PII.Email == null) error += " PII.Email is null"; if (s.PII.IPA == null) error += " PII.IPA is null"; if (s.PII.Phone == null) error += " PII.Phone is null"; if (s.PII.Address == null) error += " PII.Address is null"; } if (isClassify) if (s.Classification == null) error = " Classification is null"; else { if (s.Classification.Category1 == null) error += " Classification.Category1 Score is null"; if (s.Classification.Category2 == null) error += " Classification.Category2 Score is null"; if (s.Classification.Category3== null) error += " Classification.Category3 Score is null"; if (s.Classification.ReviewRecommended == null) error += " Classification.ReviewRecommended is null"; } if (s.Language == null) error += " Language is null"; if (s.NormalizedText == null) error += " Normal Text is null"; if (s.OriginalText == null) error += " Original Text is null"; if (s.Terms == null) error += " Terms object is null"; else { if (s.Terms.Count > 0) { if (s.Terms.Any(x => (x.Index == null || x.OriginalIndex == null || x.ListId == null || x.Term == null))) error += " Terms metadata Index or Original index or listId or term is null"; } } if (!VerifyStatus(s.Status)) error += TestBase.ErrorMessage; if (s.TrackingId == null) error += " Trackingid is null"; TestBase.ErrorMessage = error; return string.IsNullOrEmpty(error); } catch (Exception e) { TestBase.ErrorMessage += "Unable to verify the screentext response . Error:" + e.InnerException.Message; return false; } } public static bool VerifyAddImageResponse(Image img) { string error = ""; try { if (img.ContentId== null) error += "ContentId is null"; if (!VerifyStatus(img.Status)) error += TestBase.ErrorMessage; if (img.TrackingId == null) error += "Trackingid is null"; if (img.AdditionalInfo == null) error += "Aditional Info is null"; TestBase.ErrorMessage = error; return string.IsNullOrEmpty(error); } catch (Exception e) { TestBase.ErrorMessage += "Unable to verify the detect language response . Error:" + e.InnerException.Message; return false; } } public static bool VerifyCacheId(bool iscacheImage, string cacheid) { string error = ""; if (!string.IsNullOrEmpty(cacheid) != iscacheImage) error = $"Cache id is mismatch. IsCacheImage :{iscacheImage} Cacheid:{cacheid}"; TestBase.ErrorMessage += error; return string.IsNullOrEmpty(error); } public static bool VerifyStatus(Status s) { string error = ""; try { if (s != null) { if (s.Code != 3000) error += $"Status code mismatch . Actual<{s.Code}> Expected <'3000'>"; if (s.Description != "OK") error += $"Exception occures. Actual<{s.Description}> Expected <'OK'>"; if (!string.IsNullOrEmpty(s.Exception)) error += $"Exception occured. Actual<{s.Exception}> Expected <null>"; } else error += "Status is null"; TestBase.ErrorMessage = error; return string.IsNullOrEmpty(error); } catch (Exception e) { throw e; } } public static bool VerifyBadRequestResponse(BadRequestResponse br,ContentModeratorAPI api) { string error = ""; try { switch (api) { case ContentModeratorAPI.CREATE_IMAGE_LIST: break; case ContentModeratorAPI.UPDATE_IMAGE_LIST: break; case ContentModeratorAPI.GET_ALL_IMAGE_LIST: break; case ContentModeratorAPI.GET_DETAILS_IMAGE_LIST: break; case ContentModeratorAPI.DELETE_IMAGE_LIST: break; case ContentModeratorAPI.REFRESH_INDEX_IMAGE_LIST: break; case ContentModeratorAPI.CREATE_TERM_LIST: break; case ContentModeratorAPI.UPDATE_TERM_LIST: break; case ContentModeratorAPI.GET_ALL_TERM_LIST: break; case ContentModeratorAPI.GET_DETAILS_TERM_LIST: break; case ContentModeratorAPI.DELETE_TERM_LIST: break; case ContentModeratorAPI.REFRESH_INDEX_TERM_LIST: break; case ContentModeratorAPI.ADD_IMAGE: break; case ContentModeratorAPI.DELETE_IMAGE: break; case ContentModeratorAPI.DELETE_ALL_IMAGE: break; case ContentModeratorAPI.GET_ALL_IMAGES: break; case ContentModeratorAPI.ADD_TERM: break; case ContentModeratorAPI.DELETE_TERM: break; case ContentModeratorAPI.DELETE_ALL_TERM: break; case ContentModeratorAPI.GET_ALL_TERMS: break; case ContentModeratorAPI.EVALUATE: case ContentModeratorAPI.FIND_FACES: case ContentModeratorAPI.MATCH: case ContentModeratorAPI.OCR: if (!br.Message.Equals(ImageErrorMessages.IMAGE_SIZE_ERROR.GetDescription(),StringComparison.InvariantCultureIgnoreCase)) error += $"Error Message mismatch. Actual<{br.Message}> Expected<{ImageErrorMessages.IMAGE_SIZE_ERROR.GetDescription()}>"; if (!br.Errors[0].Title.Equals(ImageErrorMessages.IMAGE_SIZE_ERROR.GetDescription(), StringComparison.InvariantCultureIgnoreCase)) error += $"Errors object Title mismatch. Actual<{br.Errors[0].Title}> Expected<{ImageErrorMessages.IMAGE_SIZE_ERROR.GetDescription()}>"; if (br.TrackingId == null) error = $"Tracking id is null"; break; case ContentModeratorAPI.SCREEN_TEXT: break; case ContentModeratorAPI.DETECT_LANGUAGE: break; default: break; } TestBase.ErrorMessage = error; return string.IsNullOrEmpty(error); } catch (Exception e) { TestBase.ErrorMessage += $"Unable to verify BadRequestResponse. Response {JsonConvert.SerializeObject(br)}"; return false; } } #region EquateMethods public static bool EquateEval(Evaluate e1, Evaluate e2) { return e1.AdultClassificationScore.Equals(e2.AdultClassificationScore) && e1.IsImageAdultClassified.Equals(e2.IsImageAdultClassified) && e1.RacyClassificationScore.Equals(e2.RacyClassificationScore) && e1.IsImageRacyClassified.Equals(e2.IsImageRacyClassified) && e1.Result.Equals(e2.Result) && e1.AdvancedInfo.Equals(e2.AdvancedInfo) && e1.Status.Equals(e2.Status); } public static bool EquateFoundFaces(FoundFaces e1, FoundFaces e2) { return e1.Count.Equals(e2.Count) && e1.Faces.Equals(e2.Faces) && e1.Result.Equals(e2.Result) && e1.AdvancedInfo.Equals(e2.AdvancedInfo) && e1.Status.Equals(e2.Status); } public static bool EquateMatch(Match e1, Match e2) { return e1.Label.Equals(e2.Label) && e1.Score.Equals(e2.Score) && e1.Source.Equals(e2.Source) && e1.Tags.Count.Equals(e2.Tags.Count); } public static bool EquateOCR(OCR e1, OCR e2) { return e1.Candidates.Count.Equals(e2.Candidates.Count ) && e1.Language.Equals(e2.Language) && e1.Metadata.Equals(e2.Metadata) && e1.Text.Equals(e2.Text) && e1.Status.Equals(e2.Status); } #endregion #region Review public static bool VerifyJob(Content content, Job j) { string error = ""; try { if (j.Id == null) error += "Job id is null "; if (j.JobExecutionReport== null) error += $"JOb Execution Resport is null "; if (j.ResultMetaData == null) error += $"Metadata is null "; if (j.Type!= content.GetDescription()) error += $"Type mismatch,Actual{j.Type}, Expected {content.GetDescription()}"; if (j.WorkflowId== null) error += "Workflow id is null "; if (j.TeamName == null) error += "Team name is null "; if (j.Status == null) error += "Status is null "; if (j.ReviewId== null) error += "Review Id is null "; TestBase.ErrorMessage = $"{content.GetDescription()} job : " + (string.IsNullOrEmpty(j.Id) ? "" : j.Id) + error; return string.IsNullOrEmpty(error); } catch (Exception e) { throw e; } } public static bool VerifyReview(Content content,Review r ) { string error = ""; try { if (r.ReviewId == null) error += "Review id is null "; if (r.SubTeam == null) error += $"SubTeam is null "; if (r.Metadata == null) error += $"Metadata is null "; if (r.Type != content.GetDescription()) error += $"Type mismatch,Actual{r.Type}, Expected {content.GetDescription()}"; if (r.Content == null) error += "Content is null "; if (r.ContentId == null) error += "ContentId is null "; if (r.Status == null) error += "Status is null "; if (r.CreatedBy== null) error += "CreatedBy is null "; if (r.CreatedBy == null) error += "CreatedBy is null "; if (r.Status.Equals(ReviewStatus.COMPLETE.GetDescription())) if(r.ReviewerResultTags == null) error +="ReviewerResultTags is null "; TestBase.ErrorMessage = $"{content.GetDescription()} review : " + (string.IsNullOrEmpty(r.ReviewId) ? "" : r.ReviewId) + error; return string.IsNullOrEmpty(error); } catch (Exception e) { throw e; } } public static bool VerifyGetFrames(Frames fs) { string error = ""; try { if (fs.ReviewId == null) error += "Review Id is null"; if (fs.VideoFrames == null) error += "Video frames is null"; if (fs.VideoFrames.Count != 0) { foreach (Frame f in fs.VideoFrames) { if (f.FrameImage == null) error += " FrameImage is null"; if (f.Metadata == null) error += " Frame Metadata is null"; if (f.ReviewerResultTags == null) error += " ReviewerResultTags is null"; if (f.Timestamp == null) error += " Timestamp is null"; } } return string.IsNullOrEmpty(error); } catch (Exception e) { TestBase.ErrorMessage = error + e.InnerException; return false; } } #endregion } }
37.823056
229
0.490502
[ "MIT" ]
216Giorgiy/azure-sdk-for-net
src/SDKs/CognitiveServices/dataPlane/Vision/ContentModerator/ContentModerator.Tests/Helpers/Utilities.cs
28,218
C#
/* The MIT License (MIT) Copyright (c) 2015-2017 Secret Lab Pty. Ltd. and Yarn Spinner contributors. 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 UnityEngine; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using CsvHelper; namespace Yarn.Unity { [System.Serializable] public class LocalisedStringGroup { public SystemLanguage language; public TextAsset[] stringFiles; } /// DialogueRunners act as the interface between your game and YarnSpinner. /** Make our menu item slightly nicer looking */ [AddComponentMenu("Scripts/Yarn Spinner/Dialogue Runner")] public class DialogueRunner : MonoBehaviour { /// The JSON files to load the conversation from public TextAsset[] sourceText; /// The group of JSON files to be used for this language public LocalisedStringGroup[] stringGroups; /// Language debugging options public bool shouldOverrideLanguage = false; public SystemLanguage overrideLanguage = SystemLanguage.English; /// Our variable storage public Yarn.Unity.VariableStorageBehaviour variableStorage; /// The object that will handle the actual display and user input public Yarn.Unity.DialogueUIBehaviour dialogueUI; /// Which node to start from public string startNode = Yarn.Dialogue.DEFAULT_START; /// Whether we should start dialogue when the scene starts public bool startAutomatically = true; /// Tests to see if the dialogue is running public bool isDialogueRunning { get; private set; } public bool automaticCommands = true; /// Our conversation engine /** Automatically created on first access */ private Dialogue _dialogue; public Dialogue dialogue { get { if (_dialogue == null) { // Create the main Dialogue runner, and pass our variableStorage to it _dialogue = new Yarn.Dialogue (variableStorage); // Set up the logging system. _dialogue.LogDebugMessage = delegate (string message) { Debug.Log (message); }; _dialogue.LogErrorMessage = delegate (string message) { Debug.LogError (message); }; } return _dialogue; } } /// Start the dialogue void Start () { // Ensure that we have our Implementation object if (dialogueUI == null) { Debug.LogError ("Implementation was not set! Can't run the dialogue!"); return; } // And that we have our variable storage object if (variableStorage == null) { Debug.LogError ("Variable storage was not set! Can't run the dialogue!"); return; } // Ensure that the variable storage has the right stuff in it variableStorage.ResetToDefaults (); // Load all scripts if (sourceText != null) { foreach (var source in sourceText) { // load and compile the text dialogue.LoadString (source.text, source.name); } } if (startAutomatically) { StartDialogue(); } if (stringGroups != null) { // Load the string table for this language, if appropriate var stringsGroup = new List<LocalisedStringGroup>(stringGroups).Find( entry => entry.language == (shouldOverrideLanguage ? overrideLanguage : Application.systemLanguage) ); if (stringsGroup != null) { foreach (var table in stringsGroup.stringFiles) { this.AddStringTable(table.text); } } } } /// Add a string of text to a script public void AddScript(string text) { dialogue.LoadString(text); } /// Add a TextAsset to a script public void AddScript(TextAsset asset) { dialogue.LoadString(asset.text); } /// Loads a string table, replacing any existing strings with the same /// key. public void AddStringTable(Dictionary<string,string> stringTable) { dialogue.AddStringTable(stringTable); } /// Add a string of text to a table public void AddStringTable(string text) { // Create the dictionary that will contain these values var stringTable = new Dictionary<string,string>(); using (var reader = new System.IO.StringReader(text)) { using (var csv = new CsvHelper.CsvReader(reader)) { var records = csv.GetRecords<Yarn.LocalisedLine>(); foreach (var record in records) { stringTable[record.LineCode] = record.LineText; } } } AddStringTable(stringTable); } /// Add a TextAsset to a table public void AddStringTable(TextAsset text) { AddStringTable(text.text); } /// Destroy the variable store and start again public void ResetDialogue () { variableStorage.ResetToDefaults (); StartDialogue (); } /// Start the dialogue public void StartDialogue () { StartDialogue(startNode); } /// Start the dialogue from a given node public void StartDialogue (string startNode) { // Stop any processes that might be running already StopAllCoroutines (); dialogueUI.StopAllCoroutines (); // Get it going StartCoroutine (RunDialogue (startNode)); } IEnumerator RunDialogue (string startNode = "Start") { // Mark that we're in conversation. isDialogueRunning = true; // Signal that we're starting up. yield return StartCoroutine(this.dialogueUI.DialogueStarted()); // Get lines, options and commands from the Dialogue object, // one at a totalTimeInSeconds. foreach (Yarn.Dialogue.RunnerResult step in dialogue.Run(startNode)) { if (step is Yarn.Dialogue.LineResult) { // Wait for line to finish displaying var lineResult = step as Yarn.Dialogue.LineResult; yield return StartCoroutine (this.dialogueUI.RunLine (lineResult.line)); } else if (step is Yarn.Dialogue.OptionSetResult) { // Wait for user to finish picking an option var optionSetResult = step as Yarn.Dialogue.OptionSetResult; yield return StartCoroutine ( this.dialogueUI.RunOptions ( optionSetResult.options, optionSetResult.setSelectedOptionDelegate )); } else if (step is Yarn.Dialogue.CommandResult) { // Wait for command to finish running var commandResult = step as Yarn.Dialogue.CommandResult; if (DispatchCommand(commandResult.command.text) == true) { // command was dispatched } else { yield return StartCoroutine (this.dialogueUI.RunCommand (commandResult.command)); } } else if(step is Yarn.Dialogue.NodeCompleteResult) { // Wait for post-node action var nodeResult = step as Yarn.Dialogue.NodeCompleteResult; yield return StartCoroutine (this.dialogueUI.NodeComplete (nodeResult.nextNode)); } } // No more results! The dialogue is done. yield return StartCoroutine (this.dialogueUI.DialogueComplete ()); // Clear the 'is running' flag. We do this after DialogueComplete returns, // to allow totalTimeInSeconds for any animations that might run while transitioning // out of a conversation (ie letterboxing going away, etc) isDialogueRunning = false; } /// Clear the dialogue system public void Clear() { if (isDialogueRunning) { throw new System.InvalidOperationException("You cannot clear the dialogue system while a dialogue is running."); } dialogue.UnloadAll(); } /// Stop the dialogue public void Stop() { isDialogueRunning = false; dialogue.Stop(); } /// Test to see if a node name exists public bool NodeExists(string nodeName) { return dialogue.NodeExists(nodeName); } /// Return the current node name public string currentNodeName { get { return dialogue.currentNode; } } /// commands that can be automatically dispatched look like this: /// COMMANDNAME OBJECTNAME <param> <param> <param> ... /** We can dispatch this command if: * 1. it has at least 2 words * 2. the second word is the name of an object * 3. that object has components that have methods with the YarnCommand attribute that have the correct commandString set */ public bool DispatchCommand(string command) { var words = command.Split(' '); // need 2 parameters in order to have both a command name // and the name of an object to find if (words.Length < 2) return false; var commandName = words[0]; var objectName = words[1]; var sceneObject = GameObject.Find(objectName); // If we can't find an object, we can't dispatch a command if (sceneObject == null) return false; int numberOfMethodsFound = 0; List<string[]> errorValues = new List<string[]>(); List<string> parameters; if (words.Length > 2) { parameters = new List<string>(words); parameters.RemoveRange(0, 2); } else { parameters = new List<string>(); } // Find every MonoBehaviour (or subclass) on the object foreach (var component in sceneObject.GetComponents<MonoBehaviour>()) { var type = component.GetType(); // Find every method in this component foreach (var method in type.GetMethods()) { // Find the YarnCommand attributes on this method var attributes = (YarnCommandAttribute[]) method.GetCustomAttributes(typeof(YarnCommandAttribute), true); // Find the YarnCommand whose commandString is equal to the command name foreach (var attribute in attributes) { if (attribute.commandString == commandName) { var methodParameters = method.GetParameters(); bool paramsMatch = false; // Check if this is a params array if (methodParameters.Length == 1 && methodParameters[0].ParameterType.IsAssignableFrom(typeof(string[]))) { // Cool, we can send the command! string[][] paramWrapper = new string[1][]; paramWrapper[0] = parameters.ToArray(); method.Invoke(component, paramWrapper); numberOfMethodsFound++; paramsMatch = true; } // Otherwise, verify that this method has the right number of parameters else if (methodParameters.Length == parameters.Count) { paramsMatch = true; foreach (var paramInfo in methodParameters) { if (!paramInfo.ParameterType.IsAssignableFrom(typeof(string))) { Debug.LogErrorFormat(sceneObject, "Method \"{0}\" wants to respond to Yarn command \"{1}\", but not all of its parameters are strings!", method.Name, commandName); paramsMatch = false; break; } } if (paramsMatch) { // Cool, we can send the command! method.Invoke(component, parameters.ToArray()); numberOfMethodsFound++; } } //parameters are invalid, but name matches. if (!paramsMatch) { //save this error in case a matching command is never found. errorValues.Add(new string[] { method.Name, commandName, methodParameters.Length.ToString(), parameters.Count.ToString() }); } } } } } // Warn if we found multiple things that could respond // to this command. if (numberOfMethodsFound > 1) { Debug.LogWarningFormat(sceneObject, "The command \"{0}\" found {1} targets. " + "You should only have one - check your scripts.", command, numberOfMethodsFound); } else if (numberOfMethodsFound == 0) { //list all of the near-miss methods only if a proper match is not found, but correctly-named methods are. foreach (string[] errorVal in errorValues) { Debug.LogErrorFormat(sceneObject, "Method \"{0}\" wants to respond to Yarn command \"{1}\", but it has a different number of parameters ({2}) to those provided ({3}), or is not a string array!", errorVal[0], errorVal[1], errorVal[2], errorVal[3]); } } return numberOfMethodsFound > 0; } } /// Apply this attribute to methods in your scripts to expose /// them to Yarn. /** For example: * [YarnCommand("dosomething")] * void Foo() { * do something! * } */ public class YarnCommandAttribute : System.Attribute { public string commandString { get; private set; } public YarnCommandAttribute(string commandString) { this.commandString = commandString; } } /// Scripts that can act as the UI for the conversation should subclass this public abstract class DialogueUIBehaviour : MonoBehaviour { /// A conversation has started. public virtual IEnumerator DialogueStarted() { // Default implementation does nothing. yield break; } /// Display a line. public abstract IEnumerator RunLine (Yarn.Line line); /// Display the options, and call the optionChooser when done. public abstract IEnumerator RunOptions (Yarn.Options optionsCollection, Yarn.OptionChooser optionChooser); /// Perform some game-specific command. public abstract IEnumerator RunCommand (Yarn.Command command); /// The node has ended. public virtual IEnumerator NodeComplete(string nextNode) { // Default implementation does nothing. yield break; } /// The conversation has ended. public virtual IEnumerator DialogueComplete () { // Default implementation does nothing. yield break; } } /// Scripts that can act as a variable storage should subclass this public abstract class VariableStorageBehaviour : MonoBehaviour, Yarn.VariableStorage { /// Not implemented here public virtual void SetNumber (string variableName, float number) { throw new System.NotImplementedException (); } /// Not implemented here public virtual float GetNumber (string variableName) { throw new System.NotImplementedException (); } /// Get a value public virtual Value GetValue(string variableName) { return new Yarn.Value(this.GetNumber(variableName)); } /// Set a value public virtual void SetValue(string variableName, Value value) { this.SetNumber(variableName, value.AsNumber); } /// Not implemented here public virtual void Clear () { throw new System.NotImplementedException (); } public abstract void ResetToDefaults (); } }
37.420523
267
0.554791
[ "Unlicense" ]
rachel2386/Studio2Game
Assets/YarnSpinner/Code/DialogueRunner.cs
18,600
C#
using Idoit.API.Client.CMDB.Impact; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace IdoitUnitTests.CMDB { [TestClass] public class ImpactTest : IdoitTestBase { public ImpactTest() : base() { } //Read [TestMethod] public void ReadTest() { //Arrange var request = new IdoitImpactInstance(idoitClient); request.ObjectId = 10; request.RelationType = 10; var result = request.Read(); } } }
22.541667
63
0.563771
[ "MIT" ]
Kleinrotti/Idoit.API.Client
IdoitUnitTests/CMDB/Impact/ImpactTest.cs
543
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Repayabl.Models.DTOs { public class Room { [Key] public Guid Id { get; set; } [Required] [StringLength(10)] public string RoomNo { get; set; } public int? RoomFloorNo { get; set; } public Guid PropertyId { get; set; } public Guid? CurrentTenantId { get; set; } [Column(TypeName = "numeric(15, 2)")] public decimal MonthlyRent { get; set; } [Column(TypeName = "numeric(10, 2)")] public decimal ElectRate { get; set; } [Column(TypeName = "datetime")] public DateTime? LastBillPaidDate { get; set; } public Guid? LastPaidBillId { get; set; } } }
30.814815
55
0.615385
[ "MIT" ]
avikeid2007/Repayabl
Repayabl/Models/DTOs/Room.cs
834
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Reflection; using System.Security.Cryptography; public class EmbeddedAssembly { // Version 1.3 static Dictionary<string, Assembly> dic = null; public static void Load(string embeddedResource, string fileName) { if (dic == null) dic = new Dictionary<string, Assembly>(); byte[] ba = null; Assembly asm = null; Assembly curAsm = Assembly.GetExecutingAssembly(); //foreach (var item in curAsm.GetManifestResourceNames()) //{ // System.Windows.Forms.MessageBox.Show(item); //} using (Stream stm = curAsm.GetManifestResourceStream(embeddedResource)) { // Either the file is not existed or it is not mark as embedded resource if (stm == null) throw new Exception(embeddedResource + " is not found in Embedded Resources."); // Get byte[] from the file from embedded resource ba = new byte[(int)stm.Length]; stm.Read(ba, 0, (int)stm.Length); try { asm = Assembly.Load(ba); // Add the assembly/dll into dictionary dic.Add(asm.FullName, asm); return; } catch { // Purposely do nothing // Unmanaged dll or assembly cannot be loaded directly from byte[] // Let the process fall through for next part } } bool fileOk = false; string tempFile = ""; using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) { string fileHash = BitConverter.ToString(sha1.ComputeHash(ba)).Replace("-", string.Empty); ; tempFile = Path.GetTempPath() + fileName; if (File.Exists(tempFile)) { byte[] bb = File.ReadAllBytes(tempFile); string fileHash2 = BitConverter.ToString(sha1.ComputeHash(bb)).Replace("-", string.Empty); if (fileHash == fileHash2) { fileOk = true; } else { fileOk = false; } } else { fileOk = false; } } if (!fileOk) { System.IO.File.WriteAllBytes(tempFile, ba); } asm = Assembly.LoadFile(tempFile); dic.Add(asm.FullName, asm); } public static Assembly Get(string assemblyFullName) { if (dic == null || dic.Count == 0) return null; if (dic.ContainsKey(assemblyFullName)) return dic[assemblyFullName]; return null; } }
25.699029
102
0.564035
[ "MIT" ]
Attracted/FunProjects
JumpMan/JumpMan/EmbeddedAssembly.cs
2,649
C#
// Copyright © 2021 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Razor.TagHelpers; namespace Platformus.Core.Backend { [RestrictChildren("cell", "image-cell", "buttons-cell", "partial")] public class RowTagHelper : TagHelper { public string Class { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = TagNames.TR; output.Attributes.SetAttribute(AttributeNames.Class, "table__row" + (string.IsNullOrEmpty(this.Class) ? null : $" {this.Class}")); } } }
35.789474
136
0.725
[ "Apache-2.0" ]
Platformus/Platformus
src/Platformus.Core.Backend/Areas/Backend/TagHelpers/Tables/RowTagHelper.cs
683
C#
using System; using System.IO; using System.Threading.Tasks; using Datadog.Trace.HttpOverStreams; using Datadog.Trace.HttpOverStreams.HttpContent; namespace Datadog.Trace.Agent.Transports { internal class HttpStreamRequest : IApiRequest { /// <summary> /// This value is greater than any reasonable response we would receive from the agent. /// It is smaller than the internal default of 81920 /// https://source.dot.net/#System.Private.CoreLib/Stream.cs,122 /// It is a multiple of 4096. /// </summary> private const int ResponseReadBufferSize = 12_228; private readonly Uri _uri; private readonly DatadogHttpClient _client; private readonly IStreamFactory _streamFactory; private readonly HttpHeaders _headers = new HttpHeaders(); public HttpStreamRequest(DatadogHttpClient client, Uri uri, IStreamFactory streamFactory) { _uri = uri; _client = client; _streamFactory = streamFactory; } public void AddHeader(string name, string value) { _headers.Add(name, value); } public async Task<IApiResponse> PostAsync(ArraySegment<byte> traces) { using (var bidirectionalStream = _streamFactory.GetBidirectionalStream()) { var content = new BufferContent(traces); var request = new HttpRequest("POST", _uri.Host, _uri.PathAndQuery, _headers, content); // send request, get response var response = await _client.SendAsync(request, bidirectionalStream, bidirectionalStream).ConfigureAwait(false); // Content-Length is required as we don't support chunked transfer var contentLength = response.Content.Length; if (!contentLength.HasValue) { throw new Exception("Content-Length is required but was not provided"); } // buffer the entire contents for now var buffer = new byte[contentLength.Value]; var responseContentStream = new MemoryStream(buffer); await response.Content.CopyToAsync(buffer).ConfigureAwait(false); responseContentStream.Position = 0; return new HttpStreamResponse(response.StatusCode, responseContentStream.Length, response.GetContentEncoding(), responseContentStream, response.Headers); } } } }
39.53125
169
0.635573
[ "Apache-2.0" ]
alirezavafi/dd-trace-dotnet-splunk
src/Datadog.Trace/Agent/Transports/HttpStreamRequest.cs
2,530
C#
using System; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Engines { /** * A class that provides a basic International Data Encryption Algorithm (IDEA) engine. * <p> * This implementation is based on the "HOWTO: INTERNATIONAL DATA ENCRYPTION ALGORITHM" * implementation summary by Fauzan Mirza (F.U.Mirza@sheffield.ac.uk). (baring 1 typo at the * end of the mulinv function!). * </p> * <p> * It can be found at ftp://ftp.funet.fi/pub/crypt/cryptography/symmetric/idea/ * </p> * <p> * Note 1: This algorithm is patented in the USA, Japan, and Europe including * at least Austria, France, Germany, Italy, Netherlands, Spain, Sweden, Switzerland * and the United Kingdom. Non-commercial use is free, however any commercial * products are liable for royalties. Please see * <a href="http://www.mediacrypt.com">www.mediacrypt.com</a> for * further details. This announcement has been included at the request of * the patent holders. * </p> * <p> * Note 2: Due to the requests concerning the above, this algorithm is now only * included in the extended assembly. It is not included in the default distributions. * </p> */ public class IdeaEngine : IBlockCipher { private const int BLOCK_SIZE = 8; private int[] workingKey; /** * standard constructor. */ public IdeaEngine() { } /** * initialise an IDEA cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("invalid parameter passed to IDEA init - " + parameters.GetType().ToString()); workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey()); } public virtual string AlgorithmName { get { return "IDEA"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return BLOCK_SIZE; } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("IDEA engine not initialised"); Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); IdeaFunc(workingKey, input, inOff, output, outOff); return BLOCK_SIZE; } public virtual void Reset() { } private static readonly int MASK = 0xffff; private static readonly int BASE = 0x10001; private int BytesToWord( byte[] input, int inOff) { return ((input[inOff] << 8) & 0xff00) + (input[inOff + 1] & 0xff); } private void WordToBytes( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)((uint) word >> 8); outBytes[outOff + 1] = (byte)word; } /** * return x = x * y where the multiplication is done modulo * 65537 (0x10001) (as defined in the IDEA specification) and * a zero input is taken to be 65536 (0x10000). * * @param x the x value * @param y the y value * @return x = x * y */ private int Mul( int x, int y) { if (x == 0) { x = (BASE - y); } else if (y == 0) { x = (BASE - x); } else { int p = x * y; y = p & MASK; x = (int) ((uint) p >> 16); x = y - x + ((y < x) ? 1 : 0); } return x & MASK; } private void IdeaFunc( int[] workingKey, byte[] input, int inOff, byte[] outBytes, int outOff) { int x0, x1, x2, x3, t0, t1; int keyOff = 0; x0 = BytesToWord(input, inOff); x1 = BytesToWord(input, inOff + 2); x2 = BytesToWord(input, inOff + 4); x3 = BytesToWord(input, inOff + 6); for (int round = 0; round < 8; round++) { x0 = Mul(x0, workingKey[keyOff++]); x1 += workingKey[keyOff++]; x1 &= MASK; x2 += workingKey[keyOff++]; x2 &= MASK; x3 = Mul(x3, workingKey[keyOff++]); t0 = x1; t1 = x2; x2 ^= x0; x1 ^= x3; x2 = Mul(x2, workingKey[keyOff++]); x1 += x2; x1 &= MASK; x1 = Mul(x1, workingKey[keyOff++]); x2 += x1; x2 &= MASK; x0 ^= x1; x3 ^= x2; x1 ^= t1; x2 ^= t0; } WordToBytes(Mul(x0, workingKey[keyOff++]), outBytes, outOff); WordToBytes(x2 + workingKey[keyOff++], outBytes, outOff + 2); /* NB: Order */ WordToBytes(x1 + workingKey[keyOff++], outBytes, outOff + 4); WordToBytes(Mul(x3, workingKey[keyOff]), outBytes, outOff + 6); } /** * The following function is used to expand the user key to the encryption * subkey. The first 16 bytes are the user key, and the rest of the subkey * is calculated by rotating the previous 16 bytes by 25 bits to the left, * and so on until the subkey is completed. */ private int[] ExpandKey( byte[] uKey) { int[] key = new int[52]; if (uKey.Length < 16) { byte[] tmp = new byte[16]; Array.Copy(uKey, 0, tmp, tmp.Length - uKey.Length, uKey.Length); uKey = tmp; } for (int i = 0; i < 8; i++) { key[i] = BytesToWord(uKey, i * 2); } for (int i = 8; i < 52; i++) { if ((i & 7) < 6) { key[i] = ((key[i - 7] & 127) << 9 | key[i - 6] >> 7) & MASK; } else if ((i & 7) == 6) { key[i] = ((key[i - 7] & 127) << 9 | key[i - 14] >> 7) & MASK; } else { key[i] = ((key[i - 15] & 127) << 9 | key[i - 14] >> 7) & MASK; } } return key; } /** * This function computes multiplicative inverse using Euclid's Greatest * Common Divisor algorithm. Zero and one are self inverse. * <p> * i.e. x * MulInv(x) == 1 (modulo BASE) * </p> */ private int MulInv( int x) { int t0, t1, q, y; if (x < 2) { return x; } t0 = 1; t1 = BASE / x; y = BASE % x; while (y != 1) { q = x / y; x = x % y; t0 = (t0 + (t1 * q)) & MASK; if (x == 1) { return t0; } q = y / x; y = y % x; t1 = (t1 + (t0 * q)) & MASK; } return (1 - t1) & MASK; } /** * Return the additive inverse of x. * <p> * i.e. x + AddInv(x) == 0 * </p> */ int AddInv( int x) { return (0 - x) & MASK; } /** * The function to invert the encryption subkey to the decryption subkey. * It also involves the multiplicative inverse and the additive inverse functions. */ private int[] InvertKey( int[] inKey) { int t1, t2, t3, t4; int p = 52; /* We work backwards */ int[] key = new int[52]; int inOff = 0; t1 = MulInv(inKey[inOff++]); t2 = AddInv(inKey[inOff++]); t3 = AddInv(inKey[inOff++]); t4 = MulInv(inKey[inOff++]); key[--p] = t4; key[--p] = t3; key[--p] = t2; key[--p] = t1; for (int round = 1; round < 8; round++) { t1 = inKey[inOff++]; t2 = inKey[inOff++]; key[--p] = t2; key[--p] = t1; t1 = MulInv(inKey[inOff++]); t2 = AddInv(inKey[inOff++]); t3 = AddInv(inKey[inOff++]); t4 = MulInv(inKey[inOff++]); key[--p] = t4; key[--p] = t2; /* NB: Order */ key[--p] = t3; key[--p] = t1; } t1 = inKey[inOff++]; t2 = inKey[inOff++]; key[--p] = t2; key[--p] = t1; t1 = MulInv(inKey[inOff++]); t2 = AddInv(inKey[inOff++]); t3 = AddInv(inKey[inOff++]); t4 = MulInv(inKey[inOff]); key[--p] = t4; key[--p] = t3; key[--p] = t2; key[--p] = t1; return key; } private int[] GenerateWorkingKey( bool forEncryption, byte[] userKey) { if (forEncryption) { return ExpandKey(userKey); } else { return InvertKey(ExpandKey(userKey)); } } } }
31.274096
122
0.431282
[ "BSD-3-Clause" ]
ConnectionMaster/OutlookPrivacyPlugin
3rdParty/bccrypto-net-05282015/crypto/src/crypto/engines/IdeaEngine.cs
10,383
C#
using System; using System.Collections.Generic; using System.Text; namespace DFC.Digital.Tools.Data.Models { public class AccountNotification : BaseIntegrationModel { public string Name { get; set; } public string Email { get; set; } } }
19.214286
59
0.684015
[ "MIT" ]
SkillsFundingAgency/dfc-digital-tools
DFC.Digital.Tools/DFC.Digital.Tools.Data/Models/AccountNotification.cs
271
C#
using System; using Xunit; using Ardalis.Extensions.StringManipulation; namespace Ardalis.Extensions.UnitTests { public class ReverseTests { [Theory] [InlineData(null)] [InlineData("")] public void ReturnsEmptyStringGivenNullOrEmptyString(string input) { string result = input.Reverse(); Assert.Equal(String.Empty, result); } [Theory] [InlineData("a", "a")] [InlineData("abcde", "edcba")] public void ReturnsReversedString(string input, string expectedResult) { string result = input.Reverse(); Assert.Equal(expectedResult, result); } } }
23.333333
78
0.595714
[ "MIT" ]
MarkusGnigler/Ardalis.Extensions
tests/Ardalis.Extensions.UnitTests/StringManipulation/ReverseTests.cs
702
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.Plugin.WindowWalker.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Plugin.WindowWalker.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Switches between open windows.. /// </summary> public static string wox_plugin_windowwalker_plugin_description { get { return ResourceManager.GetString("wox_plugin_windowwalker_plugin_description", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Window Walker. /// </summary> public static string wox_plugin_windowwalker_plugin_name { get { return ResourceManager.GetString("wox_plugin_windowwalker_plugin_name", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Running. /// </summary> public static string wox_plugin_windowwalker_running { get { return ResourceManager.GetString("wox_plugin_windowwalker_running", resourceCulture); } } } }
43.230769
196
0.592781
[ "MIT" ]
0xf0f/PowerToys
src/modules/launcher/Plugins/Microsoft.Plugin.WindowWalker/Properties/Resources.Designer.cs
3,846
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace System.Globalization { [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum CalendarWeekRule { FirstDay = 0, // Week 1 begins on the first day of the year FirstFullWeek = 1, // Week 1 begins on first FirstDayOfWeek not before the first day of the year FirstFourDayWeek = 2 // Week 1 begins on first FirstDayOfWeek such that FirstDayOfWeek+3 is not before the first day of the year }; }
35.55
147
0.696203
[ "MIT" ]
LaudateCorpus1/corert
src/System.Private.CoreLib/src/System/Globalization/CalendarWeekRule.cs
711
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BezierCurve : MonoBehaviour { public Vector3[] points; public void Reset() { points = new Vector3[] { new Vector3(1f, 0, 0), new Vector3(2f, 0, 0), new Vector3(3f, 0, 0), new Vector3(4f, 0, 0) }; } public Vector3 GetPoint(float t) { return transform.TransformPoint(Bezier.GetPoint(points[0], points[1], points[2], points[3], t)); } public Vector3 GetVelocity(float t) { return transform.TransformPoint(Bezier.GetFirstDerivative(points[0], points[1], points[2], points[3], t)) - transform.position; // Returns a vector, not a point, so not affected by position } public Vector3 GetDirection(float t) { return GetVelocity(t).normalized; } }
24.861111
135
0.604469
[ "MIT" ]
Gaetz/unity-Spline
Assets/Scripts/BezierCurve.cs
897
C#
// <auto-generated /> namespace PhotoMSK.Data.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class OrdersAndContracts : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(OrdersAndContracts)); string IMigrationMetadata.Id { get { return "201506092218038_OrdersAndContracts"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
27.966667
101
0.629321
[ "MIT" ]
MarkusMokler/photomsmsk-by
PhotoMSK/Core/PhotoMSK.Data/Migrations/201506092218038_OrdersAndContracts.Designer.cs
839
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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. // File System.Web.UI.WebControls.TextBoxControlBuilder.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { public partial class TextBoxControlBuilder : System.Web.UI.ControlBuilder { #region Methods and constructors public override bool AllowWhitespaceLiterals() { return default(bool); } public override bool HtmlDecodeLiterals() { return default(bool); } public TextBoxControlBuilder() { } #endregion } }
39.95
463
0.76262
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/System.Web/Sources/System.Web.UI.WebControls.TextBoxControlBuilder.cs
2,397
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class PlayerMovement : MonoBehaviour { [Header("Clamping Zone")] public Vector2 zoneOfAction; [Header("Movement")] public float speed; public PlayerInput playerInput; [Header("Looking")] public Camera mainCamera; private Vector2 vectorLooking; private Vector2 pointToLook; [Header("Farming")] public GameObject soilToPlant; public Transform Crosshair; [Header("Animations")] public Animator playerAnimator; public float horizontal,vertical; public float Moving; private Vector2 vectorMovement; private Rigidbody2D rgb; [Header("timerFootstep")] public float timerFootstep = .5f; public float timeToStep = .5f; void Start() { rgb = this.GetComponent<Rigidbody2D>(); } public void OnMove(InputAction.CallbackContext value) { vectorMovement = value.ReadValue<Vector2>(); if (value.started) { Moving = 1; horizontal = vectorMovement.x; vertical = vectorMovement.y; } else if(value.canceled) { Moving = 0; } } public void OnLook(InputAction.CallbackContext value) { vectorLooking = value.ReadValue<Vector2>(); vectorLooking.Normalize(); pointToLook = mainCamera.ScreenToWorldPoint(Mouse.current.position.ReadValue()); } void Update() { if (GameManager.instance.gameOver) { } else { rgb.velocity += vectorMovement * speed * Time.deltaTime; transform.position = new Vector3(Mathf.Clamp(transform.position.x, -zoneOfAction.x, zoneOfAction.x), Mathf.Clamp(transform.position.y, -zoneOfAction.y, zoneOfAction.y), 0); Vector2 direction = pointToLook - (Vector2)transform.position; //direction from Center to Cursor Vector2 normalizedDirection = direction.normalized; normalizedDirection.x = Mathf.Round(normalizedDirection.x); normalizedDirection.y = Mathf.Round(normalizedDirection.y); Crosshair.position = new Vector3(Mathf.Round(transform.position.x), Mathf.Round(transform.position.y), Mathf.Round(transform.position.z)) + (Vector3)normalizedDirection; } } private void LateUpdate() { if (GameManager.instance.gameOver) { } else { playerAnimator.SetFloat("Horizontal", horizontal); playerAnimator.SetFloat("Vertical", vertical); playerAnimator.SetFloat("Speed", Moving); } } }
26.711538
112
0.62167
[ "MIT" ]
OcelotDevelop/Chaotic_Farming
Chaotic Farming/Assets/Scripts/PlayerMovement.cs
2,778
C#
using Adonet_Blog.Entities; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace Adonet_Blog.Services { /// <summary> /// Used to get and send data to the Post Db table /// </summary> public class PostService { private SqlConnection _conn; SqlCommand _command; /// <summary> /// Injecting IConfiguration as dependency /// </summary> /// <param name="config"></param> public PostService(IConfiguration config) { ConnectionService connServ = new ConnectionService(config); this._conn = connServ.DbConnection(); } public List<Post> GetAllPosts() { List<Post> posts = new List<Post>(); // SQL query this._command = new SqlCommand("select * from [Post]", this._conn); // Defines the command type this._command.CommandType = CommandType.Text; // Getting the data and closing the connection IDataReader dataReader = this._command.ExecuteReader(CommandBehavior.CloseConnection); // Storing the data while(dataReader.Read()) { Post post = new Post(); post.PostId = dataReader["PostId"] is DBNull ? 0 : int.Parse(dataReader["PostId"].ToString()); post.UserId = dataReader["UserId"] is DBNull ? 0 : int.Parse(dataReader["UserId"].ToString()); post.Title = dataReader["Title"] is DBNull ? "" : dataReader["Title"].ToString(); post.Content = dataReader["Content"] is DBNull ? "" : dataReader["Content"].ToString(); if (dataReader["Publishing_Date"] != DBNull.Value) { post.Publishing_Date = DateTime.Parse(dataReader["Publishing_Date"].ToString()); } if (dataReader["Modified_Date"] != DBNull.Value) { post.Modified_Date = DateTime.Parse(dataReader["Modified_Date"].ToString()); } posts.Add(post); } return posts; } public Post GetPost(int id) { Post post = new Post(); // SQL query //this._command = new SqlCommand($"select [Post].*, [User].[Username] from [Post] right join [User] ON [User].[UserId] = [Post].[UserId] where [Post].[PostId] = {id}", this._conn); this._command = new SqlCommand($"select [Post].*, [User].[Username] from [Post] left join [User] ON [User].[UserId] = [Post].[UserId] where [Post].[PostId] = {id}", this._conn); // Defines the command type this._command.CommandType = CommandType.Text; // Getting the data and closing the connection IDataReader dataReader = this._command.ExecuteReader(CommandBehavior.CloseConnection); // Storing the data while (dataReader.Read()) { post.PostId = dataReader["PostId"] is DBNull ? 0 : int.Parse(dataReader["PostId"].ToString()); post.UserId = dataReader["UserId"] is DBNull ? 0 : int.Parse(dataReader["UserId"].ToString()); post.Title = dataReader["Title"] is DBNull ? string.Empty : dataReader["Title"].ToString(); post.Content = dataReader["Content"] is DBNull ? string.Empty : dataReader["Content"].ToString(); if (dataReader["Publishing_Date"] != DBNull.Value) { post.Publishing_Date = DateTime.Parse(dataReader["Publishing_Date"].ToString()); } if (dataReader["Modified_Date"] != DBNull.Value) { post.Modified_Date = DateTime.Parse(dataReader["Modified_Date"].ToString()); } User myUser = new User { UserId = post.PostId, Username = dataReader["Username"] is DBNull ? "This post may have been deleted." : dataReader["Username"].ToString(), //Password = dataReader["Password"] is DBNull ? "This post may have been deleted." : dataReader["Password"].ToString(), }; post.Writer = myUser; } return post; } public List<Post> GetPostsByUser(int userId) { List<Post> posts = new List<Post>(); // SQL query //this._command = new SqlCommand($"select [Post].*, [User].[Username] from Post right join [User] ON [User].[UserId] = [Post].[UserId] where [Post].[UserId] = {userId}", this._conn); this._command = new SqlCommand($"select [Post].*, [User].[Username] from Post left join [User] ON [User].[UserId] = [Post].[UserId] where [Post].[UserId] = {userId}", this._conn); // Defines the command type this._command.CommandType = CommandType.Text; // Getting the data and closing the connection IDataReader dataReader = this._command.ExecuteReader(CommandBehavior.CloseConnection); // Storing the data while (dataReader.Read()) { Post post = new Post(); post.PostId = dataReader["PostId"] is DBNull ? 0 : int.Parse(dataReader["PostId"].ToString()); post.UserId = dataReader["UserId"] is DBNull ? 0 : int.Parse(dataReader["UserId"].ToString()); post.Title = dataReader["Title"] is DBNull ? "" : dataReader["Title"].ToString(); post.Content = dataReader["Content"] is DBNull ? "" : dataReader["Content"].ToString(); if (dataReader["Publishing_Date"] != DBNull.Value) { post.Publishing_Date = DateTime.Parse(dataReader["Publishing_Date"].ToString()); } if (dataReader["Modified_Date"] != DBNull.Value) { post.Modified_Date = DateTime.Parse(dataReader["Modified_Date"].ToString()); } User myUser = new User { UserId = post.PostId, Username = dataReader["Username"] is DBNull ? "This post may have been deleted." : dataReader["Username"].ToString(), }; post.Writer = myUser; posts.Add(post); } return posts; } public bool Create(Post post) { bool result = false; // SQL query this._command = new SqlCommand("insert into [Post] (UserId, Title, Content, Publishing_Date, Modified_Date) values (@UserId, @Title, @Content, @Publishing_Date, @Modified_Date)", this._conn); this._command.Parameters.AddWithValue("@UserId", post.UserId); this._command.Parameters.AddWithValue("@Title", post.Title); this._command.Parameters.AddWithValue("@Content", post.Content); this._command.Parameters.AddWithValue("@Publishing_Date", post.Publishing_Date); this._command.Parameters.AddWithValue("@Modified_Date", post.Modified_Date); // Getting the querry result int success = this._command.ExecuteNonQuery(); result = success != 0 ? true : false; return result; } public bool Update(Post post) { bool result = false; // SQL query this._command = new SqlCommand("update [Post] set [Title]=@Title, [Content]=@Content, [Modified_Date]=@Modified_Date where [Post].[PostId] = @PostId", this._conn); this._command.Parameters.AddWithValue("@Title", post.Title); this._command.Parameters.AddWithValue("@Content", post.Content); this._command.Parameters.AddWithValue("@Modified_Date", post.Modified_Date); this._command.Parameters.AddWithValue("@PostId", post.PostId); // Getting the querry result int success = this._command.ExecuteNonQuery(); result = success != 0 ? true : false; return result; } public bool Delete(int id) { bool result = false; // SQL query this._command = new SqlCommand("delete [Post] where [Post].[PostId] = @PostId", this._conn); this._command.Parameters.AddWithValue("@PostId", id); // Getting the querry result int success = this._command.ExecuteNonQuery(); result = success != 0 ? true : false; return result; } public bool Delete(Post post) { return Delete(post.PostId); } public List<Post> Search(string term) { List<Post> posts = new List<Post>(); // SQL query this._command = new SqlCommand(@$"select [Post].*, [User].[Username] from [Post] left join [User] ON [User].[UserId] = [Post].[UserId] where [Post].[Title] like '%" + term + "%' or [Post].[Content] like '%" + term + "%'", this._conn); // Defines the command type this._command.CommandType = CommandType.Text; // Getting the data and closing the connection IDataReader dataReader = this._command.ExecuteReader(CommandBehavior.CloseConnection); // Storing the data while (dataReader.Read()) { Post post = new Post(); post.PostId = dataReader["PostId"] is DBNull ? 0 : int.Parse(dataReader["PostId"].ToString()); post.UserId = dataReader["UserId"] is DBNull ? 0 : int.Parse(dataReader["UserId"].ToString()); post.Title = dataReader["Title"] is DBNull ? "" : dataReader["Title"].ToString(); post.Content = dataReader["Content"] is DBNull ? "" : dataReader["Content"].ToString(); if (dataReader["Publishing_Date"] != DBNull.Value) { post.Publishing_Date = DateTime.Parse(dataReader["Publishing_Date"].ToString()); } if (dataReader["Modified_Date"] != DBNull.Value) { post.Modified_Date = DateTime.Parse(dataReader["Modified_Date"].ToString()); } User myUser = new User { UserId = post.PostId, Username = dataReader["Username"] is DBNull ? "This post may have been deleted." : dataReader["Username"].ToString(), }; post.Writer = myUser; posts.Add(post); } return posts; } } }
42.303502
204
0.555004
[ "Apache-2.0" ]
Victoralm/AspNetCore5AndVueJSFromZeroToHero
Adonet-Blog/Services/PostService.cs
10,874
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Globalization; using Microsoft.Protocols.TestTools.StackSdk.Security.SspiLib; namespace Microsoft.Protocols.TestTools.StackSdk.Security.Sspi { /// <summary> /// Utility class of SSPI. /// </summary> public static class SspiUtility { //A pointer to a null-terminated string that specifies the name of the security package with which these //credentials will be used. private const string Negotiate = "Negotiate"; private const string Kerberos = "Kerberos"; private const string Ntlm = "NTLM"; private const string Schannel = "Microsoft Unified Security Protocol Provider"; private const string CredSsp = "CredSsp"; //Security context attributes defined by SSPI. //reference: http://msdn.microsoft.com/en-us/library/aa379326(VS.85).aspx private const string SECPKG_ATTR_SIZES = "SECPKG_ATTR_SIZES"; private const string SECPKG_ATTR_NAMES = "SECPKG_ATTR_NAMES"; private const string SECPKG_ATTR_LIFESPAN = "SECPKG_ATTR_LIFESPAN"; private const string SECPKG_ATTR_DCE_INFO = "SECPKG_ATTR_DCE_INFO"; private const string SECPKG_ATTR_STREAM_SIZES = "SECPKG_ATTR_STREAM_SIZES"; private const string SECPKG_ATTR_KEY_INFO = "SECPKG_ATTR_KEY_INFO"; private const string SECPKG_ATTR_AUTHORITY = "SECPKG_ATTR_AUTHORITY"; private const string SECPKG_ATTR_PROTO_INFO = "SECPKG_ATTR_PROTO_INFO"; private const string SECPKG_ATTR_PASSWORD_EXPIRY = "SECPKG_ATTR_PASSWORD_EXPIRY"; private const string SECPKG_ATTR_SESSION_KEY = "SECPKG_ATTR_SESSION_KEY"; private const string SECPKG_ATTR_PACKAGE_INFO = "SECPKG_ATTR_PACKAGE_INFO"; private const string SECPKG_ATTR_USER_FLAGS = "SECPKG_ATTR_USER_FLAGS"; private const string SECPKG_ATTR_NEGOTIATION_INFO = "SECPKG_ATTR_NEGOTIATION_INFO"; private const string SECPKG_ATTR_NATIVE_NAMES = "SECPKG_ATTR_NATIVE_NAMES"; private const string SECPKG_ATTR_FLAGS = "SECPKG_ATTR_FLAGS"; // These attributes exist only in Win XP and greater private const string SECPKG_ATTR_USE_VALIDATED = "SECPKG_ATTR_USE_VALIDATED"; private const string SECPKG_ATTR_CREDENTIAL_NAME = "SECPKG_ATTR_CREDENTIAL_NAME"; private const string SECPKG_ATTR_TARGET_INFORMATION = "SECPKG_ATTR_TARGET_INFORMATION"; private const string SECPKG_ATTR_ACCESS_TOKEN = "SECPKG_ATTR_ACCESS_TOKEN"; // These attributes exist only in Win2K3 and greater private const string SECPKG_ATTR_TARGET = "SECPKG_ATTR_TARGET"; private const string SECPKG_ATTR_AUTHENTICATION_ID = "SECPKG_ATTR_AUTHENTICATION_ID"; // These attributes exist only in Win2K3SP1 and greater private const string SECPKG_ATTR_LOGOFF_TIME = "SECPKG_ATTR_LOGOFF_TIME"; //Defined in schannel.h private const string SECPKG_ATTR_REMOTE_CERT_CONTEXT = "SECPKG_ATTR_REMOTE_CERT_CONTEXT"; private const string SECPKG_ATTR_LOCAL_CERT_CONTEXT = "SECPKG_ATTR_LOCAL_CERT_CONTEXT"; private const string SECPKG_ATTR_ROOT_STORE = "SECPKG_ATTR_ROOT_STORE"; private const string SECPKG_ATTR_ISSUER_LIST_EX = "SECPKG_ATTR_ISSUER_LIST_EX"; private const string SECPKG_ATTR_CONNECTION_INFO = "SECPKG_ATTR_CONNECTION_INFO"; private const string SECPKG_ATTR_EAP_KEY_BLOCK = "SECPKG_ATTR_EAP_KEY_BLOCK"; private const string SECPKG_ATTR_APP_DATA = "SECPKG_ATTR_APP_DATA"; //Schannel key static size defined in SecPkgContext_EapKeyBlock Structure. //http://msdn.microsoft.com/en-us/library/aa379822(v=VS.85).aspx private const int SchannelKeySize = 128; private const int SchannelIvSize = 64; private static byte[] ConcatenateSecurityBuffers( SecurityBuffer[] securityBuffers, SecurityBufferType[] targetTypes, bool bothReadOnlyAndReadWrite) { byte[] buf = new byte[0]; for (int i = 0; i < securityBuffers.Length; i++) { SecurityBufferType securityBufferType = (securityBuffers[i].BufferType & ~SecurityBufferType.AttrMask); bool typeMatch = false; for (int j = 0; j < targetTypes.Length; j++) { if (securityBufferType == targetTypes[j]) { typeMatch = true; break; } } if (typeMatch) { bool skip = !bothReadOnlyAndReadWrite && (((securityBuffers[i].BufferType & SecurityBufferType.ReadOnly) != 0) || ((securityBuffers[i].BufferType & SecurityBufferType.ReadOnlyWithChecksum) != 0)); if (!skip && securityBuffers[i].Buffer != null) { buf = ArrayUtility.ConcatenateArrays(buf, securityBuffers[i].Buffer); } } } return buf; } /// <summary> /// Concatenate all buffers of a specified type in the list. /// </summary> /// <param name="securityBuffers">Input security buffers.</param> /// <param name="targetTypes">Specified types.</param> /// <returns>A single byte array with all buffers concatenated.</returns> /// <exception cref="ArgumentNullException"> /// Thrown when securityBuffers is null. /// </exception> public static byte[] ConcatenateSecurityBuffers(SecurityBuffer[] securityBuffers, params SecurityBufferType[] targetTypes) { if (securityBuffers == null || securityBuffers.Length == 0) { throw new ArgumentNullException("securityBuffers"); } for (int i = 0; i < securityBuffers.Length; i++) { if (securityBuffers[i] == null) { throw new ArgumentNullException("securityBuffers"); } } return ConcatenateSecurityBuffers(securityBuffers, targetTypes, true); } /// <summary> /// Concatenate all read-write (READONLY flag is not set) buffers of a specified type in the list. /// </summary> /// <param name="securityBuffers">Input security buffers.</param> /// <param name="targetTypes">Specified types.</param> /// <returns>A single byte array with all buffers concatenated.</returns> /// <exception cref="ArgumentNullException"> /// Thrown when securityBuffers is null. /// </exception> public static byte[] ConcatenateReadWriteSecurityBuffers( SecurityBuffer[] securityBuffers, params SecurityBufferType[] targetTypes) { if (securityBuffers == null || securityBuffers.Length == 0) { throw new ArgumentNullException("securityBuffers"); } for (int i = 0; i < securityBuffers.Length; i++) { if (securityBuffers[i] == null) { throw new ArgumentNullException("securityBuffers"); } } return ConcatenateSecurityBuffers(securityBuffers, targetTypes, false); } /// <summary> /// Update buffers of a specified type in the list. /// Buffer will be separated automatically to fit the original length of a security buffer. /// If Buffer field of an input security buffer is null, it means the length is unlimited /// (that is all remaining data will be copied into it). /// Only read-write (READONLY flag is not set) security buffer will be updated. /// </summary> /// <param name="securityBuffers">Input security buffers.</param> /// <param name="targetType">A specified type.</param> /// <param name="buffer">The buffer to be updated into security buffers.</param> /// <exception cref="ArgumentNullException"> /// Thrown when securityBuffers or buffer is null. /// </exception> /// <exception cref="SspiException"> /// Total length of security buffers is not enough. /// </exception> public static void UpdateSecurityBuffers(SecurityBuffer[] securityBuffers, SecurityBufferType targetType, byte[] buffer) { UpdateSecurityBuffers(securityBuffers, new SecurityBufferType[] { targetType }, buffer); } /// <summary> /// Update buffers of a specified type in the list. /// Buffer will be separated automatically to fit the original length of a security buffer. /// If Buffer field of an input security buffer is null, it means the length is unlimited /// (that is all remaining data will be copied into it). /// Only read-write (READONLY flag is not set) security buffer will be updated. /// </summary> /// <param name="securityBuffers">Input security buffers.</param> /// <param name="targetTypes">Specified types.</param> /// <param name="buffer">The buffer to be updated into security buffers.</param> /// <exception cref="ArgumentNullException"> /// Thrown when securityBuffers or buffer is null. /// </exception> /// <exception cref="SspiException"> /// Total length of security buffers is not enough. /// </exception> public static void UpdateSecurityBuffers(SecurityBuffer[] securityBuffers, SecurityBufferType[] targetTypes, byte[] buffer) { if (securityBuffers == null || securityBuffers.Length == 0) { throw new ArgumentNullException("securityBuffers"); } for (int i = 0; i < securityBuffers.Length; i++) { if (securityBuffers[i] == null) { throw new ArgumentNullException("securityBuffers"); } } if (buffer == null) { throw new ArgumentNullException("buffer"); } int offset = 0; for (int i = 0; i < securityBuffers.Length; i++) { SecurityBufferType securityBufferType = (securityBuffers[i].BufferType & ~SecurityBufferType.AttrMask); bool isReadOnly = ((securityBuffers[i].BufferType & SecurityBufferType.ReadOnly) != 0) || ((securityBuffers[i].BufferType & SecurityBufferType.ReadOnlyWithChecksum) != 0); bool typeMatch = false; for (int j = 0; j < targetTypes.Length; j++) { if (securityBufferType == targetTypes[j]) { typeMatch = true; break; } } if (typeMatch && !isReadOnly) { int length = buffer.Length - offset; if (securityBuffers[i].Buffer != null && securityBuffers[i].Buffer.Length < length) { length = securityBuffers[i].Buffer.Length; } securityBuffers[i].Buffer = ArrayUtility.SubArray( buffer, offset, length); offset += length; } } if (offset < buffer.Length) { throw new SspiException("Total length of security buffers is not enough."); } else if (offset > buffer.Length) { //Unlikely to happen throw new InvalidOperationException("Extra data were written to security buffers."); } } #region Windows SSPI /// <summary> /// Verify message whether follow the format: MESSAGE_LENGTH(4 bytes)|MESSAGE. /// </summary> /// <param name="message">Message contains header.</param> /// <returns>If true, verify successful, otherwise fail.</returns> internal static bool VerifyMessageHeader(byte[] message) { if (message == null) { return false; } //Verify message header if (message.Length < sizeof(int)) { return false; } else { int messageLength = BitConverter.ToInt32(message, 0); //The value of header should be less than or equal length of message body and signature(optional). if (messageLength > message.Length - sizeof(int)) { return false; } } return true; } /// <summary> /// Free un-managed resources in SecurityWinntAuthIdentity /// </summary> /// <param name="authIdentity">Security Winnt Auth Identity.</param> internal static void FreeSecurityWinntAuthIdentity(SecurityWinntAuthIdentity authIdentity) { if (authIdentity.User != IntPtr.Zero) { Marshal.FreeHGlobal(authIdentity.User); authIdentity.User = IntPtr.Zero; } if (authIdentity.Domain != IntPtr.Zero) { Marshal.FreeHGlobal(authIdentity.Domain); authIdentity.Domain = IntPtr.Zero; } if (authIdentity.Password != IntPtr.Zero) { Marshal.FreeHGlobal(authIdentity.Password); authIdentity.Password = IntPtr.Zero; } } /// <summary> /// Free un-managed memory in SchannelCred. /// </summary> /// <param name="schannelCred">SchannelCred structure</param> internal static void FreeSchannelCred(SchannelCred schannelCred) { if (schannelCred.paCred != IntPtr.Zero) { Marshal.FreeHGlobal(schannelCred.paCred); schannelCred.paCred = IntPtr.Zero; } } /// <summary> /// Free un-managed memory in CredSspCred /// </summary> /// <param name="credSsp">CredSspCred structure</param> internal static void FreeCredSspCred(CredSspCred credSsp) { if (credSsp.pSchannelCred != IntPtr.Zero) { Marshal.FreeHGlobal(credSsp.pSchannelCred); credSsp.pSchannelCred = IntPtr.Zero; } if (credSsp.pSpnegoCred != IntPtr.Zero) { Marshal.FreeHGlobal(credSsp.pSpnegoCred); credSsp.pSpnegoCred = IntPtr.Zero; } } /// <summary> /// Convert SecurityPackage type to package string used by SSPI. /// </summary> /// <param name="packageType">Package type</param> /// <returns>Package string used by SSPI</returns> /// <exception cref="ArgumentException">If packageType is not supported, throw this exception.</exception> internal static string GetPackageStringName(SecurityPackageType packageType) { string package = string.Empty; switch (packageType) { case SecurityPackageType.CredSsp: package = CredSsp; break; case SecurityPackageType.Kerberos: package = Kerberos; break; case SecurityPackageType.Negotiate: package = Negotiate; break; case SecurityPackageType.Ntlm: package = Ntlm; break; case SecurityPackageType.Schannel: package = Schannel; break; default: throw new ArgumentException("Invlid packageType value.", "packageType"); } return package; } /// <summary> /// Create un-managed memory of SecurityWinntAuthIdentity structure /// </summary> /// <param name="authIndentity">SecurityWinntAuthIdentity structure</param> /// <returns>IntPtr of SecurityWinntAuthIdentity</returns> internal static IntPtr CreateAuthData(SecurityWinntAuthIdentity authIndentity) { IntPtr pAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(authIndentity)); Marshal.StructureToPtr(authIndentity, pAuthData, false); return pAuthData; } /// <summary> /// Create un-managed memory of SchannelCred structure. /// </summary> /// <param name="schannelCred">Schannel_Cred structure</param> /// <returns>IntPtr of SchannelCred</returns> internal static IntPtr CreateAuthData(SchannelCred schannelCred) { IntPtr pAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(schannelCred)); Marshal.StructureToPtr(schannelCred, pAuthData, false); return pAuthData; } /// <summary> /// Create un-managed memory of CredSspCred structure. /// </summary> /// <param name="credSsp">CredSspCred structure</param> /// <returns>IntPtr of CredSspCred</returns> internal static IntPtr CreateAuthData(CredSspCred credSsp) { IntPtr pAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(credSsp)); Marshal.StructureToPtr(credSsp, pAuthData, false); return pAuthData; } /// <summary> /// Query Session key by context handle. /// </summary> /// <param name="packageType">Package type</param> /// <param name="contextHandle">context handle</param> /// <returns>Session key</returns> internal static byte[] QuerySessionKey(SecurityPackageType packageType, ref SecurityHandle contextHandle) { IntPtr pSessionKey = IntPtr.Zero; byte[] sessionKey = null; if (packageType == SecurityPackageType.Schannel || packageType == SecurityPackageType.CredSsp) { pSessionKey = Marshal.AllocHGlobal(SchannelKeySize + SchannelIvSize); uint hResult = NativeMethods.QueryContextAttributes( ref contextHandle, NativeMethods.SECPKG_ATTR_EAP_KEY_BLOCK, pSessionKey); if (hResult == NativeMethods.SEC_E_OK) { if (pSessionKey != IntPtr.Zero) { sessionKey = new byte[SchannelKeySize]; Marshal.Copy(pSessionKey, sessionKey, 0, SchannelKeySize); } } Marshal.FreeHGlobal(pSessionKey); } else { pSessionKey = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityPackageContextSessionKey))); uint hResult = NativeMethods.QueryContextAttributes( ref contextHandle, NativeMethods.SECPKG_ATTR_SESSION_KEY, pSessionKey); if (hResult == NativeMethods.SEC_E_OK) { if (pSessionKey != IntPtr.Zero) { SecurityPackageContextSessionKey contextSessionKey = (SecurityPackageContextSessionKey) Marshal.PtrToStructure(pSessionKey, typeof(SecurityPackageContextSessionKey)); sessionKey = new byte[contextSessionKey.SessionKeyLength]; Marshal.Copy(contextSessionKey.SessionKey, sessionKey, 0, sessionKey.Length); NativeMethods.FreeContextBuffer(contextSessionKey.SessionKey); } } Marshal.FreeHGlobal(pSessionKey); } return sessionKey; } /// <summary> /// Query ContextSizes attribute. /// </summary> /// <param name="contextHandle">context handle</param> /// <returns>Context sizes</returns> /// <exception cref="SspiException">If verify fail, throw this exception.</exception> internal static SecurityPackageContextSizes QueryContextSizes(ref SecurityHandle contextHandle) { IntPtr pContextSizes = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityPackageContextSizes))); uint hResult = NativeMethods.QueryContextAttributes( ref contextHandle, NativeMethods.SECPKG_ATTR_SIZES, pContextSizes); if (hResult == NativeMethods.SEC_E_OK) { SecurityPackageContextSizes contextSizes = (SecurityPackageContextSizes)Marshal.PtrToStructure( pContextSizes, typeof(SecurityPackageContextSizes)); Marshal.FreeHGlobal(pContextSizes); return contextSizes; } else { Marshal.FreeHGlobal(pContextSizes); throw new SspiException("Query ContextSizes failed.", hResult); } } /// <summary> /// Sign message with MakeSignature of SSPI. /// </summary> /// <param name="contextHandle">Context handle</param> /// <param name="sequenceNumber">Sequence number</param> /// <param name="securityBuffers">SecurityBufferDesc for MakeSignature.</param> /// <exception cref="SspiException">If verify fail, throw this exception.</exception> internal static void MakeSignature( ref SecurityHandle contextHandle, uint sequenceNumber, params SecurityBuffer[] securityBuffers) { SecurityBufferDescWrapper securityBufferDescWrapper = new SecurityBufferDescWrapper(securityBuffers); uint hResult = NativeMethods.MakeSignature( ref contextHandle, 0, ref securityBufferDescWrapper.securityBufferDesc, sequenceNumber); if (hResult != NativeMethods.SEC_E_OK) { securityBufferDescWrapper.FreeSecurityBufferDesc(); throw new SspiException("Sign failed.", hResult); } else { SspiSecurityBuffer[] buffers = securityBufferDescWrapper.securityBufferDesc.GetBuffers(); if (buffers != null) { for (int i = 0; i < buffers.Length; i++) { if (securityBuffers[i].BufferType == SecurityBufferType.Token) { securityBuffers[i].Buffer = new byte[buffers[i].bufferLength]; Marshal.Copy( buffers[i].pSecBuffer, securityBuffers[i].Buffer, 0, (int)buffers[i].bufferLength); } } } securityBufferDescWrapper.FreeSecurityBufferDesc(); } } /// <summary> /// Verify signature with VerifySignature of SSPI. /// </summary> /// <param name="contextHandle">context handle</param> /// <param name="securityBuffers">SecurityBufferDesc for VerifySignature.</param> /// <returns>If successful, return true.</returns> /// <param name="sequenceNumber">Sequence number</param> /// <exception cref="SspiException">If verify fail, throw this exception.</exception> internal static bool VerifySignature( ref SecurityHandle contextHandle, uint sequenceNumber, params SecurityBuffer[] securityBuffers) { SecurityBufferDescWrapper securityBufferDescWrapper = new SecurityBufferDescWrapper(securityBuffers); uint pfQop; uint hResult = NativeMethods.VerifySignature( ref contextHandle, ref securityBufferDescWrapper.securityBufferDesc, sequenceNumber, out pfQop); securityBufferDescWrapper.FreeSecurityBufferDesc(); if (hResult == NativeMethods.SEC_E_OK) { return true; } else { throw new SspiException("Verify failed.", hResult); } } /// <summary> /// Encrypt message with EncryptMessage of SSPI /// </summary> /// <param name="contextHandle">context handle</param> /// <param name="sequenceNumber">sequence number</param> /// <param name="qualityOfProtection">The quality of protection flag</param> /// <param name="securityBuffers">SecurityBufferDesc for EncryptMessage</param> /// <exception cref="SspiException">If verify fail, throw this exception.</exception> internal static void Encrypt( ref SecurityHandle contextHandle, uint sequenceNumber, SECQOP_WRAP qualityOfProtection, params SecurityBuffer[] securityBuffers) { SecurityBufferDescWrapper encryptBufferDescWrapper = new SecurityBufferDescWrapper(securityBuffers); uint hResult = NativeMethods.EncryptMessage( ref contextHandle, (uint)qualityOfProtection, ref encryptBufferDescWrapper.securityBufferDesc, sequenceNumber); if (hResult == NativeMethods.SEC_E_OK) { SspiSecurityBuffer[] buffers = encryptBufferDescWrapper.securityBufferDesc.GetBuffers(); for (int i = 0; i < securityBuffers.Length; i++) { securityBuffers[i].Buffer = new byte[buffers[i].bufferLength]; if (buffers[i].pSecBuffer != IntPtr.Zero) { Marshal.Copy(buffers[i].pSecBuffer, securityBuffers[i].Buffer, 0, securityBuffers[i].Buffer.Length); } } encryptBufferDescWrapper.FreeSecurityBufferDesc(); } else { encryptBufferDescWrapper.FreeSecurityBufferDesc(); throw new SspiException("Encrypt failed.", hResult); } } /// <summary> /// Decrypt message with DecryptMessage Of SSPI /// </summary> /// <param name="contextHandle">context handle</param> /// <param name="sequenceNumber">sequence number</param> /// <param name="securityBuffers">SecurityBufferDesc for DecryptMessage</param> /// <exception cref="SspiException">If verify fail, throw this exception.</exception> internal static bool Decrypt( ref SecurityHandle contextHandle, uint sequenceNumber, params SecurityBuffer[] securityBuffers) { SecurityBufferDescWrapper decryptBufferDescWrapper = new SecurityBufferDescWrapper(securityBuffers); //A variable of type ULONG that receives package-specific flags that indicate the quality of protection. //Only for out parameter. uint pfQop; uint hResult = NativeMethods.DecryptMessage( ref contextHandle, ref decryptBufferDescWrapper.securityBufferDesc, sequenceNumber, out pfQop); if (hResult == NativeMethods.SEC_E_OK) { SspiSecurityBuffer[] buffers = decryptBufferDescWrapper.securityBufferDesc.GetBuffers(); for (int i = 0; i < securityBuffers.Length; i++) { securityBuffers[i].Buffer = new byte[buffers[i].bufferLength]; if (buffers[i].pSecBuffer != IntPtr.Zero) { Marshal.Copy(buffers[i].pSecBuffer, securityBuffers[i].Buffer, 0, securityBuffers[i].Buffer.Length); securityBuffers[i].BufferType = (SecurityBufferType)buffers[i].bufferType; } } decryptBufferDescWrapper.FreeSecurityBufferDesc(); return true; } else { decryptBufferDescWrapper.FreeSecurityBufferDesc(); throw new SspiException("Decrypt failed.", hResult); } } /// <summary> /// Free credential handle /// </summary> /// <param name="credentialHandle">credential handle</param> internal static void FreeCredentialsHandle(ref SecurityHandle credentialHandle) { uint hResult = NativeMethods.FreeCredentialsHandle(ref credentialHandle); if (hResult == NativeMethods.SEC_E_OK) { credentialHandle.HighPart = IntPtr.Zero; credentialHandle.LowPart = IntPtr.Zero; } } /// <summary> /// Delete context handle /// </summary> /// <param name="contextHandle">context handle</param> internal static void DeleteSecurityContext(ref SecurityHandle contextHandle) { uint hResult = NativeMethods.DeleteSecurityContext(ref contextHandle); if (hResult == NativeMethods.SEC_E_OK) { contextHandle.LowPart = IntPtr.Zero; contextHandle.HighPart = IntPtr.Zero; } } /// <summary> /// Acquire credential with AcquireCredentialsHandle of SSPI. /// </summary> /// <param name="packageType">Security package type</param> /// <param name="accountCredential">Account credential</param> /// <param name="serverPrincipal">Server principal name</param> /// <param name="fCredentialUse">A flag that indicates how these credentials will be used.</param> /// <param name="credentialHandle">Credential handle</param> internal static void AcquireCredentialsHandle( SecurityPackageType packageType, AccountCredential accountCredential, string serverPrincipal, uint fCredentialUse, out SecurityHandle credentialHandle) { string stringPackage = SspiUtility.GetPackageStringName(packageType); SecurityInteger expiryTime; SecurityWinntAuthIdentity authIdentity = new SecurityWinntAuthIdentity(accountCredential); IntPtr pAuthData = IntPtr.Zero; SchannelCred schannelCred = new SchannelCred(); schannelCred.dwVersion = Consts.SCHANNEL_CRED_VERSION; schannelCred.cCreds = 0; schannelCred.paCred = IntPtr.Zero; CredSspCred credSsp = new CredSspCred(); switch (packageType) { case SecurityPackageType.Ntlm: case SecurityPackageType.Kerberos: case SecurityPackageType.Negotiate: pAuthData = SspiUtility.CreateAuthData(authIdentity); break; case SecurityPackageType.Schannel: pAuthData = SspiUtility.CreateAuthData(schannelCred); break; case SecurityPackageType.CredSsp: credSsp.Type = CredSspSubmitType.CredsspSubmitBufferBoth; credSsp.pSchannelCred = CreateAuthData(schannelCred); credSsp.pSpnegoCred = CreateAuthData(authIdentity); pAuthData = CreateAuthData(credSsp); break; //default, if other values, exception will be thrown by GetPackageStringName. default: throw new ArgumentException("Invlid packageType value.", "packageType"); } uint result = NativeMethods.AcquireCredentialsHandle( serverPrincipal, stringPackage, fCredentialUse, IntPtr.Zero, pAuthData, IntPtr.Zero, IntPtr.Zero, out credentialHandle, out expiryTime); //Free memory switch (packageType) { case SecurityPackageType.Ntlm: case SecurityPackageType.Kerberos: case SecurityPackageType.Negotiate: SspiUtility.FreeSecurityWinntAuthIdentity(authIdentity); break; case SecurityPackageType.Schannel: stringPackage = Schannel; SspiUtility.FreeSchannelCred(schannelCred); break; case SecurityPackageType.CredSsp: SspiUtility.FreeSecurityWinntAuthIdentity(authIdentity); SspiUtility.FreeSchannelCred(schannelCred); SspiUtility.FreeCredSspCred(credSsp); break; //default, if other values, exception will be thrown by GetPackageStringName. default: throw new ArgumentException("Invlid packageType value.", "packageType"); } Marshal.FreeHGlobal(pAuthData); if (result != NativeMethods.SEC_E_OK) { throw new SspiException("AquireCredentialsHandle failed", result); } } /// <summary> /// Acquire credential with AcquireCredentialsHandle of SSPI. /// </summary> /// <param name="packageType">Security package type</param> /// <param name="certificateCredential">Account credential</param> /// <param name="serverPrincipal">Server principal name</param> /// <param name="fCredentialUse">A flag that indicates how these credentials will be used.</param> /// <param name="credentialHandle">Credential handle</param> internal static void AcquireCredentialsHandle( SecurityPackageType packageType, CertificateCredential certificateCredential, string serverPrincipal, uint fCredentialUse, out SecurityHandle credentialHandle) { string stringPackage = SspiUtility.GetPackageStringName(packageType); SecurityInteger expiryTime = new SecurityInteger(); uint enabledProtocols; if (fCredentialUse == NativeMethods.SECPKG_CRED_OUTBOUND) { enabledProtocols = NativeMethods.ClientEnabledTlsProtocols; } else { enabledProtocols = NativeMethods.ServerEnabledTlsProtocols; } SchannelCred schannelCred = new SchannelCred(certificateCredential, enabledProtocols); CredSspCred sspCred = new CredSspCred(); IntPtr pAuthData = IntPtr.Zero; if (packageType == SecurityPackageType.Schannel) { pAuthData = SspiUtility.CreateAuthData(schannelCred); } else if (packageType == SecurityPackageType.CredSsp) { sspCred.pSchannelCred = SspiUtility.CreateAuthData(schannelCred); sspCred.pSpnegoCred = IntPtr.Zero; sspCred.Type = CredSspSubmitType.CredsspSubmitBufferBoth; pAuthData = SspiUtility.CreateAuthData(sspCred); } uint result = NativeMethods.AcquireCredentialsHandle( serverPrincipal, stringPackage, fCredentialUse, IntPtr.Zero, pAuthData, IntPtr.Zero, IntPtr.Zero, out credentialHandle, out expiryTime); //Free memory SspiUtility.FreeSchannelCred(schannelCred); if (pAuthData != IntPtr.Zero) { if (packageType == SecurityPackageType.CredSsp) { Marshal.FreeHGlobal(sspCred.pSchannelCred); } Marshal.FreeHGlobal(pAuthData); } if (result != NativeMethods.SEC_E_OK) { throw new SspiException("AquireCredentialsHandle fails.", result); } } /// <summary> /// Acquire credential with AcquireCredentialsHandle of DTLS. /// </summary> /// <param name="packageType">Security package type</param> /// <param name="certificateCredential">Account credential</param> /// <param name="serverPrincipal">Server principal name</param> /// <param name="fCredentialUse">A flag that indicates how these credentials will be used.</param> /// <param name="credentialHandle">Credential handle</param> internal static void DtlsAcquireCredentialsHandle( SecurityPackageType packageType, CertificateCredential certificateCredential, string serverPrincipal, uint fCredentialUse, out SecurityHandle credentialHandle) { string stringPackage = SspiUtility.GetPackageStringName(packageType); SecurityInteger expiryTime = new SecurityInteger(); uint enabledProtocols; if (fCredentialUse == NativeMethods.SECPKG_CRED_OUTBOUND) { enabledProtocols = NativeMethods.SP_PROT_DTLS_CLIENT; } else { enabledProtocols = NativeMethods.SP_PROT_DTLS_SERVER; } SchannelCred schannelCred = new SchannelCred(certificateCredential, enabledProtocols); CredSspCred sspCred = new CredSspCred(); IntPtr pAuthData = IntPtr.Zero; if (packageType == SecurityPackageType.Schannel) { pAuthData = SspiUtility.CreateAuthData(schannelCred); } else if (packageType == SecurityPackageType.CredSsp) { sspCred.pSchannelCred = SspiUtility.CreateAuthData(schannelCred); sspCred.pSpnegoCred = IntPtr.Zero; sspCred.Type = CredSspSubmitType.CredsspSubmitBufferBoth; pAuthData = SspiUtility.CreateAuthData(sspCred); } uint result = NativeMethods.AcquireCredentialsHandle( null, stringPackage, fCredentialUse, IntPtr.Zero, pAuthData, IntPtr.Zero, IntPtr.Zero, out credentialHandle, out expiryTime); //Free memory SspiUtility.FreeSchannelCred(schannelCred); if (pAuthData != IntPtr.Zero) { if (packageType == SecurityPackageType.CredSsp) { Marshal.FreeHGlobal(sspCred.pSchannelCred); } Marshal.FreeHGlobal(pAuthData); } if (result != NativeMethods.SEC_E_OK) { throw new SspiException("AquireCredentialsHandle fails.", result); } } #region Query context attributes /// <summary> /// Query context attribute by attribute name. /// </summary> /// <param name="contextHandle">context handle</param> /// <param name="contextAttribute">context attribute name</param> /// <returns>Pointer of attribute value.</returns> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal static object QueryContextAttributes(ref SecurityHandle contextHandle, string contextAttribute) { uint attribute = 0; IntPtr pBuffer = IntPtr.Zero; string stringAttribute = contextAttribute.ToUpper(CultureInfo.InvariantCulture); switch (stringAttribute) { case SECPKG_ATTR_SIZES: attribute = NativeMethods.SECPKG_ATTR_SIZES; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityPackageContextSizes))); break; case SECPKG_ATTR_LIFESPAN: attribute = NativeMethods.SECPKG_ATTR_LIFESPAN; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityPackageContextLifespan))); break; case SECPKG_ATTR_STREAM_SIZES: attribute = NativeMethods.SECPKG_ATTR_STREAM_SIZES; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityPackageContextStreamSizes))); break; case SECPKG_ATTR_KEY_INFO: attribute = NativeMethods.SECPKG_ATTR_KEY_INFO; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SspiSecurityPackageContextKeyInfo))); break; case SECPKG_ATTR_AUTHORITY: attribute = NativeMethods.SECPKG_ATTR_AUTHORITY; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityPackageContextAuthority))); break; case SECPKG_ATTR_PASSWORD_EXPIRY: attribute = NativeMethods.SECPKG_ATTR_PASSWORD_EXPIRY; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityInteger))); break; case SECPKG_ATTR_SESSION_KEY: attribute = NativeMethods.SECPKG_ATTR_SESSION_KEY; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityPackageContextSessionKey))); break; case SECPKG_ATTR_PACKAGE_INFO: attribute = NativeMethods.SECPKG_ATTR_PACKAGE_INFO; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr))); break; case SECPKG_ATTR_NEGOTIATION_INFO: attribute = NativeMethods.SECPKG_ATTR_NEGOTIATION_INFO; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SspiSecurityPackageContextNegotiationInfo))); break; case SECPKG_ATTR_NATIVE_NAMES: attribute = NativeMethods.SECPKG_ATTR_NATIVE_NAMES; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SspiSecurityPackageContextNativeNames))); break; case SECPKG_ATTR_FLAGS: attribute = NativeMethods.SECPKG_ATTR_FLAGS; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(uint))); break; case SECPKG_ATTR_TARGET_INFORMATION: attribute = NativeMethods.SECPKG_ATTR_TARGET_INFORMATION; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityPackageContextTargetInformation))); break; case SECPKG_ATTR_REMOTE_CERT_CONTEXT: attribute = NativeMethods.SECPKG_ATTR_REMOTE_CERT_CONTEXT; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr))); break; case SECPKG_ATTR_LOCAL_CERT_CONTEXT: attribute = NativeMethods.SECPKG_ATTR_LOCAL_CERT_CONTEXT; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr))); break; case SECPKG_ATTR_ROOT_STORE: attribute = NativeMethods.SECPKG_ATTR_ROOT_STORE; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr))); break; case SECPKG_ATTR_ISSUER_LIST_EX: attribute = NativeMethods.SECPKG_ATTR_ISSUER_LIST_EX; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SspiSecurityPackageContextIssuerListInfo))); break; case SECPKG_ATTR_CONNECTION_INFO: attribute = NativeMethods.SECPKG_ATTR_CONNECTION_INFO; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityPackageContextConnectionInfo))); break; case SECPKG_ATTR_EAP_KEY_BLOCK: attribute = NativeMethods.SECPKG_ATTR_EAP_KEY_BLOCK; pBuffer = Marshal.AllocHGlobal(SchannelKeySize + SchannelIvSize); break; case SECPKG_ATTR_APP_DATA: attribute = NativeMethods.SECPKG_ATTR_APP_DATA; pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SecurityPackageContextSessionAppData))); break; default: throw new ArgumentException("Error context attribute name.", "contextAttribute"); } uint hResult = NativeMethods.QueryContextAttributes(ref contextHandle, attribute, pBuffer); if (hResult == NativeMethods.SEC_E_OK) { object attributeValue; switch (stringAttribute) { case SECPKG_ATTR_SIZES: attributeValue = Marshal.PtrToStructure(pBuffer, typeof(SecurityPackageContextSizes)); break; case SECPKG_ATTR_LIFESPAN: attributeValue = Marshal.PtrToStructure(pBuffer, typeof(SecurityPackageContextLifespan)); break; case SECPKG_ATTR_STREAM_SIZES: attributeValue = Marshal.PtrToStructure(pBuffer, typeof(SecurityPackageContextStreamSizes)); break; case SECPKG_ATTR_KEY_INFO: SspiSecurityPackageContextKeyInfo keyInfo; keyInfo = (SspiSecurityPackageContextKeyInfo)Marshal.PtrToStructure( pBuffer, typeof(SspiSecurityPackageContextKeyInfo)); attributeValue = new SecurityPackageContextKeyInfo(keyInfo); Marshal.FreeHGlobal(keyInfo.sSignatureAlgorithmName); Marshal.FreeHGlobal(keyInfo.sEncryptAlgorithmName); break; case SECPKG_ATTR_AUTHORITY: SecurityPackageContextAuthority authority; authority = (SecurityPackageContextAuthority)Marshal.PtrToStructure( pBuffer, typeof(SecurityPackageContextAuthority)); attributeValue = Marshal.PtrToStringUni(authority.sAuthorityName); break; case SECPKG_ATTR_PASSWORD_EXPIRY: attributeValue = Marshal.PtrToStructure(pBuffer, typeof(SecurityInteger)); break; case SECPKG_ATTR_SESSION_KEY: SecurityPackageContextSessionKey sessionKey; sessionKey = (SecurityPackageContextSessionKey)Marshal.PtrToStructure( pBuffer, typeof(SecurityPackageContextSessionKey)); attributeValue = sessionKey.GetSessionKey(); Marshal.FreeHGlobal(sessionKey.SessionKey); break; case SECPKG_ATTR_PACKAGE_INFO: SspiSecurityPackageInformation packageInfo; packageInfo = (SspiSecurityPackageInformation)Marshal.PtrToStructure( Marshal.ReadIntPtr(pBuffer), typeof(SspiSecurityPackageInformation)); attributeValue = new SecurityPackageInformation(packageInfo); break; case SECPKG_ATTR_NEGOTIATION_INFO: SspiSecurityPackageContextNegotiationInfo negotiationInfo; negotiationInfo = (SspiSecurityPackageContextNegotiationInfo)Marshal.PtrToStructure( pBuffer, typeof(SspiSecurityPackageContextNegotiationInfo)); attributeValue = new SecurityPackageContextNegotiationInfo(negotiationInfo); Marshal.FreeHGlobal(negotiationInfo.PackageInfo); break; case SECPKG_ATTR_NATIVE_NAMES: SspiSecurityPackageContextNativeNames nativeNames; nativeNames = (SspiSecurityPackageContextNativeNames)Marshal.PtrToStructure( pBuffer, typeof(SspiSecurityPackageContextNativeNames)); attributeValue = new SecurityPackageContextNativeNames(nativeNames); break; case SECPKG_ATTR_FLAGS: attributeValue = (uint)Marshal.ReadInt32(pBuffer); break; case SECPKG_ATTR_TARGET_INFORMATION: SecurityPackageContextTargetInformation targetInformation; targetInformation = (SecurityPackageContextTargetInformation)Marshal.PtrToStructure( pBuffer, typeof(SecurityPackageContextTargetInformation)); attributeValue = targetInformation.GetTargetInfo(); Marshal.FreeHGlobal(targetInformation.MarshalledTargetInfo); break; case SECPKG_ATTR_REMOTE_CERT_CONTEXT: SspiCertContext remoteCertContext; remoteCertContext = (SspiCertContext)Marshal.PtrToStructure( Marshal.ReadIntPtr(pBuffer), typeof(SspiCertContext)); attributeValue = new CertContext(remoteCertContext); Marshal.FreeHGlobal(remoteCertContext.pbCertEncoded); break; case SECPKG_ATTR_LOCAL_CERT_CONTEXT: SspiCertContext localCertContext; localCertContext = (SspiCertContext)Marshal.PtrToStructure( Marshal.ReadIntPtr(pBuffer), typeof(SspiCertContext)); attributeValue = new CertContext(localCertContext); Marshal.FreeHGlobal(localCertContext.pbCertEncoded); break; case SECPKG_ATTR_ROOT_STORE: attributeValue = Marshal.ReadIntPtr(pBuffer); break; case SECPKG_ATTR_ISSUER_LIST_EX: SspiSecurityPackageContextIssuerListInfo issuerList; issuerList = (SspiSecurityPackageContextIssuerListInfo)Marshal.PtrToStructure( pBuffer, typeof(SspiSecurityPackageContextIssuerListInfo)); attributeValue = new SecurityPackageContextIssuerListInfo(issuerList); NativeMethods.FreeContextBuffer(issuerList.aIssuers); break; case SECPKG_ATTR_CONNECTION_INFO: SecurityPackageContextConnectionInfo connectionInfo; connectionInfo = (SecurityPackageContextConnectionInfo)Marshal.PtrToStructure( pBuffer, typeof(SecurityPackageContextConnectionInfo)); attributeValue = connectionInfo; break; case SECPKG_ATTR_EAP_KEY_BLOCK: SecurityPackageContextEapKeyBlock eapKeyBlock = new SecurityPackageContextEapKeyBlock(); eapKeyBlock.rgbKeys = new byte[SchannelKeySize]; Marshal.Copy(pBuffer, eapKeyBlock.rgbKeys, 0, SchannelKeySize); eapKeyBlock.rgbIVs = new byte[SchannelIvSize]; Marshal.Copy(new IntPtr(pBuffer.ToInt64() + SchannelKeySize), eapKeyBlock.rgbIVs, 0, SchannelIvSize); attributeValue = eapKeyBlock; break; case SECPKG_ATTR_APP_DATA: SecurityPackageContextSessionAppData sessionAppData; sessionAppData = (SecurityPackageContextSessionAppData)Marshal.PtrToStructure( pBuffer, typeof(SecurityPackageContextSessionAppData)); attributeValue = sessionAppData.GetAppData(); Marshal.FreeHGlobal(sessionAppData.pbAppData); break; default: throw new ArgumentException("Error context attribute name.", "contextAttribute"); } Marshal.FreeHGlobal(pBuffer); return attributeValue; } else { Marshal.FreeHGlobal(pBuffer); throw new SspiException("QueryContextAttributes failed.", hResult); } } #endregion #endregion Windows SSPI #region Ntsec API /// <summary> /// retrieve the local machine account password. /// </summary> /// <returns> /// a string that specifies the local macine account password. /// </returns> /// <exception cref="InvalidOperationException"> /// thrown when LsaOpenPolicy STATUS_ACCESS_DENIED, please run the program as administrator /// </exception> /// <exception cref="InvalidOperationException"> /// thrown when LsaOpenPolicy failed. /// </exception> /// <exception cref="InvalidOperationException"> /// thrown when LsaRetrievePrivateData failed. /// </exception> /// <exception cref="InvalidOperationException"> /// thrown when local machine account is invalid /// </exception> /// <exception cref="InvalidOperationException"> /// thrown when local machine account password is invalid /// </exception> public static string RetrieveLocalMachineAccountPassword() { NtStatus ntsResult = NtStatus.STATUS_SUCCESS; // Open PolicyHandle IntPtr policyHandle = IntPtr.Zero; LsaObjectAttributes objectAttributes = new LsaObjectAttributes(); ntsResult = NativeMethods.LsaOpenPolicy( IntPtr.Zero, // NULL, the function opens the Policy object on the local system. ref objectAttributes, AccessMask.POLICY_GET_PRIVATE_INFORMATION, out policyHandle); if (ntsResult == NtStatus.STATUS_ACCESS_DENIED) { throw new InvalidOperationException( "LsaOpenPolicy STATUS_ACCESS_DENIED, please run the program as administrator"); } if (ntsResult != NtStatus.STATUS_SUCCESS) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "LsaOpenPolicy failed, Result={0}", ntsResult)); } IntPtr privateData = IntPtr.Zero; LsaUnicodeString keyName = new LsaUnicodeString(); try { // Retrieve PrivateData string localMachineNameKey = "$MACHINE.ACC"; keyName.Buffer = Marshal.StringToHGlobalUni(localMachineNameKey); keyName.Length = (ushort)(UnicodeEncoding.CharSize * localMachineNameKey.Length); keyName.MaximumLength = (ushort)(keyName.Length + UnicodeEncoding.CharSize); ntsResult = NativeMethods.LsaRetrievePrivateData(policyHandle, ref keyName, out privateData); if (ntsResult != NtStatus.STATUS_SUCCESS) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "LsaRetrievePrivateData failed, Result={0}", ntsResult)); } //Get Local Machine Account Password LsaUnicodeString localMachineAccount = (LsaUnicodeString)Marshal.PtrToStructure(privateData, typeof(LsaUnicodeString)); if (localMachineAccount.Buffer == IntPtr.Zero) { throw new InvalidOperationException("local machine account is invalid"); } if (localMachineAccount.Length == 0) { throw new InvalidOperationException("local machine account password is invalid"); } return Marshal.PtrToStringUni( localMachineAccount.Buffer, localMachineAccount.Length / UnicodeEncoding.CharSize); } finally { if (privateData != IntPtr.Zero) { NativeMethods.LsaFreeMemory(privateData); } if (keyName.Buffer != IntPtr.Zero) { Marshal.FreeHGlobal(keyName.Buffer); } if (policyHandle != IntPtr.Zero) { NativeMethods.LsaClose(policyHandle); } } } #endregion } }
45.049421
144
0.571796
[ "MIT" ]
G-arj/WindowsProtocolTestSuites
ProtoSDK/Sspi/SspiUtility.cs
58,341
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace StackList { using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; public partial class MainPage : global::Xamarin.Forms.ContentPage { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private void InitializeComponent() { this.LoadFromXaml(typeof(MainPage)); } } }
31.92
102
0.516291
[ "MIT" ]
tristanmhmx/StackList
StackList/StackList/StackList/obj/Debug/StackList.MainPage.xaml.g.cs
798
C#
using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using GeminiGraphEditor; using WDE.QuestChainEditor.Editor.ViewModels; namespace WDE.QuestChainEditor.Editor.Views { /// <summary> /// Interaction logic for BlueprintGraphControlView.xaml /// </summary> public partial class BlueprintGraphControlView : UserControl { private bool dragging; private bool hadMouseDown; private Point originalContentMouseDownPoint; private bool previouslyHadSelected; public BlueprintGraphControlView() { InitializeComponent(); } private GraphViewModel ViewModel => (GraphViewModel) DataContext; private void OnGraphControlConnectionDragStarted(object sender, ConnectionDragStartedEventArgs e) { dragging = true; ConnectorViewModel sourceConnector = (ConnectorViewModel) e.SourceConnector.DataContext; Point currentDragPoint = Mouse.GetPosition(GraphControl); ConnectionViewModel connection = ViewModel.OnConnectionDragStarted(sourceConnector, currentDragPoint); e.Connection = connection; } private void OnGraphControlConnectionDragging(object sender, ConnectionDraggingEventArgs e) { Point currentDragPoint = Mouse.GetPosition(GraphControl); ConnectionViewModel connection = (ConnectionViewModel) e.Connection; ViewModel.OnConnectionDragging(currentDragPoint, connection); } private void OnGraphControlConnectionDragCompleted(object sender, ConnectionDragCompletedEventArgs e) { dragging = false; Point currentDragPoint = Mouse.GetPosition(GraphControl); ConnectorViewModel sourceConnector = (ConnectorViewModel) e.SourceConnector.DataContext; ConnectionViewModel newConnection = (ConnectionViewModel) e.Connection; ViewModel.OnConnectionDragCompleted(currentDragPoint, newConnection, sourceConnector); } protected override void OnPreviewMouseDown(MouseButtonEventArgs e) { Focus(); base.OnPreviewMouseDown(e); } protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.Delete) { ViewModel.DeleteSelectedConnections(); ViewModel.DeleteSelectedElements(); } base.OnKeyDown(e); } private void GraphControl_MouseDown(object sender, MouseButtonEventArgs e) { hadMouseDown = true; previouslyHadSelected = ViewModel.SelectedElements.Count() > 0 || ViewModel.SelectedConnections.Count() > 0; } private void GraphControl_MouseUp(object sender, MouseButtonEventArgs e) { if (!dragging && hadMouseDown && !previouslyHadSelected && ViewModel.SelectedElements.Count() == 0 && ViewModel.SelectedConnections.Count() == 0) { Point currentDragPoint = Mouse.GetPosition(GraphControl); ViewModel.ShowPicker(currentDragPoint); } previouslyHadSelected = false; hadMouseDown = false; } } }
36.955056
120
0.660079
[ "Unlicense" ]
Crypticaz/WoWDatabaseEditor
WDE.QuestChainEditor/Editor/Views/BlueprintGraphControlView.xaml.cs
3,291
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using MawBlog.Models; using MawBlog.Data; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore; using System.IO; using System.Collections; using MawBlog.ViewModels; namespace MawBlog.Controllers { public class HomeController : Controller { private readonly ApplicationDbContext _context; private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger, ApplicationDbContext context) { _context = context; _logger = logger; } public async Task<IActionResult> Index(int page) { var posted = _context.Post.Where(p => p.IsPublished).ToList().Count; if (page < 0) { page = 0; } if(page * 5 > _context.Post.ToList().Count) { page = _context.Post.ToList().Count / 5; } var posts = _context.Post .Where(p => p.IsPublished) .OrderByDescending(p => p.Created) .Include(p => p.Blog) .Skip(page * 5).Take(5); var blogs = _context.Blog; var tags = _context.Tag; CategoriesVM categories = new CategoriesVM() { Blogs = await blogs.ToListAsync(), Posts = await posts.ToListAsync(), Tags = await tags.ToListAsync(), PageNum = page, TotalPosts = _context.Post.ToList().Count }; return View(categories); } public async Task<IActionResult> Results(string SearchString) { var posts = from p in _context.Post select p; var blogs = _context.Blog; var tags = _context.Tag; if (!String.IsNullOrEmpty(SearchString)) { posts = posts.Where(p => p.Title.Contains(SearchString) || p.Abstract.Contains(SearchString) || p.Content.Contains(SearchString)); //return View("Index", await posts.Include(p => p.Blog).ToListAsync()); } //return View("Index", await posts.Include(p => p.Blog).ToListAsync()); CategoriesVM categories = new CategoriesVM() { Blogs = await blogs.ToListAsync(), Posts = await posts.ToListAsync(), Tags = await tags.ToListAsync() }; return View("Index", categories); } public async Task<IActionResult> Categories() { var id = RouteData.Values["id"].ToString(); var posts = _context.Post.Where(p => p.BlogId == Int32.Parse(id) && p.IsPublished == true).Include(p => p.Blog); var blogs = _context.Blog; var tags = _context.Tag; CategoriesVM categories = new CategoriesVM() { Blogs = await blogs.ToListAsync(), Posts = await posts.ToListAsync(), Tags = await tags.ToListAsync() }; return View("Index", categories); } public async Task<IActionResult> Tag() { var name = RouteData.Values["id"].ToString(); var posts = _context.Tag.Where(t => t.Name == name).Select(t => t.Post); var blogs = _context.Blog; CategoriesVM categories = new CategoriesVM() { Blogs = await blogs.ToListAsync(), Posts = await posts.ToListAsync(), Tags = await _context.Tag.ToListAsync() }; return View("Index", categories); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
35.2
146
0.547822
[ "MIT" ]
mackenzieweaver/MawBlog
MawBlog/Controllers/HomeController.cs
4,226
C#
using PortableDeviceApiLib; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; namespace MediaDevices { /// <summary> /// This class provides functions for creating and searching for portable devices. /// <para>In oposite to previous version this manager provides possibility to use /// MTP from separate STA threads, just create once manager instance in each thread.</para> /// </summary> public class MediaManager : IDisposable { private readonly PortableDeviceManager portableDeviceManager; private List<MediaDevice> devices; private List<MediaDevice> privateDevices; /// <summary> /// Creates a new instance of media manager. /// <para>Remember that this instance is tidly connected with <see cref="PortableDeviceManager"/> /// instance and its parent STA thread. Do not try to call this object outside it's apartment, /// it will not work. You will get <see cref="COMException"/>.</para> /// <para><see cref="MediaManager"/> creates its own instance of COM portable device manager /// so that you are able to fork MTP connection from any STA thread.</para> /// <para>To use it, create a new instance of this manager and start fetching devices.</para> /// </summary> public MediaManager() { this.portableDeviceManager = new PortableDeviceManager(); } /// <summary> /// Returns an enumerable collection of currently available portable devices. /// </summary> /// <returns>>An enumerable collection of portable devices currently available.</returns> public IEnumerable<MediaDevice> GetDevices() { portableDeviceManager.RefreshDeviceList(); // get number of devices uint count = 0; portableDeviceManager.GetDevices(null, ref count); if (count == 0) { return new List<MediaDevice>(); } // get device IDs var deviceIds = new string[count]; portableDeviceManager.GetDevices(deviceIds, ref count); if (devices == null) { devices = deviceIds.Select(d => new MediaDevice(d, this.portableDeviceManager)).ToList(); } else { UpdateDeviceList(devices, deviceIds); } return devices; } private void UpdateDeviceList(List<MediaDevice> deviceList, string[] deviceIdList) { var idList = deviceIdList.ToList(); // remove var remove = deviceList.Where(d => !idList.Contains(d.DeviceId)).Select(d => d.DeviceId).ToList(); deviceList.RemoveAll(d => remove.Contains(d.DeviceId)); // add var add = idList.Where(id => !deviceList.Select(d => d.DeviceId).Contains(id)).ToList(); deviceList.AddRange(add.Select(id => new MediaDevice(id, this.portableDeviceManager))); } /// <summary> /// Returns an enumerable collection of currently available private portable devices. /// </summary> /// <returns>>An enumerable collection of private portable devices currently available.</returns> public IEnumerable<MediaDevice> GetPrivateDevices() { portableDeviceManager.RefreshDeviceList(); // get number of devices uint count = 0; portableDeviceManager.GetPrivateDevices(null, ref count); if (count == 0) { return new List<MediaDevice>(); } // get device IDs var deviceIds = new string[count]; portableDeviceManager.GetPrivateDevices(deviceIds, ref count); if (privateDevices == null) { privateDevices = deviceIds.Select(d => new MediaDevice(d, this.portableDeviceManager)).ToList(); } else { UpdateDeviceList(privateDevices, deviceIds); } return privateDevices; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting /// unmanaged resources. /// </summary> public void Dispose() { if (devices != null) { foreach (var dev in devices) { dev.DestroyDevice(); } devices = null; } } /// <summary> /// Check if a device with given description is connected with MTP / PTP enabled. /// By default, some Android device is connected as USB charging only. /// </summary> /// <param name="deviceDescription">Device description</param> /// <returns>true if device connected with MTP / PTP capability.</returns> public bool IsDeviceConnected(string deviceDescription) { MediaDevice ptrDevice = GetDevices().FirstOrDefault(x => x.Description == deviceDescription); if (ptrDevice == null) return false; //Enumerate Directory to ensure Media Device in MTP or PTP Mode. //By default, Android device is connected as USB Charging only with no file access. ptrDevice.Connect(); MediaDirectoryInfo rootInfo = ptrDevice.GetRootDirectory(); try { var dirs = rootInfo.EnumerateDirectories(); if (rootInfo.EnumerateDirectories().Count() > 0) { ptrDevice.Dispose(); ptrDevice = null; return true; } } catch { ptrDevice.Dispose(); ptrDevice = null; } return false; } /// <summary> /// Find and return device by description. Only return device which connected as MTP / PTP. /// </summary> /// <param name="deviceDescription">Device description</param> /// <returns></returns> public MediaDevice GetDevice(string deviceDescription) { MediaDevice ptrDevice = GetDevices().FirstOrDefault(x => x.Description == deviceDescription); if (ptrDevice == null) return null; //Enumerate Directory to ensure Media Device in MTP or PTP Mode. //By default, Android device is connected as USB Charging only with no file access. ptrDevice.Connect(); MediaDirectoryInfo rootInfo = ptrDevice.GetRootDirectory(); try { var dirs = rootInfo.EnumerateDirectories(); if (rootInfo.EnumerateDirectories().Count() > 0) { return ptrDevice; } } catch { ptrDevice.Dispose(); ptrDevice = null; } return null; } } }
38.251366
112
0.575714
[ "MIT" ]
Code-Artist/MediaDevicesExt
MediaDevicesExt/MediaManager.cs
7,002
C#
using System; using System.Collections.Generic; using System.Linq; namespace HalloJoe.Extensions { /// <summary> /// IList extension methods /// </summary> public static class ListExtensions { /// <summary> /// Shuffle IList /// </summary> internal static Random _rnd = new Random(); /// <summary> /// Shuffle list using Fisher-yates algorithm. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = _rnd.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="size"></param> /// <returns></returns> public static IEnumerable<IList<T>> GetPartitions<T>(this IList<T> list, int size) => list.AsEnumerable().GetPartitions(size); } }
27.222222
94
0.478367
[ "MIT" ]
hallojoe/HalloJoe.Extensions
Extensions.Net46/List.cs
1,227
C#
using Microsoft.SPOT.Hardware; namespace MFMock { internal class OutputPortWrapper:IOutputPort { private readonly OutputPort mPort; public OutputPortWrapper(OutputPort port) { mPort = port; } public bool Read() { return mPort.Read(); } public void Write(bool state) { mPort.Write(state); } public void Dispose() { mPort.Dispose(); } } }
18.666667
49
0.505952
[ "Apache-2.0" ]
mvphelps/MFMock
MFMock/OutputPortWrapper.cs
506
C#
using IBM.Data.DB2.iSeries; using OrmTxcSql.Data; namespace OrmTxcSql.DB2.Data { /// <summary> /// プロパティの接続文字列を戻すデータソース。 /// </summary> public class DB2ConnectionStringBuilderDataSource : DataSource { public iDB2ConnectionStringBuilder ConnectionStringBuilder { get; set; } public override string GetConnectionString() => this.ConnectionStringBuilder.ToString(); } }
20.380952
80
0.682243
[ "MIT" ]
tanoue13/OrmTxcSql
Sources/OrmTxcSql.DB2/Data/DB2ConnectionStringBuilderDataSource.cs
472
C#
/* * Created by: Peter @sHTiF Stefcek */ using System; using UnityEditor; using UnityEngine; namespace VertexColorPainter.Editor { [Serializable] public class VCPEditorConfig : ScriptableObject { [HideInInspector] public bool enabled = false; [HideInInspector] public bool enableClosestPaint = false; [HideInInspector] public ChannelType channelType; [HideInInspector] public ToolType toolType; [HideInInspector] public float brushSize = 1; [HideInInspector] public Color brushColor = Color.white; [HideInInspector] public bool lockToSubmesh = false; [HideInInspector] public bool autoFill = false; [HideInInspector] public bool previousOutlineSetting = false; [HideInInspector] public bool enableUv0Editing = false; [HideInInspector] public bool overlayRender = true; [HideInInspector] public bool autoMeshFraming = false; [HideInInspector] public Color colorChangeCurrent = Color.white; [HideInInspector] public Color colorChangeNew = Color.white; public float brushOutlineSize = 0.004f; public float forcedMinBrushSize = 1f; public float forcedMaxBrushSize = 10f; public Material vertexColorMaterial; public static VCPEditorConfig Create() { var config = (VCPEditorConfig)AssetDatabase.LoadAssetAtPath( "Assets/Resources/Editor/VertexColorPainterEditorConfig.asset", typeof(VCPEditorConfig)); if (config == null) { config = ScriptableObject.CreateInstance<VCPEditorConfig>(); if (config != null) { if (!AssetDatabase.IsValidFolder("Assets/Resources")) { AssetDatabase.CreateFolder("Assets", "Resources"); } if (!AssetDatabase.IsValidFolder("Assets/Resources/Editor")) { AssetDatabase.CreateFolder("Assets/Resources", "Editor"); } AssetDatabase.CreateAsset(config, "Assets/Resources/Editor/VertexColorPainterEditorConfig.asset"); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } } return config; } } }
27.042553
118
0.573171
[ "MIT" ]
pshtif/VertexColorPainter
Editor/Scripts/VCPEditorConfig.cs
2,542
C#
using System; using MSFramework.Ef.Design; using Template.Infrastructure; namespace Template.API { public class DesignTimeDbContextFactory : DesignTimeDbContextFactoryBase<AppDbContext> { protected override IServiceProvider GetServiceProvider() { return Program.CreateHostBuilder(new string[0]).Build().Services; } } }
22.2
68
0.795796
[ "MIT" ]
jonechenug/MSFramework
template/Content/src/Template.API/DesignTimeDbContextFactory.cs
333
C#
using System; namespace WT.Ecommerce.Domain.Models { public class PaginationLinks { public PaginationLinks(string endPoint, int recordCount, int skip, int limit) { RecordCount = recordCount; PageCount = (int)Math.Ceiling((double)recordCount / limit) - 1; Self = $"{endPoint}?skip={skip}&limit={limit}"; First= $"{endPoint}?skip=0&limit={limit}"; Prev = skip == 0 ? string.Empty : $"{endPoint}?skip={skip - limit}&limit={limit}"; Next = skip < PageCount * limit ? $"{endPoint}?skip={skip +limit}&limit={limit}":string.Empty; Last = $"{endPoint}?skip={PageCount * limit}&limit={limit}"; } public string Self { get; private set; } public string First { get; private set; } public string Last { get; private set; } public string Prev { get; private set; } public string Next { get; private set; } public int RecordCount { get; private set; } public int PageCount { get; private set; } } }
36.46875
106
0.534704
[ "MIT" ]
farzin2171/WT.EcommerceProject
WT.ECommerce/WT.Ecommerce.Domain/Models/PaginationLinks.cs
1,169
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Logfile.Structured.UnitTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
40.5
62
0.839506
[ "MIT" ]
KristianVirkus/LogfileStructured
src/Logfile.Structured/AssemblyInfo.cs
164
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; namespace Microsoft.AspNetCore.Mvc.Razor { public interface IRazorPage { ViewContext ViewContext { get; set; } IHtmlContent BodyContent { get; set; } bool IsLayoutBeingRendered { get; set; } string Path { get; set; } string Layout { get; set; } IDictionary<string, RenderAsyncDelegate> PreviousSectionWriters { get; set; } IDictionary<string, RenderAsyncDelegate> SectionWriters { get; } Task ExecuteAsync(); void EnsureRenderedBodyOrSections(); } }
26.09375
95
0.697006
[ "MIT" ]
dougbu/razor-tooling
src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim.Version1_X/Microsoft.AspNetCore.Mvc.Razor/IRazorPage.cs
837
C#
using System.Collections.Generic; using System.Linq; namespace MyFirstCompiler.CodeAnalysis { class SyntaxToken : SyntaxNode { public override SyntaxKind Kind { get; } public int Position { get; } public string Text { get; } public object Value { get; } public override IEnumerable<SyntaxNode> GetChildren() { return Enumerable.Empty<SyntaxNode>(); } public SyntaxToken(SyntaxKind kind, int position, string text, object value) { Kind = kind; Position = position; Text = text; Value = value; } public SyntaxToken(SyntaxKind kind, int position, char text, object value) : this(kind, position, text.ToString(), value) { } } }
26.387097
130
0.577017
[ "Apache-2.0" ]
LindaLawton/MyFirstCompiler
src/MyFirstCompiler/CodeAnalysis/SyntaxToken.cs
820
C#
using FakeSurveyGenerator.Application.Common.Identity; namespace FakeSurveyGenerator.Infrastructure.Identity { internal sealed class OAuthUser : IUser { public string Id { get; init; } public string DisplayName { get; init; } public string EmailAddress { get; init; } public OAuthUser() { } // Used for System.Text.Json deserialization public OAuthUser(string id, string displayName, string emailAddress) : this() { Id = id; DisplayName = displayName; EmailAddress = emailAddress; } } }
28.333333
85
0.633613
[ "MIT" ]
MarcelMichau/fake-survey-generator
src/server/FakeSurveyGenerator.Infrastructure/Identity/OAuthUser.cs
597
C#
namespace AngleSharp.Html.LinkRels { using AngleSharp.Dom; using AngleSharp.Html.Dom; using AngleSharp.Io.Processors; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading.Tasks; class ImportLinkRelation : BaseLinkRelation { #region Fields private static readonly ConditionalWeakTable<IDocument, ImportList> ImportLists = new ConditionalWeakTable<IDocument, ImportList>(); private Boolean _async; #endregion #region ctor public ImportLinkRelation(IHtmlLinkElement link) : base(link, new DocumentRequestProcessor(link?.Owner.Context)) { } #endregion #region Properties public IDocument Import => (Processor as DocumentRequestProcessor)?.ChildDocument; public Boolean IsAsync => _async; #endregion #region Methods /// <summary> /// See http://www.w3.org/TR/html-imports/#dfn-import-request. /// </summary> public override Task LoadAsync() { var link = Link; var document = link.Owner; var list = ImportLists.GetOrCreateValue(document); var location = Url; var processor = Processor; var item = new ImportEntry { Relation = this, IsCycle = location != null && CheckCycle(document, location) }; list.Add(item); if (location != null && !item.IsCycle) { var request = link.CreateRequestFor(location); _async = link.HasAttribute(AttributeNames.Async); return processor?.ProcessAsync(request); } return null; } #endregion #region Helpers private static Boolean CheckCycle(IDocument document, Url location) { var ancestor = document.ImportAncestor; while (ancestor != null && ImportLists.TryGetValue(ancestor, out var list)) { if (list.Contains(location)) { return true; } ancestor = ancestor.ImportAncestor; } return false; } #endregion #region Import List private sealed class ImportList { private readonly List<ImportEntry> _list; public ImportList() { _list = new List<ImportEntry>(); } public Boolean Contains(Url location) { for (var i = 0; i < _list.Count; i++) { Url relationUrl = _list[i].Relation.Url; if (relationUrl != null && relationUrl.Equals(location)) { return true; } } return false; } public void Add(ImportEntry item) { _list.Add(item); } public void Remove(ImportEntry item) { _list.Remove(item); } } private struct ImportEntry { public ImportLinkRelation Relation; public Boolean IsCycle; } #endregion } }
25.514925
140
0.513016
[ "MIT" ]
bdbai/AngleSharp
src/AngleSharp/Html/LinkRels/ImportLinkRelation.cs
3,419
C#
// *********************************************************************** // Assembly : HZH_Controls // Created : 08-23-2019 // // *********************************************************************** // <copyright file="UCProcessWave.Designer.cs"> // Copyright by Huang Zhenghui(黄正辉) All, QQ group:568015492 QQ:623128629 Email:623128629@qq.com // </copyright> // // Blog: https://www.cnblogs.com/bfyx // GitHub:https://github.com/kwwwvagaa/NetWinformControl // gitee:https://gitee.com/kwwwvagaa/net_winform_custom_control.git // // If you use this code, please keep this note. // *********************************************************************** namespace HZH_Controls.Controls { /// <summary> /// Class UCProcessWave. /// Implements the <see cref="HZH_Controls.Controls.UCControlBase" /> /// </summary> /// <seealso cref="HZH_Controls.Controls.UCControlBase" /> partial class UCProcessWave { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 组件设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.ucWave1 = new HZH_Controls.Controls.UCWave(); this.SuspendLayout(); // // ucWave1 // this.ucWave1.Dock = System.Windows.Forms.DockStyle.Bottom; this.ucWave1.Location = new System.Drawing.Point(0, 140); this.ucWave1.Name = "ucWave1"; this.ucWave1.Size = new System.Drawing.Size(150, 10); this.ucWave1.TabIndex = 0; this.ucWave1.Text = "ucWave1"; this.ucWave1.WaveColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(77)))), ((int)(((byte)(59))))); this.ucWave1.WaveHeight = 15; this.ucWave1.WaveSleep = 100; this.ucWave1.WaveWidth = 100; // // UCProcessWave // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(231)))), ((int)(((byte)(237))))); this.Controls.Add(this.ucWave1); this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.Name = "UCProcessWave"; this.Size = new System.Drawing.Size(150, 150); this.ResumeLayout(false); } #endregion /// <summary> /// The uc wave1 /// </summary> private UCWave ucWave1; } }
35.793103
137
0.51124
[ "Apache-2.0" ]
DotNetFrameWork/NetWinformControl
HZH_Controls/HZH_Controls/Controls/Process/UCProcessWave.Designer.cs
3,276
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using net.sxtrader.bftradingstrategies.lsparserinterfaces; using System.Xml; using net.sxtrader.bftradingstrategies.sxhelper; using System.Threading; using System.Diagnostics; using System.Globalization; using net.sxtrader.muk; namespace net.sxtrader.bftradingstrategies.livescoreparser { enum MATCHSTATE { FIRSTHALF = 2, HT = 3, SECONDHALF = 4, ENDED = 5 }; class LiveScore2 : IScore { private int _matchId; private int _leagueId; private int _leagueIdParent; private int _sid; private int _kid; private int _lnr; private DateTime _startTime; private int _c1; private int _c2; private int _sma; private int _h0; private int _h1; private int _h2; private int _h3; private int _g0; private int _g1; private int _g2; private int _g3; private ulong _hid; private ulong _gid; private int _scoreA = 0; private int _scoreB = 0; private String _teamA; private String _teamB; private String _hrc; //Heimmannschaft Rote Karte String: Spielzeit + Name Spieler private int _hrci; //Heimmannschaft Rote Kart Zähler private String _grc; //Gastmannschaft Rote Karte String: Spielzeit + Name Spieler private int _grci; //Gastmannschaft Rote Karte Zähler private String _mstan; private String _hstan; private String _gstan; private String _golI; private String _l; private String _a; private String _league; private int m_iRefCounter; private int m_playtime; private bool m_stopPlaytime = false; private bool _pulsconnected = false; private LIVESTATES m_isStart = LIVESTATES.Eighth; private object _lockThreadStarter = "lockThreadStarter"; #region IScore Member public event EventHandler<GoalEventArgs> RaiseGoalEvent; public event EventHandler<GoalBackEventArgs> BackGoalEvent; public event EventHandler<PlaytimeTickEventArgs> PlaytimeTickEvent; public event EventHandler<GameEndedEventArgs> GameEndedEvent; public bool Ended { get { return this.MatchState == LIVESTATES.End; } } public string TeamA { get { return _teamA; } } public string TeamB { get { return _teamB; } } public ulong TeamAId { get { return _hid; } } public ulong TeamBId { get { return _gid; } } public string League { get { return _league; } } public int ScoreA { get { return _scoreA; } } public int ScoreB { get { return _scoreB; } } public DateTime StartDTS { get { return _startTime; } } public String BetfairMatch { get; set; } public string getScore() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0} - {1}", _scoreA, _scoreB); return sb.ToString(); } public string getLiveMatch() { return String.Format(CultureInfo.InvariantCulture, "{0} - {1}", this.TeamA, this.TeamB); } public IScore IncreaseRef() { m_iRefCounter++; lock (_lockThreadStarter) { // Playtimethreadüberprüfung } return this; } public void DecreaseRef() { m_iRefCounter--; if (m_iRefCounter < 0) m_iRefCounter = 0; // Falls kein Subscriber mehr vorhanden, dann Playtimethread stoppen if (m_iRefCounter == 0) { } } public SCORESTATE getScoreState() { if (_scoreA == 0 && _scoreB == 0) return SCORESTATE.initdraw; else if (_scoreA == _scoreB) return SCORESTATE.draw; else return SCORESTATE.undraw; } public bool isRunning() { if (m_isStart == LIVESTATES.First || m_isStart == LIVESTATES.HT || m_isStart == LIVESTATES.Second) return true; return false; } public int Playtime { get { return m_playtime; } } public LIVESTATES MatchState { get { switch ((MATCHSTATE)_sid) { case MATCHSTATE.FIRSTHALF: return LIVESTATES.First; case MATCHSTATE.HT: return LIVESTATES.HT; case MATCHSTATE.SECONDHALF: return LIVESTATES.Second; case MATCHSTATE.ENDED: return LIVESTATES.End; default: return LIVESTATES.Eigthteenth; } } } #endregion public int ID { get { return _matchId; } } public LiveScore2(XmlNode node) { XmlAttribute attribute = node.Attributes["MId"]; _matchId = -1; if (attribute != null && attribute.Value.Length != 0) { _matchId = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["LId"]; _leagueId = -1; if (attribute != null && attribute.Value.Length != 0) { _leagueId = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["_LId"]; _leagueIdParent = -1; if (attribute != null && attribute.Value.Length != 0) { _leagueIdParent = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["SId"]; _sid = -1; if (attribute != null && attribute.Value.Length != 0) { _sid = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["KId"]; _kid = -1; if (attribute != null && attribute.Value.Length != 0) { _kid = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["LNr"]; _lnr = -1; if (attribute != null && attribute.Value.Length != 0) { _lnr = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["C0"]; int startTimeSeconds = -1; if (attribute != null && attribute.Value.Length != 0) { startTimeSeconds = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); DateTime dts1970 = new DateTime(1970, 1, 1); TimeSpan spanToAdd = new TimeSpan(0, 0, startTimeSeconds); DateTime dtsStartUtc = dts1970.Add(spanToAdd); TimeZoneInfo tziLocal = TimeZoneInfo.Local; _startTime = TimeZoneInfo.ConvertTimeFromUtc(dtsStartUtc, tziLocal); } attribute = node.Attributes["C1"]; _c1 = -1; if (attribute != null && attribute.Value.Length != 0) { _c1 = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["C2"]; _c2 = -1; if (attribute != null && attribute.Value.Length != 0) { _c2 = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); if(_sid == (int)MATCHSTATE.SECONDHALF) _startTime = _startTime.AddSeconds(_c2); } attribute = node.Attributes["SMA"]; _sma = -1; if (attribute != null && attribute.Value.Length != 0) { _sma = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["H0"]; _h0 = 0; if (attribute != null && attribute.Value.Length != 0) { _h0 = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } _scoreA = _h0; attribute = node.Attributes["H1"]; _h1 = 0; if (attribute != null && attribute.Value.Length != 0) { _h1 = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["H2"]; _h2 = 0; if (attribute != null && attribute.Value.Length != 0) { _h2 = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["H3"]; _h3 = 0; if (attribute != null && attribute.Value.Length != 0) { _h3 = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["G0"]; _g0 = 0; if (attribute != null && attribute.Value.Length != 0) { _g0 = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } _scoreB = _g0; attribute = node.Attributes["G1"]; _g1 = 0; if (attribute != null && attribute.Value.Length != 0) { _g1 = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["G2"]; _g2 = 0; if (attribute != null && attribute.Value.Length != 0) { _g2 = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["G3"]; _g3 = 0; if (attribute != null && attribute.Value.Length != 0) { _g3 = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["HId"]; _hid = 0; if (attribute != null && attribute.Value.Length != 0) { _hid = UInt32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["GId"]; _gid = 0; if (attribute != null && attribute.Value.Length != 0) { _gid = UInt32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["HN"]; _teamA = String.Empty; if (attribute != null && attribute.Value.Length != 0) { _teamA = attribute.Value; } attribute = node.Attributes["GN"]; _teamB = String.Empty; if (attribute != null && attribute.Value.Length != 0) { _teamB = attribute.Value; } attribute = node.Attributes["HRC"]; _hrc = String.Empty; if (attribute != null && attribute.Value.Length != 0) { _hrc = attribute.Value; } attribute = node.Attributes["HRCi"]; _hrci = 0; if (attribute != null && attribute.Value.Length != 0) { _hrci = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["GRC"]; _grc = String.Empty; if (attribute != null && attribute.Value.Length != 0) { _grc = attribute.Value; } attribute = node.Attributes["GRCi"]; _grci = 0; if (attribute != null && attribute.Value.Length != 0) { _grci = Int32.Parse(attribute.Value, CultureInfo.InvariantCulture); } attribute = node.Attributes["MStan"]; _mstan = String.Empty; if (attribute != null && attribute.Value.Length != 0) { _mstan = attribute.Value; } attribute = node.Attributes["HStan"]; _hstan = String.Empty; if (attribute != null && attribute.Value.Length != 0) { _hstan = attribute.Value; } attribute = node.Attributes["GStan"]; _gstan = String.Empty; if (attribute != null && attribute.Value.Length != 0) { _gstan = attribute.Value; } attribute = node.Attributes["GolI"]; _golI = String.Empty; if (attribute != null && attribute.Value.Length != 0) { _golI = attribute.Value; } attribute = node.Attributes["L"]; _l = String.Empty; if (attribute != null && attribute.Value.Length != 0) { _l = attribute.Value; } attribute = node.Attributes["A"]; _a = String.Empty; if (attribute != null && attribute.Value.Length != 0) { _a = attribute.Value; } //mhe 09.11.11 //Neue Logik für Tor Alternative über Z-Knoten auch möglich? attribute = node.Attributes["S1"]; if(attribute != null && attribute.Value.Length != 0) { String[] scoreStrings = attribute.Value.Split(new char[] {'-'}); try { if (!Int32.TryParse(scoreStrings[0], out _scoreA)) _scoreA = 0; if (!Int32.TryParse(scoreStrings[1], out _scoreB)) _scoreB = 0; } catch { //Alles i.O., wenn Score nicht nummerisch, dann beachten wir ihn nicht. ; } } _lockThreadStarter = "lockThreadStarter" + this.ID; } void Instance_Pulse(object sender, EventArgs e) { if (this.isRunning()) { log("Received Pulse - Update Playtime"); ThreadPool.QueueUserWorkItem(new WaitCallback(this.updatePlaytime)); } } /* public void updateLivescore(XmlDocument document) { log(String.Format("Updateing Livescore. Updatestring {0}", document.InnerXml)); XmlElement elem = document.DocumentElement; XmlAttribute attribute = elem.Attributes["SId"]; if (attribute != null) { updateMatchState(attribute.Value); } attribute = elem.Attributes["H0"]; if (attribute != null) { updateHomeScore(attribute.Value); } attribute = elem.Attributes["G0"]; if (attribute != null) { updateGuestScore(attribute.Value); } attribute = elem.Attributes["HRCi"]; if (attribute != null) { updateHomeRedCard(attribute.Value); } attribute = elem.Attributes["GRCi"]; if (attribute != null) { updateGuestRedCard(attribute.Value); } //mhe 09.11.11 //Neue Logik für Tor Alternative über Z-Knoten auch möglich? attribute = elem.Attributes["S1"]; if (!String.IsNullOrEmpty(attribute.Value)) { String[] scoreStrings = attribute.Value.Split(new char[] { '-' }); try { updateHomeScore(scoreStrings[0]); updateGuestScore(scoreStrings[1]); } catch { //Alles i.O., wenn Score nicht nummerisch, dann beachten wir ihn nicht. ; } } } */ public void updateLivescore(MATCHSTATE livestate, int live_a, int live_b, int red_a, int red_b, DateTime startTime) { //log("Updateing Livescore"); if (_startTime != startTime) { log(String.Format(CultureInfo.InvariantCulture, "Starttime has changed. Old Starttime: {0}. New Starttime: {1}", _startTime, startTime)); _startTime = startTime; } if (_sid != (int)livestate) { updateMatchState(livestate); } // Tor für Team a gefallen oder Zurückgenommen if (live_a != _scoreA) { updateHomeScore(live_a.ToString(CultureInfo.InvariantCulture)); } // Tor für Team b gefallen oder zurück genommen if (live_b != _scoreB) { updateGuestScore(live_b.ToString(CultureInfo.InvariantCulture)); } // Rote Karte für Team A if (red_a != _hrci) { updateHomeRedCard(red_a.ToString(CultureInfo.InvariantCulture)); } if (red_b != _grci) { updateGuestRedCard(red_b.ToString(CultureInfo.InvariantCulture)); } } private void updateGuestRedCard(String value) { if (value.Length == 0) return; int redB = Int32.Parse(value, CultureInfo.InvariantCulture); if (redB != _grci) { _grci = redB; log(String.Format(CultureInfo.InvariantCulture, "Team {0} Red Card: {1}", this.TeamB, this.RedB)); EventHandler<RedCardEventArgs> handler = RedCardEvent; if (handler != null) { log("Notifying Listerners: Red Card"); handler(this, new RedCardEventArgs(_teamB, _hrci, _grci)); } } } private void updateHomeRedCard(String value) { if (value.Length == 0) return; int redA = Int32.Parse(value, CultureInfo.InvariantCulture); if (redA != _hrci) { _hrci = redA; log(String.Format(CultureInfo.InvariantCulture, "Team {0} Red Card: {1}", this.TeamA, this.RedA)); EventHandler<RedCardEventArgs> handler = RedCardEvent; if (handler != null) { log("Notifying Listerners: Red Card"); handler(this, new RedCardEventArgs(_teamA, _hrci, _grci)); } } } private void updateGuestScore(String value) { if (String.IsNullOrEmpty(value)) return; int scoreB = Int32.Parse(value, CultureInfo.InvariantCulture); if (scoreB > _scoreB) { _scoreB = scoreB; log(String.Format(CultureInfo.InvariantCulture, "Team {0} scored a goal. Score is now {1}", this.TeamB, this.getScore())); EventHandler<GoalEventArgs> handler = RaiseGoalEvent; if (handler != null) { log("Notifying Listerners: New Score"); handler(this, new GoalEventArgs(_teamB, _scoreA, _scoreB)); } } else if (scoreB < _scoreB) { _scoreB = scoreB; log(String.Format(CultureInfo.InvariantCulture, "Team {0} goal was canceled. New Score {1}", this.TeamB, this.getScore())); EventHandler<GoalBackEventArgs> handler = BackGoalEvent; if (handler != null) { log("Notifying Listerners: Goal canceled"); handler(this, new GoalBackEventArgs(_teamB, _scoreA, _scoreB)); } } } private void updateHomeScore(String value) { if (value.Length == 0) return; int scoreA = Int32.Parse(value, CultureInfo.InvariantCulture); if (scoreA > _scoreA) { _scoreA = scoreA; log(String.Format(CultureInfo.InvariantCulture, "Team {0} scored a goal. Score is now {1}", this.TeamA, this.getScore())); EventHandler<GoalEventArgs> handler = RaiseGoalEvent; if (handler != null) { log("Notifying Listerners: New Score"); handler(this, new GoalEventArgs(_teamA, _scoreA, _scoreB)); } } else if (scoreA < _scoreA) { _scoreA = scoreA; log(String.Format(CultureInfo.InvariantCulture, "Team {0} goal was canceled. New Score {1}", this.TeamA, this.getScore())); EventHandler<GoalBackEventArgs> handler = BackGoalEvent; if (handler != null) { log("Notifying Listerners: Goal canceled"); handler(this, new GoalBackEventArgs(_teamA, _scoreA, _scoreB)); } } } private void updateMatchState(MATCHSTATE value) { MATCHSTATE oldState = (MATCHSTATE)_sid; log(String.Format(CultureInfo.InvariantCulture, "Update Gamestate. Old state is {0}. New State is {1}", _sid, value)); _sid = (int)value; if (oldState == MATCHSTATE.HT && value == MATCHSTATE.SECONDHALF) _startTime = DateTime.Now; updateTick(); } /* private void updateMatchState(String value) { if (String.IsNullOrEmpty(value)) return; if (_sid == Int32.Parse(value, CultureInfo.InvariantCulture)) return; log(String.Format(CultureInfo.InvariantCulture, "Update Gamestate. Old state is {0}. New State is {1}", _sid, value)); _sid = Int32.Parse(value); updateTick(); } */ private void updateTick() { if (_sid == (int)MATCHSTATE.FIRSTHALF) { m_isStart = LIVESTATES.First; // Nur wenn schon Subscriber vorhanden sind if (m_iRefCounter > 0) { lock (_lockThreadStarter) { if (!_pulsconnected) { SXMinutePulse.Instance.Pulse += Instance_Pulse; _pulsconnected = true; } m_stopPlaytime = false; } } } else if (_sid == (int)MATCHSTATE.HT) { m_isStart = LIVESTATES.HT; lock (_lockThreadStarter) { if (!_pulsconnected) { SXMinutePulse.Instance.Pulse += Instance_Pulse; _pulsconnected = true; } } } else if (_sid == (int)MATCHSTATE.SECONDHALF) { m_isStart = LIVESTATES.Second; // Nur wenn Subscriber vorhanden if (m_iRefCounter > 0) { lock (_lockThreadStarter) { if (!_pulsconnected) { SXMinutePulse.Instance.Pulse += Instance_Pulse; _pulsconnected = true; } m_stopPlaytime = false; } } } else if (_sid == (int)MATCHSTATE.ENDED) { m_isStart = LIVESTATES.End; if (_pulsconnected) { SXMinutePulse.Instance.Pulse -= Instance_Pulse; _pulsconnected = false; } log("Game has ended"); EventHandler<GameEndedEventArgs> handler = GameEndedEvent; if (handler != null) { log("Notifying Listeners: Game has Ended"); handler(this, new GameEndedEventArgs(_teamA, _scoreA, _scoreB)); } } else { m_isStart = LIVESTATES.Eighth; lock (_lockThreadStarter) { if (_pulsconnected) { SXMinutePulse.Instance.Pulse -= Instance_Pulse; _pulsconnected = false; } m_stopPlaytime = true; } } } private void doTick() { int bssj = _sid == (int)MATCHSTATE.HT ? 46 : 0; if (_sid == (int)MATCHSTATE.FIRSTHALF || _sid == (int)MATCHSTATE.SECONDHALF) { if (_sid == (int)MATCHSTATE.FIRSTHALF) { bssj = Convert.ToInt32(DateTime.Now.Subtract(_startTime).TotalMinutes); if (bssj < 0) bssj = 0; if (bssj > 45) bssj = 45; } else if (_sid == (int)MATCHSTATE.SECONDHALF) { bssj = Convert.ToInt32(DateTime.Now.Subtract(_startTime).TotalMinutes) + 45;// -15; if (bssj < 46) bssj = 46; if (bssj > 90) bssj = 90; } else if (_sid == (int)MATCHSTATE.ENDED) bssj = 90; else if (_sid == (int)MATCHSTATE.HT) bssj = 45; m_playtime = bssj; /* m_playtimeThread = new Thread(this.updatePlaytime); m_playtimeThread.IsBackground = true; m_playtimeThread.Start(); */ } } private void updatePlaytime(Object stateInfo) { log("Update Playtime"); doTick(); log(String.Format(CultureInfo.InvariantCulture, "New Playtime is {0}", m_playtime)); //m_playtime += 1; EventHandler<PlaytimeTickEventArgs> handler = PlaytimeTickEvent; if (handler != null) { log("Notifying Listerners: New Playtime"); handler(this, new PlaytimeTickEventArgs(String.Format(CultureInfo.InvariantCulture, "Match {0} - {1}", _teamA, _teamB), m_playtime)); } } #region IScore Member public event EventHandler<RedCardEventArgs> RedCardEvent; public int RedA { get { return _hrci; } } public int RedB { get { return _grci; } } #endregion public MATCHSTATE getLivestate() { return (MATCHSTATE)_sid; } private void log(String message) { if (BetfairMatch != null) LiveTickerLog.Instance.writeLog(this.BetfairMatch, "liveticker2", message); } public void Dispose() { if (_pulsconnected) { SXMinutePulse.Instance.Pulse -= new EventHandler<EventArgs>(Instance_Pulse); _pulsconnected = false; } } } }
32.571922
153
0.48041
[ "MIT" ]
SXTrader/SXTrader
BFTradingStrategies/LiveScoreParser/LiveScore2.cs
28,322
C#
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("CustomBgProfiles")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("PTV AG")] [assembly: AssemblyProduct("CustomBgProfiles")] [assembly: AssemblyCopyright("Copyright © PTV AG 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
40.5
96
0.753086
[ "MIT" ]
ptv-logistics/xserver.net-bin
CustomBgProfiles/Properties/AssemblyInfo.cs
2,190
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Runtime.CompilerServices; #if SIGN [assembly: InternalsVisibleTo("Microsoft.R.Core.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")] [assembly: InternalsVisibleTo("Microsoft.R.Editor, PublicKey=002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")] [assembly: InternalsVisibleTo("Microsoft.R.Editor.Windows, PublicKey=002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")] [assembly: InternalsVisibleTo("Microsoft.R.Editor.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")] [assembly: InternalsVisibleTo("Microsoft.R.Debugger, PublicKey=002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")] [assembly: InternalsVisibleTo("Microsoft.VisualStudio.R.Package, PublicKey=002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")] #else [assembly: InternalsVisibleTo("Microsoft.R.Core.Test")] [assembly: InternalsVisibleTo("Microsoft.R.Editor")] [assembly: InternalsVisibleTo("Microsoft.R.Editor.Windows")] [assembly: InternalsVisibleTo("Microsoft.R.Editor.Test")] [assembly: InternalsVisibleTo("Microsoft.R.Debugger")] [assembly: InternalsVisibleTo("Microsoft.VisualStudio.R.Package")] #endif
132.272727
398
0.928866
[ "MIT" ]
Bhaskers-Blu-Org2/RTVS
src/R/Core/Impl/Properties/AssemblyInfo.cs
2,912
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System.Collections.Generic; using Stride.Core.Collections; using Stride.Core.Threading; namespace Stride.Rendering { /// <summary> /// Stage-specific data for a <see cref="RenderView"/>. /// </summary> /// Mostly useful to store list of <see cref="RenderNode"/> prefiltered by a <see cref="Rendering.RenderStage"/> and a <see cref="RenderView"/>. public struct RenderViewStage { public readonly int Index; /// <summary> /// Invalid slot. /// </summary> public static readonly RenderViewStage Invalid = new RenderViewStage(-1); public RenderViewStage(int index) { Index = index; RenderNodes = null; SortedRenderNodes = null; } public RenderViewStage(RenderStage renderStage) { Index = renderStage.Index; RenderNodes = null; SortedRenderNodes = null; } /// <summary> /// List of render nodes. It might cover multiple RenderStage and RootRenderFeature. RenderStages contains RenderStage range information. /// Used mostly for sorting and rendering. /// </summary> public ConcurrentCollector<RenderNodeFeatureReference> RenderNodes; /// <summary> /// Sorted list of render nodes, that should be used during actual drawing. /// </summary> public FastList<RenderNodeFeatureReference> SortedRenderNodes; public static implicit operator RenderViewStage(RenderStage renderStage) { return new RenderViewStage(renderStage); } } }
35.773585
163
0.646624
[ "MIT" ]
Alan-love/xenko
sources/engine/Stride.Rendering/Rendering/RenderViewStage.cs
1,896
C#
using System; using System.IO; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Newtonsoft; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Tiled_Monogame_example { public class Map { private List<Layer> MapLayers; private float height; private float width; public float Height => height; public float Width => width; private float tileheight; private float tilewidth; public float TileHeight => tileheight; public float TileWidth => tilewidth; public Map(string MapPath, Game1 game, int tileSize, int ScreenScaler = 1) { MapLayers = new List<Layer>(); using (StreamReader JsonFile = File.OpenText(MapPath)) { JObject MapJson = (JObject)JToken.ReadFrom(new JsonTextReader(JsonFile)); JArray LayersJson = (JArray)MapJson["layers"]; JArray LayerJsonData = (JArray)MapJson["tilesets"]; foreach (JObject Layers in LayersJson) { string Json = "{\n" + $"data:{Layers["data"].ToString()},\nname:'{Layers["name"].ToString()}'," + "\n}"; Layer layer = JsonConvert.DeserializeObject<Layer>(Json); layer.LoadTileset(game, tileSize); MapLayers.Add(layer); } int i = 0; foreach (JObject LayersData in LayerJsonData) { string Json2 = "{\n" + $"firstgid:{LayersData["firstgid"].ToString()},"+"\n"+"}"; Layer tempLayer = JsonConvert.DeserializeObject<Layer>(Json2); MapLayers[i].firstgid = tempLayer.firstgid; MapLayers[i].setDataValues(); i += 1; } } } private void getMapData(JObject MapJson) { string MapData = "{\n" +$"height:{MapJson["height"].ToString()},\ntileheight:{MapJson["tileheight"].ToString()},\ntilewidth:{MapJson["tilewidth"].ToString()},\nwidth:{MapJson["width"].ToString()},"+ "\n}"; System.Console.WriteLine(MapData); string[] data = new string[4]; data[0] = JsonConvert.DeserializeObject<string>(MapData); data[1] = JsonConvert.DeserializeObject<string>(MapData); data[2] = JsonConvert.DeserializeObject<string>(MapData); data[3] = JsonConvert.DeserializeObject<string>(MapData); // Map tempMap = JsonConvert.DeserializeObject<Map>(MapData); System.Console.WriteLine(Height + " " + Width); System.Console.WriteLine(TileHeight + " " + TileWidth); } public void DrawMap(SpriteBatch spriteBatch, int ScreenScaler = 1) { foreach (Layer layer in MapLayers) { layer.DrawLayer(spriteBatch, ScreenScaler); } } } }
37.987805
191
0.554414
[ "MIT" ]
RubemNto/Mongoame_Tiled
Tiled_Monogame_example/Map.cs
3,117
C#
using System; using System.Runtime.Serialization; using System.Xml.Serialization; namespace Organisation.BusinessLayer.DTO.Read { [Serializable] [DataContract] [XmlRoot(ElementName = "AddressHolder")] public class PhoneHours : AddressHolder { [DataMember] public string Type { get { return "PhoneHours"; } } } }
22.125
59
0.689266
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
OS2sync/OS2sync
BusinessLayer/Source/dto/read/address/PhoneHours.cs
356
C#
using Newtonsoft.Json; using System.Collections.Generic; namespace PddOpenSdk.Models.Request.Ddk { public partial class SearchDdkGoodsRequestModel : PddRequestModel { /// <summary> /// 商品关键词,与opt_id字段选填一个或全部填写 /// </summary> [JsonProperty("keyword")] public string Keyword { get; set; } /// <summary> /// 商品标签类目ID,使用pdd.goods.opt.get获取 /// </summary> [JsonProperty("opt_id")] public long? OptId { get; set; } /// <summary> /// 默认值1,商品分页数 /// </summary> [JsonProperty("page")] public int? Page { get; set; } /// <summary> /// 默认100,每页商品数量 /// </summary> [JsonProperty("page_size")] public int? PageSize { get; set; } /// <summary> /// 排序方式:0-综合排序;1-按佣金比率升序;2-按佣金比例降序;3-按价格升序;4-按价格降序;5-按销量升序;6-按销量降序;7-优惠券金额排序升序;8-优惠券金额排序降序;9-券后价升序排序;10-券后价降序排序;11-按照加入多多进宝时间升序;12-按照加入多多进宝时间降序;13-按佣金金额升序排序;14-按佣金金额降序排序;15-店铺描述评分升序;16-店铺描述评分降序;17-店铺物流评分升序;18-店铺物流评分降序;19-店铺服务评分升序;20-店铺服务评分降序;27-描述评分击败同类店铺百分比升序,28-描述评分击败同类店铺百分比降序,29-物流评分击败同类店铺百分比升序,30-物流评分击败同类店铺百分比降序,31-服务评分击败同类店铺百分比升序,32-服务评分击败同类店铺百分比降序 /// </summary> [JsonProperty("sort_type")] public int? SortType { get; set; } /// <summary> /// 是否只返回优惠券的商品,false返回所有商品,true只返回有优惠券的商品 /// </summary> [JsonProperty("with_coupon")] public bool? WithCoupon { get; set; } /// <summary> /// 筛选范围列表 样例:[{"range_id":0,"range_from":1,"range_to":1500},{"range_id":1,"range_from":1,"range_to":1500}] range_id枚举及描述: 0,最小成团价 1,券后价 2,佣金比例 3,优惠券价格 4,广告创建时间 5,销量 6,佣金金额 7,店铺描述分 8,店铺物流分 9,店铺服务分 10, 店铺描述分击败同行业百分比 11, 店铺物流分击败同行业百分比 12,店铺服务分击败同行业百分比 13,商品分 17 ,优惠券/最小团购价 18,过去两小时pv 19,过去两小时销量 /// </summary> [JsonProperty("range_list")] public string RangeList { get; set; } /// <summary> /// 商品类目ID,使用pdd.goods.cats.get接口获取 /// </summary> [JsonProperty("cat_id")] public long? CatId { get; set; } /// <summary> /// 商品ID列表。例如:[123456,123],当入参带有goods_id_list字段,将不会以opt_id、 cat_id、keyword维度筛选商品 /// </summary> [JsonProperty("goods_id_list")] public List<long?> GoodsIdList { get; set; } /// <summary> /// 店铺类型,1-个人,2-企业,3-旗舰店,4-专卖店,5-专营店,6-普通店(未传为全部) /// </summary> [JsonProperty("merchant_type")] public int? MerchantType { get; set; } /// <summary> /// 推广位id /// </summary> [JsonProperty("pid")] public string Pid { get; set; } /// <summary> /// 自定义参数 /// </summary> [JsonProperty("custom_parameters")] public string CustomParameters { get; set; } /// <summary> /// 店铺类型数组 /// </summary> [JsonProperty("merchant_type_list")] public int? MerchantTypeList { get; set; } /// <summary> /// 是否为品牌商品 /// </summary> [JsonProperty("is_brand_goods")] public bool? IsBrandGoods { get; set; } } }
38.012346
364
0.574862
[ "Apache-2.0" ]
zuhuizou/open-pdd-net-sdk
PddOpenSdk/PddOpenSdk/Models/Request/Ddk/SearchDdkGoodsRequestModel.cs
4,213
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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. // File System.ComponentModel.Design.DesignerVerbCollection.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ComponentModel.Design { public partial class DesignerVerbCollection : System.Collections.CollectionBase { #region Methods and constructors public int Add(DesignerVerb value) { return default(int); } public void AddRange(DesignerVerb[] value) { } public void AddRange(System.ComponentModel.Design.DesignerVerbCollection value) { } public bool Contains(DesignerVerb value) { return default(bool); } public void CopyTo(DesignerVerb[] array, int index) { } public DesignerVerbCollection() { } public DesignerVerbCollection(DesignerVerb[] value) { } public int IndexOf(DesignerVerb value) { return default(int); } public void Insert(int index, DesignerVerb value) { } protected override void OnClear() { } protected override void OnInsert(int index, Object value) { } protected override void OnRemove(int index, Object value) { } protected override void OnSet(int index, Object oldValue, Object newValue) { } protected override void OnValidate(Object value) { } public void Remove(DesignerVerb value) { } #endregion #region Properties and indexers public DesignerVerb this [int index] { get { return default(DesignerVerb); } set { } } #endregion } }
28.295082
463
0.715817
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/System/Sources/System.ComponentModel.Design.DesignerVerbCollection.cs
3,452
C#