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 |
|---|---|---|---|---|---|---|---|---|
namespace Binance.Net.Objects.Spot.LendingData
{
/// <summary>
/// Purchase result
/// </summary>
public class BinanceLendingPurchaseResult
{
/// <summary>
/// The id of the purchase
/// </summary>
public int PurchaseId { get; set; }
}
}
| 21.071429 | 47 | 0.559322 | [
"MIT"
] | CarlPrentice/Binance.Net | Binance.Net/Objects/Spot/LendingData/BinanceLendingPurchaseResult.cs | 297 | C# |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Contexts
{
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
public class ScopeContextTest
{
[Fact]
public void PushPropertyCaseInsensitiveTest()
{
// Arrange
ScopeContext.Clear();
var expectedValue = "World";
Dictionary<string, object> allProperties = null;
var success = false;
object value;
// Act
using (ScopeContext.PushProperty("HELLO", expectedValue))
{
success = ScopeContext.TryGetProperty("hello", out value);
allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value);
}
var failed = ScopeContext.TryGetProperty("hello", out var _);
// Assert
Assert.True(success);
Assert.Equal(expectedValue, value);
Assert.Single(allProperties);
Assert.Equal(expectedValue, allProperties["HELLO"]);
Assert.False(failed);
}
[Fact]
public void LoggerPushPropertyTest()
{
// Arrange
ScopeContext.Clear();
var expectedValue = "World";
Dictionary<string, object> allProperties = null;
var success = false;
object value;
var logger = new LogFactory().GetCurrentClassLogger();
// Act
using (logger.PushScopeProperty("HELLO", expectedValue))
{
success = ScopeContext.TryGetProperty("hello", out value);
allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value);
}
var failed = ScopeContext.TryGetProperty("hello", out var _);
// Assert
Assert.True(success);
Assert.Equal(expectedValue, value);
Assert.Single(allProperties);
Assert.Equal(expectedValue, allProperties["HELLO"]);
Assert.False(failed);
}
[Fact]
public void PushPropertyNestedTest()
{
// Arrange
ScopeContext.Clear();
var expectedString = "World";
var expectedGuid = System.Guid.NewGuid();
Dictionary<string, object> allProperties = null;
object stringValueLookup1 = null;
object stringValueLookup2 = null;
bool stringValueLookup3 = false;
object guidValueLookup1 = null;
bool guidValueLookup2 = false;
bool guidValueLookup3 = false;
// Act
using (ScopeContext.PushProperty("Hello", expectedString))
{
using (ScopeContext.PushProperty("RequestId", expectedGuid))
{
ScopeContext.TryGetProperty("Hello", out stringValueLookup1);
ScopeContext.TryGetProperty("RequestId", out guidValueLookup1);
allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value);
}
ScopeContext.TryGetProperty("Hello", out stringValueLookup2);
guidValueLookup2 = ScopeContext.TryGetProperty("RequestId", out var _);
}
guidValueLookup3 = ScopeContext.TryGetProperty("RequestId", out var _);
stringValueLookup3 = ScopeContext.TryGetProperty("Hello", out var _);
// Assert
Assert.Equal(2, allProperties.Count);
Assert.Equal(expectedString, allProperties["Hello"]);
Assert.Equal(expectedGuid, allProperties["RequestId"]);
Assert.Equal(expectedString, stringValueLookup1);
Assert.Equal(expectedString, stringValueLookup2);
Assert.Equal(expectedGuid, guidValueLookup1);
Assert.False(guidValueLookup2);
Assert.False(guidValueLookup3);
Assert.False(guidValueLookup3);
Assert.False(stringValueLookup3);
}
#if !NET3_5 && !NET4_0
[Fact]
public void PushNestedStatePropertiesTest()
{
// Arrange
ScopeContext.Clear();
var expectedString = "World";
var expectedGuid = System.Guid.NewGuid();
var expectedProperties = new[] { new KeyValuePair<string, object>("Hello", expectedString), new KeyValuePair<string, object>("RequestId", expectedGuid) };
var expectedNestedState = "First Push";
Dictionary<string, object> allProperties = null;
object[] allNestedStates = null;
object stringValueLookup = null;
// Act
using (ScopeContext.PushProperty("Hello", "People"))
{
using (ScopeContext.PushNestedStateProperties(expectedNestedState, expectedProperties))
{
allNestedStates = ScopeContext.GetAllNestedStates();
allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value);
}
ScopeContext.TryGetProperty("Hello", out stringValueLookup);
}
// Assert
Assert.Equal(2, allProperties.Count);
Assert.Equal(expectedString, allProperties["Hello"]);
Assert.Equal(expectedGuid, allProperties["RequestId"]);
Assert.Single(allNestedStates);
Assert.Equal(expectedNestedState, allNestedStates[0]);
Assert.Equal("People", stringValueLookup);
}
[Fact]
public void LoggerPushNestedStatePropertiesTest()
{
// Arrange
ScopeContext.Clear();
var expectedString = "World";
var expectedGuid = System.Guid.NewGuid();
var expectedProperties = new[] { new KeyValuePair<string, object>("Hello", expectedString), new KeyValuePair<string, object>("RequestId", expectedGuid) };
Dictionary<string, object> allProperties = null;
object[] allNestedStates = null;
object stringValueLookup = null;
var logger = new LogFactory().GetCurrentClassLogger();
// Act
using (logger.PushScopeProperty("Hello", "People"))
{
using (logger.PushScopeState(expectedProperties))
{
allNestedStates = ScopeContext.GetAllNestedStates();
allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value);
}
ScopeContext.TryGetProperty("Hello", out stringValueLookup);
}
// Assert
Assert.Equal(2, allProperties.Count);
Assert.Equal(expectedString, allProperties["Hello"]);
Assert.Equal(expectedGuid, allProperties["RequestId"]);
Assert.Single(allNestedStates);
Assert.Equal(expectedProperties, allNestedStates[0]);
Assert.Equal("People", stringValueLookup);
}
#endif
[Fact]
public void PushNestedStateTest()
{
// Arrange
ScopeContext.Clear();
var expectedNestedState = "First Push";
object topNestedState = null;
object[] allNestedStates = null;
// Act
using (ScopeContext.PushNestedState(expectedNestedState))
{
topNestedState = ScopeContext.PeekNestedState();
allNestedStates = ScopeContext.GetAllNestedStates();
}
var failed = ScopeContext.PeekNestedState() != null;
// Assert
Assert.Equal(expectedNestedState, topNestedState);
Assert.Single(allNestedStates);
Assert.Equal(expectedNestedState, allNestedStates[0]);
Assert.False(failed);
}
[Fact]
public void DoublePushNestedStateTest()
{
// Arrange
ScopeContext.Clear();
var expectedNestedState1 = "First Push";
var expectedNestedState2 = System.Guid.NewGuid();
object topNestedState1 = null;
object topNestedState2 = null;
object[] allNestedStates = null;
// Act
using (ScopeContext.PushNestedState(expectedNestedState1))
{
topNestedState1 = ScopeContext.PeekNestedState();
using (ScopeContext.PushNestedState(expectedNestedState2))
{
topNestedState2 = ScopeContext.PeekNestedState();
allNestedStates = ScopeContext.GetAllNestedStates();
}
}
var failed = ScopeContext.PeekNestedState() != null;
// Assert
Assert.Equal(expectedNestedState1, topNestedState1);
Assert.Equal(expectedNestedState2, topNestedState2);
Assert.Equal(2, allNestedStates.Length);
Assert.Equal(expectedNestedState2, allNestedStates[0]);
Assert.Equal(expectedNestedState1, allNestedStates[1]);
Assert.False(failed);
}
[Fact]
public void LoggerPushNestedStateTest()
{
// Arrange
ScopeContext.Clear();
var expectedNestedState = "First Push";
object topNestedState = null;
object[] allNestedStates = null;
var logger = new LogFactory().GetCurrentClassLogger();
// Act
using (logger.PushScopeState(expectedNestedState))
{
topNestedState = ScopeContext.PeekNestedState();
allNestedStates = ScopeContext.GetAllNestedStates();
}
var failed = ScopeContext.PeekNestedState() != null;
// Assert
Assert.Equal(expectedNestedState, topNestedState);
Assert.Single(allNestedStates);
Assert.Equal(expectedNestedState, allNestedStates[0]);
Assert.False(failed);
}
[Fact]
public void ClearScopeContextTest()
{
// Arrange
ScopeContext.Clear();
var expectedNestedState = "First Push";
var expectedString = "World";
var expectedGuid = System.Guid.NewGuid();
object[] allNestedStates1 = null;
object[] allNestedStates2 = null;
object stringValueLookup1 = null;
object stringValueLookup2 = null;
// Act
using (ScopeContext.PushProperty("Hello", expectedString))
{
using (ScopeContext.PushProperty("RequestId", expectedGuid))
{
using (ScopeContext.PushNestedState(expectedNestedState))
{
ScopeContext.Clear();
allNestedStates1 = ScopeContext.GetAllNestedStates();
ScopeContext.TryGetProperty("Hello", out stringValueLookup1);
}
}
// Original scope was restored on dispose, verify expected behavior
allNestedStates2 = ScopeContext.GetAllNestedStates();
ScopeContext.TryGetProperty("Hello", out stringValueLookup2);
}
// Assert
Assert.Null(stringValueLookup1);
Assert.Equal(expectedString, stringValueLookup2);
Assert.Empty(allNestedStates1);
Assert.Empty(allNestedStates2);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeState using ${scopenested}. Marked obsolete on NLog 5.0")]
public void LegacyNdlcPopShouldNotAffectProperties1()
{
// Arrange
ScopeContext.Clear();
var expectedValue = "World";
var success = false;
object propertyValue;
// Act
using (ScopeContext.PushProperty("Hello", expectedValue))
{
NestedDiagnosticsLogicalContext.PopObject(); // Should not pop anything (skip legacy mode)
success = ScopeContext.TryGetProperty("Hello", out propertyValue);
}
// Assert
Assert.True(success);
Assert.Equal(expectedValue, propertyValue);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeState using ${scopenested}. Marked obsolete on NLog 5.0")]
public void LegacyNdlcPopShouldNotAffectProperties2()
{
// Arrange
ScopeContext.Clear();
var expectedValue = "World";
var expectedNestedState = "First Push";
var success = false;
object propertyValue;
object nestedState;
// Act
using (ScopeContext.PushProperty("Hello", expectedValue))
{
ScopeContext.PushNestedState(expectedNestedState);
nestedState = NestedDiagnosticsLogicalContext.PopObject(); // Should only pop active scope (skip legacy mode)
success = ScopeContext.TryGetProperty("Hello", out propertyValue);
}
// Assert
Assert.True(success);
Assert.Equal(expectedValue, propertyValue);
Assert.Equal(expectedNestedState, nestedState);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeState using ${scopenested}. Marked obsolete on NLog 5.0")]
public void LegacyNdlcPopShouldNotAffectProperties3()
{
// Arrange
ScopeContext.Clear();
var expectedValue1 = "World";
var expectedValue2 = System.Guid.NewGuid();
var expectedNestedState1 = "First Push";
var expectedNestedState2 = System.Guid.NewGuid();
var success1 = false;
var success2 = false;
object propertyValue1;
object propertyValue2;
object nestedState1;
object nestedState2;
// Act
using (ScopeContext.PushProperty("Hello", expectedValue1))
{
ScopeContext.PushNestedState(expectedNestedState1);
ScopeContext.PushNestedState(expectedNestedState2);
using (ScopeContext.PushProperty("RequestId", expectedValue2))
{
nestedState2 = NestedDiagnosticsLogicalContext.PopObject(); // Evil pop where it should leave properties alone (Legacy mode)
nestedState1 = NestedDiagnosticsLogicalContext.PopObject(); // Evil pop where it should leave properties alone (Legacy mode)
success1 = ScopeContext.TryGetProperty("Hello", out propertyValue1);
success2 = ScopeContext.TryGetProperty("RequestId", out propertyValue2);
}
}
// Assert
Assert.True(success1);
Assert.True(success2);
Assert.Equal(expectedValue1, propertyValue1);
Assert.Equal(expectedValue2, propertyValue2);
Assert.Equal(expectedNestedState1, nestedState1);
Assert.Equal(expectedNestedState2, nestedState2);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeState using ${scopenested}. Marked obsolete on NLog 5.0")]
public void LegacyNdlcClearShouldNotAffectProperties1()
{
// Arrange
ScopeContext.Clear();
var expectedValue = "World";
var success = false;
object propertyValue;
// Act
using (ScopeContext.PushProperty("Hello", expectedValue))
{
NestedDiagnosticsLogicalContext.Clear(); // Should not clear anything (skip legacy mode)
success = ScopeContext.TryGetProperty("Hello", out propertyValue);
}
// Assert
Assert.True(success);
Assert.Equal(expectedValue, propertyValue);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeState using ${scopenested}. Marked obsolete on NLog 5.0")]
public void LegacyNdlcClearShouldNotAffectProperties2()
{
// Arrange
ScopeContext.Clear();
var expectedValue = "World";
var expectedNestedState = "First Push";
var success = false;
object propertyValue;
// Act
using (ScopeContext.PushProperty("Hello", expectedValue))
{
ScopeContext.PushNestedState(expectedNestedState);
NestedDiagnosticsLogicalContext.Clear(); // Should not clear properties (Legacy mode)
success = ScopeContext.TryGetProperty("Hello", out propertyValue);
}
// Assert
Assert.True(success);
Assert.Equal(expectedValue, propertyValue);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
public void LegacyMdlcClearShouldNotAffectStackValues1()
{
// Arrange
ScopeContext.Clear();
var expectedNestedState = "First Push";
object[] allNestedStates = null;
// Act
using (ScopeContext.PushNestedState(expectedNestedState))
{
MappedDiagnosticsLogicalContext.Clear(); // Should not clear anything (skip legacy mode)
allNestedStates = ScopeContext.GetAllNestedStates();
}
// Assert
Assert.Single(allNestedStates);
Assert.Equal(expectedNestedState, allNestedStates[0]);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
public void LegacyMdlcClearShouldNotAffectStackValues2()
{
// Arrange
ScopeContext.Clear();
var expectedValue = "World";
var expectedNestedState = "First Push";
object[] allNestedStates = null;
// Act
using (ScopeContext.PushNestedState(expectedNestedState))
{
ScopeContext.PushProperty("Hello", expectedValue);
MappedDiagnosticsLogicalContext.Clear(); // Should not clear stack (Legacy mode)
allNestedStates = ScopeContext.GetAllNestedStates();
}
// Assert
Assert.Single(allNestedStates);
Assert.Equal(expectedNestedState, allNestedStates[0]);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
public void LegacyMdlcRemoveShouldNotAffectStackValues1()
{
// Arrange
ScopeContext.Clear();
var expectedNestedState = "First Push";
object[] allNestedStates = null;
// Act
using (ScopeContext.PushNestedState(expectedNestedState))
{
MappedDiagnosticsLogicalContext.Remove("Hello"); // Should not remove anything (skip legacy mode)
allNestedStates = ScopeContext.GetAllNestedStates();
}
// Assert
Assert.Single(allNestedStates);
Assert.Equal(expectedNestedState, allNestedStates[0]);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
public void LegacyMdlcRemoveShouldNotAffectStackValues2()
{
// Arrange
ScopeContext.Clear();
var expectedValue1 = "World";
var expectedValue2 = System.Guid.NewGuid();
var expectedNestedState1 = "First Push";
var expectedNestedState2 = System.Guid.NewGuid();
object propertyValue1;
object propertyValue2;
object[] allNestedStates = null;
var success1 = false;
var success2 = false;
// Act
using (ScopeContext.PushNestedState(expectedNestedState1))
{
using (ScopeContext.PushProperty("Hello", expectedValue1))
{
using (ScopeContext.PushNestedState(expectedNestedState2))
{
ScopeContext.PushProperty("RequestId", expectedValue2);
MappedDiagnosticsLogicalContext.Remove("RequestId"); // Should not change stack (Legacy mode)
allNestedStates = ScopeContext.GetAllNestedStates();
success1 = ScopeContext.TryGetProperty("Hello", out propertyValue1);
success2 = ScopeContext.TryGetProperty("RequestId", out propertyValue2);
}
}
}
// Assert
Assert.Equal(2, allNestedStates.Length);
Assert.Equal(expectedNestedState2, allNestedStates[0]);
Assert.Equal(expectedNestedState1, allNestedStates[1]);
Assert.True(success1);
Assert.False(success2);
Assert.Equal(expectedValue1, propertyValue1);
Assert.Null(propertyValue2);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
public void LegacyMdlcSetShouldNotAffectStackValues1()
{
// Arrange
ScopeContext.Clear();
var expectedValue = "World";
var expectedNestedState = "First Push";
object propertyValue;
object[] allNestedStates = null;
var success = false;
// Act
using (ScopeContext.PushNestedState(expectedNestedState))
{
MappedDiagnosticsLogicalContext.Set("Hello", expectedValue); // Skip legacy mode (normal property push)
success = ScopeContext.TryGetProperty("Hello", out propertyValue);
allNestedStates = ScopeContext.GetAllNestedStates();
}
// Assert
Assert.Single(allNestedStates);
Assert.Equal(expectedNestedState, allNestedStates[0]);
Assert.True(success);
Assert.Equal(expectedValue, propertyValue);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
public void LegacyMdlcSetShouldNotAffectStackValues2()
{
// Arrange
ScopeContext.Clear();
var expectedValue = "World";
var expectedNestedState = "First Push";
object propertyValue;
object[] allNestedStates = null;
var success = false;
// Act
using (ScopeContext.PushNestedState(expectedNestedState))
{
using (ScopeContext.PushProperty("Hello", expectedValue))
{
MappedDiagnosticsLogicalContext.Set("Hello", expectedValue); // Skip legacy mode (ignore when same value)
success = ScopeContext.TryGetProperty("Hello", out propertyValue);
allNestedStates = ScopeContext.GetAllNestedStates();
}
}
// Assert
Assert.Single(allNestedStates);
Assert.Equal(expectedNestedState, allNestedStates[0]);
Assert.True(success);
Assert.Equal(expectedValue, propertyValue);
}
[Fact]
[Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
public void LegacyMdlcSetShouldNotAffectStackValues3()
{
// Arrange
ScopeContext.Clear();
var expectedValue = "Bob";
var expectedNestedState = "First Push";
object propertyValue1;
object propertyValue2;
object[] allNestedStates = null;
var success1 = false;
var success2 = false;
// Act
using (ScopeContext.PushNestedState(expectedNestedState))
{
using (ScopeContext.PushProperty("Hello", "World"))
{
MappedDiagnosticsLogicalContext.Set("Hello", expectedValue); // Enter legacy mode (need to overwrite)
success1 = ScopeContext.TryGetProperty("Hello", out propertyValue1);
allNestedStates = ScopeContext.GetAllNestedStates();
}
success2 = ScopeContext.TryGetProperty("Hello", out propertyValue2);
}
// Assert
Assert.Single(allNestedStates);
Assert.Equal(expectedNestedState, allNestedStates[0]);
Assert.True(success1);
Assert.Equal(expectedValue, propertyValue1);
Assert.False(success2);
Assert.Null(propertyValue2);
}
}
}
| 40.737952 | 166 | 0.588983 | [
"BSD-3-Clause"
] | ErickJeffries/NLog | tests/NLog.UnitTests/Contexts/ScopeContextTest.cs | 27,052 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Couchbase.Core.Configuration.Server;
using Couchbase.Core.DI;
using Couchbase.Core.IO.Operations;
using Couchbase.Core.Logging;
using Couchbase.Management.Buckets;
using Couchbase.Utils;
using Microsoft.Extensions.Logging;
namespace Couchbase.Core
{
internal class ClusterContext : IDisposable
{
private readonly ILogger<ClusterContext> _logger;
private readonly IRedactor _redactor;
private readonly IConfigHandler _configHandler;
private readonly IClusterNodeFactory _clusterNodeFactory;
private readonly CancellationTokenSource _tokenSource;
protected readonly ConcurrentDictionary<string, BucketBase> Buckets = new ConcurrentDictionary<string, BucketBase>();
private bool _disposed;
//For testing
public ClusterContext() : this(null, new CancellationTokenSource(), new ClusterOptions())
{
}
public ClusterContext(CancellationTokenSource tokenSource, ClusterOptions options)
: this(null, tokenSource, options)
{
}
public ClusterContext(ICluster cluster, CancellationTokenSource tokenSource, ClusterOptions options)
{
Cluster = cluster;
ClusterOptions = options;
_tokenSource = tokenSource;
// Register this instance of ClusterContext
options.AddSingletonService(this);
ServiceProvider = options.BuildServiceProvider();
_logger = ServiceProvider.GetRequiredService<ILogger<ClusterContext>>();
_redactor = ServiceProvider.GetRequiredService<IRedactor>();
_configHandler = ServiceProvider.GetRequiredService<IConfigHandler>();
_clusterNodeFactory = ServiceProvider.GetRequiredService<IClusterNodeFactory>();
}
/// <summary>
/// Nodes currently being managed.
/// </summary>
public ClusterNodeCollection Nodes { get; } = new ClusterNodeCollection();
public ClusterOptions ClusterOptions { get; }
/// <summary>
/// <seealso cref="IServiceProvider"/> for dependency injection within the context of this cluster.
/// </summary>
public IServiceProvider ServiceProvider { get; }
public BucketConfig GlobalConfig { get; set; }
public ICluster Cluster { get; }
public bool SupportsCollections { get; set; }
public CancellationToken CancellationToken => _tokenSource.Token;
public void StartConfigListening()
{
_configHandler.Start(ClusterOptions.EnableConfigPolling);
}
public void RegisterBucket(BucketBase bucket)
{
if (Buckets.TryAdd(bucket.Name, bucket))
{
_configHandler.Subscribe(bucket);
}
}
public void UnRegisterBucket(BucketBase bucket)
{
if (Buckets.TryRemove(bucket.Name, out var removedBucket))
{
_configHandler.Unsubscribe(bucket);
removedBucket.Dispose();
}
}
public void PublishConfig(BucketConfig bucketConfig)
{
_configHandler.Publish(bucketConfig);
}
public IClusterNode GetRandomNodeForService(ServiceType service, string bucketName = null)
{
IClusterNode node;
switch (service)
{
case ServiceType.Views:
try
{
node = Nodes.GetRandom(x => x.HasViews && x.Owner
!= null && x.Owner.Name == bucketName);
}
catch (NullReferenceException)
{
throw new ServiceMissingException(
$"No node with the Views service has been located for {_redactor.MetaData(bucketName)}");
}
break;
case ServiceType.Query:
node = Nodes.GetRandom(x => x.HasQuery);
break;
case ServiceType.Search:
node = Nodes.GetRandom(x => x.HasSearch);
break;
case ServiceType.Analytics:
node = Nodes.GetRandom(x => x.HasAnalytics);
break;
default:
throw new ServiceNotAvailableException(service);
}
if (node == null)
{
throw new ServiceNotAvailableException(service);
}
return node;
}
public async Task PruneNodesAsync(BucketConfig config)
{
var ipEndpointService = ServiceProvider.GetRequiredService<IIpEndPointService>();
var existingEndpoints = await config.NodesExt.ToAsyncEnumerable()
.SelectAwait(p => ipEndpointService.GetIpEndPointAsync(p, CancellationToken))
.ToListAsync(CancellationToken).ConfigureAwait(false);
var removed = Nodes.Where(x =>
!existingEndpoints.Any(y => x.KeyEndPoints.Any(z => z.Equals(y))));
foreach (var node in removed)
{
RemoveNode(node);
}
}
public IEnumerable<IClusterNode> GetNodes(string bucketName)
{
return Nodes.Where(x => x.Owner != null &&
x.Owner.Name.Equals(bucketName))
.Select(node => node);
}
public IClusterNode GetRandomNode()
{
return Nodes.GetRandom();
}
public void AddNode(IClusterNode node)
{
if (Nodes.Add(node))
{
_logger.LogDebug("Added {endPoint}", _redactor.SystemData(node.EndPoint));
}
}
public bool RemoveNode(IClusterNode removedNode)
{
if (Nodes.Remove(removedNode.EndPoint, out removedNode))
{
_logger.LogDebug("Removing {endPoint}", _redactor.SystemData(removedNode.EndPoint));
removedNode.Dispose();
return true;
}
return false;
}
public void RemoveAllNodes()
{
foreach (var removedNode in Nodes.Clear())
{
removedNode.Dispose();
}
}
public async Task<IClusterNode> GetUnassignedNodeAsync(HostEndpoint endpoint)
{
var dnsResolver = ServiceProvider.GetRequiredService<IDnsResolver>();
var ipAddress = await dnsResolver.GetIpAddressAsync(endpoint.Host, CancellationToken).ConfigureAwait(false);
return Nodes.FirstOrDefault(
x => !x.IsAssigned && x.EndPoint.Address.Equals(ipAddress));
}
public async Task BootstrapGlobalAsync()
{
if (ClusterOptions.ConnectionStringValue == null)
{
throw new InvalidOperationException("ConnectionString has not been set.");
}
if (ClusterOptions.ConnectionStringValue.IsValidDnsSrv())
{
try
{
// Always try to use DNS SRV to bootstrap if connection string is valid
// It can be disabled by returning an empty URI list from IDnsResolver
var dnsResolver = ServiceProvider.GetRequiredService<IDnsResolver>();
var bootstrapUri = ClusterOptions.ConnectionStringValue.GetDnsBootStrapUri();
var servers = (await dnsResolver.GetDnsSrvEntriesAsync(bootstrapUri, CancellationToken).ConfigureAwait(false)).ToList();
if (servers.Any())
{
_logger.LogInformation(
$"Successfully retrieved DNS SRV entries: [{_redactor.SystemData(string.Join(",", servers))}]");
ClusterOptions.ConnectionStringValue =
new ConnectionString(ClusterOptions.ConnectionStringValue, servers);
}
}
catch (Exception exception)
{
_logger.LogInformation(exception, "Error trying to retrieve DNS SRV entries.");
}
}
foreach (var server in ClusterOptions.ConnectionStringValue.GetBootstrapEndpoints(ClusterOptions.EnableTls))
{
var node = await _clusterNodeFactory.CreateAndConnectAsync(server, CancellationToken).ConfigureAwait(false);
GlobalConfig = await node.GetClusterMap().ConfigureAwait(false);
if (GlobalConfig == null)
{
AddNode(node); //GCCCP is not supported - pre-6.5 server fall back to CCCP like SDK 2
}
else
{
GlobalConfig.IsGlobal = true;
foreach (var nodeAdapter in GlobalConfig.GetNodes())//Initialize cluster nodes for global services
{
if (server.Host.Equals(nodeAdapter.Hostname))//this is the bootstrap node so update
{
node.NodesAdapter = nodeAdapter;
SupportsCollections = node.Supports(ServerFeatures.Collections);
AddNode(node);
}
else
{
var newNode = await _clusterNodeFactory.CreateAndConnectAsync(server, CancellationToken).ConfigureAwait(false);
newNode.NodesAdapter = nodeAdapter;
SupportsCollections = node.Supports(ServerFeatures.Collections);
AddNode(newNode);
}
}
}
}
}
public async Task<IBucket> GetOrCreateBucketAsync(string name)
{
if (Buckets.TryGetValue(name, out var bucket))
{
return bucket;
}
foreach (var server in ClusterOptions.ConnectionStringValue.GetBootstrapEndpoints(ClusterOptions.EnableTls))
{
foreach (var type in Enum.GetValues(typeof(BucketType)))
{
bucket = await CreateAndBootStrapBucketAsync(name, server, (BucketType) type).ConfigureAwait(false);
return bucket;
}
}
throw new BucketNotFoundException(name);
}
public async Task<BucketBase> CreateAndBootStrapBucketAsync(string name, HostEndpoint endpoint, BucketType type)
{
var node = await GetUnassignedNodeAsync(endpoint).ConfigureAwait(false);
if (node == null)
{
node = await _clusterNodeFactory.CreateAndConnectAsync(endpoint, CancellationToken).ConfigureAwait(false);
AddNode(node);
}
var bucketFactory = ServiceProvider.GetRequiredService<IBucketFactory>();
var bucket = bucketFactory.Create(name, type);
try
{
await bucket.BootstrapAsync(node).ConfigureAwait(false);
RegisterBucket(bucket);
}
catch(Exception e)
{
_logger.LogError(e, "Could not bootstrap bucket {name}.", _redactor.MetaData(name));
UnRegisterBucket(bucket);
}
return bucket;
}
public async Task RebootStrapAsync(string name)
{
if(Buckets.TryGetValue(name, out var bucket))
{
//need to remove the old nodes
var oldNodes = Nodes.Where(x => x.Owner == bucket).ToArray();
foreach (var node in oldNodes)
{
if (Nodes.Remove(node.EndPoint, out var removedNode))
{
removedNode.Dispose();
}
}
//start going through the bootstrap list trying to connect
foreach (var endpoint in ClusterOptions.ConnectionStringValue.GetBootstrapEndpoints(ClusterOptions
.EnableTls))
{
var node = await GetUnassignedNodeAsync(endpoint).ConfigureAwait(false);
if (node == null)
{
node = await _clusterNodeFactory.CreateAndConnectAsync(endpoint, CancellationToken)
.ConfigureAwait(false);
AddNode(node);
}
try
{
//connected so let bootstrapping continue on the bucket
await bucket.BootstrapAsync(node).ConfigureAwait(false);
RegisterBucket(bucket);
}
catch (Exception e)
{
_logger.LogError(e, "Could not bootstrap bucket {name}.", _redactor.MetaData(name));
UnRegisterBucket(bucket);
}
}
}
else
{
throw new BucketNotFoundException(name);
}
}
public async Task ProcessClusterMapAsync(IBucket bucket, BucketConfig config)
{
var ipEndPointService = ServiceProvider.GetRequiredService<IIpEndPointService>();
foreach (var nodeAdapter in config.GetNodes())
{
var endPoint = await ipEndPointService.GetIpEndPointAsync(nodeAdapter, CancellationToken);
if (Nodes.TryGet(endPoint, out var bootstrapNode))
{
_logger.LogDebug("Using existing node {endPoint} for bucket {bucket.Name} using rev#{config.Rev}",
_redactor.SystemData(endPoint), _redactor.MetaData(bucket.Name), config.Rev);
if (bootstrapNode.HasKv)
{
await bootstrapNode.SelectBucketAsync(bucket, CancellationToken).ConfigureAwait(false);
}
bootstrapNode.NodesAdapter = nodeAdapter;
SupportsCollections = bootstrapNode.Supports(ServerFeatures.Collections);
continue; //bootstrap node is skipped because it already went through these steps
}
_logger.LogDebug("Creating node {endPoint} for bucket {bucket.Name} using rev#{config.Rev}",
_redactor.SystemData(endPoint), _redactor.MetaData(bucket.Name), config.Rev);
var node = await _clusterNodeFactory.CreateAndConnectAsync(
// We want the BootstrapEndpoint to use the host name, not just the IP
new HostEndpoint(nodeAdapter.Hostname, endPoint.Port),
CancellationToken).ConfigureAwait(false);
node.NodesAdapter = nodeAdapter;
if (node.HasKv)
{
await node.SelectBucketAsync(bucket, CancellationToken).ConfigureAwait(false);
}
SupportsCollections = node.Supports(ServerFeatures.Collections);
AddNode(node);
}
await PruneNodesAsync(config).ConfigureAwait(false);
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_configHandler?.Dispose();
_tokenSource?.Dispose();
foreach (var bucketName in Buckets.Keys)
{
if (Buckets.TryRemove(bucketName, out var bucket))
{
bucket.Dispose();
}
}
RemoveAllNodes();
}
}
}
| 38.447619 | 140 | 0.549975 | [
"Apache-2.0"
] | malscent/couchbase-net-client | src/Couchbase/Core/ClusterContext.cs | 16,148 | C# |
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace TodoListWebApp
{
public class TokenFactory
{
//
// The Client ID is used by the application to uniquely identify itself to Azure AD.
// The Cert Name is the subject name of the certificate used to authenticate this application to Azure AD.
// The Tenant is the name of the Azure AD tenant in which this application is registered.
// The AAD Instance is the instance of Azure, for example public Azure or Azure China.
// The Authority is the sign-in URL of the tenant.
//
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string clientId = ConfigurationManager.AppSettings["ida:ClientIdSqlAadApp"];
private static string certName = ConfigurationManager.AppSettings["ida:CertName"];
static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
//
// To authenticate to the To Do list service, the client needs to know the service's App ID URI.
// To contact the To Do list service we need it's URL as well.
//
private static string sqlDBResourceId = ConfigurationManager.AppSettings["sqldb:ResourceId"];
//private static string todoListBaseAddress = ConfigurationManager.AppSettings["todo:TodoListBaseAddress"];
private static HttpClient httpClient = new HttpClient();
private static AuthenticationContext authContext = null;
private static ClientAssertionCertificate certCred = null;
private static string token;
public static string GetAccessToken()
{
//
// Create the authentication context to be used to acquire tokens.
//
authContext = new AuthenticationContext(Startup.Authority);
//
// Initialize the Certificate Credential to be used by ADAL.
// First find the matching certificate in the cert store.
//
X509Certificate2 cert = null;
X509Store store = new X509Store(StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
// Place all certificates in an X509Certificate2Collection object.
X509Certificate2Collection certCollection = store.Certificates;
// Find unexpired certificates.
X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
// From the collection of unexpired certificates, find the ones with the correct name.
X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false);
if (signingCert.Count == 0)
{
throw new Exception("Cannot find certificate: " + certName);
}
// Return the first certificate in the collection, has the right name and is current.
cert = signingCert[0];
}
finally
{
store.Close();
}
// Then create the certificate credential.
certCred = new ClientAssertionCertificate(clientId, cert);
AcquireToken().Wait();
return token;
}
static async Task AcquireToken()
{
//
// Get an access token from Azure AD using client credentials.
// If the attempt to get a token fails because the server is unavailable, retry twice after 3 seconds each.
//
AuthenticationResult result = null;
int retryCount = 0;
bool retry = false;
token = null;
do
{
retry = false;
try
{
// ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
result = await authContext.AcquireTokenAsync(sqlDBResourceId, certCred);
}
catch (AdalException ex)
{
if (ex.ErrorCode == "temporarily_unavailable")
{
retry = true;
retryCount++;
Thread.Sleep(3000);
}
Debug.WriteLine(
String.Format("An error occurred while acquiring a token\nTime: {0}\nError: {1}\nRetry: {2}\n",
DateTime.Now.ToString(),
ex.ToString(),
retry.ToString()));
}
} while ((retry == true) && (retryCount < 3));
if (result == null)
{
Debug.WriteLine("Canceling attempt to contact To Do list service.\n");
return;
}
token = result.AccessToken;
Debug.WriteLine("The access token obtained is:");
Debug.WriteLine("--------------------------------------------------");
Debug.WriteLine(result.AccessToken);
Debug.WriteLine("--------------------------------------------------");
}
public static async Task<string> GetToken(string authority, string resource, string scope, string clientId, string clientSecret)
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
return result.AccessToken;
}
}
} | 42.945578 | 140 | 0.591003 | [
"MIT"
] | sameer-kumar/Azure-AD-WebApp-WebAPI-OpenIDConnect-DotNet | TodoListWebApp/App_Start/TokenFactory.cs | 6,315 | C# |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Collections.Generic;
namespace osu.Framework.Graphics.Shaders
{
/// <summary>
/// A mapping of a global uniform to many shaders which need to receive updates on a change.
/// </summary>
internal class UniformMapping<T> : IUniformMapping
where T : struct
{
public T Value;
public List<GlobalUniform<T>> LinkedUniforms = new List<GlobalUniform<T>>();
public string Name { get; }
public UniformMapping(string name)
{
Name = name;
}
public void LinkShaderUniform(IUniform uniform)
{
var typedUniform = (GlobalUniform<T>)uniform;
typedUniform.UpdateValue(this);
LinkedUniforms.Add(typedUniform);
}
public void UnlinkShaderUniform(IUniform uniform)
{
var typedUniform = (GlobalUniform<T>)uniform;
LinkedUniforms.Remove(typedUniform);
}
public void UpdateValue(ref T newValue)
{
Value = newValue;
for (int i = 0; i < LinkedUniforms.Count; i++)
LinkedUniforms[i].UpdateValue(this);
}
}
}
| 28.645833 | 103 | 0.585455 | [
"MIT"
] | AtomCrafty/osu-framework | osu.Framework/Graphics/Shaders/UniformMapping.cs | 1,330 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
*/
namespace TencentCloud.Gaap.V20180529.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class ModifyHTTPSListenerAttributeResponse : AbstractModel
{
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// 内部实现,用户禁止调用
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 29.977273 | 83 | 0.667172 | [
"Apache-2.0"
] | Darkfaker/tencentcloud-sdk-dotnet | TencentCloud/Gaap/V20180529/Models/ModifyHTTPSListenerAttributeResponse.cs | 1,399 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Starbound.RealmFactory.DataModel.Properties
{
public abstract class ObjectPropertyTemplate<T>
{
/// <summary>
/// Gets or sets the name for the property. This is displayed in GUIs.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets a description for the property. This explains what the property is used for
/// at the object type level. This is also displayed in tool tips or in other parts of the
/// GUI, as needed to provide the artist with the information they need to make the right choice
/// for values for it.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets the default value for this particular property template.
/// </summary>
public T DefaultValue { get; set; }
/// <summary>
/// Validates a specific instance for correctness. The default implementation is that all instances
/// are valid--there's no real validation.
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public virtual bool Validate(ObjectProperty<T> instance)
{
return true;
}
/// <summary>
/// All property templates must be able to duplicate themselves.
/// </summary>
/// <returns></returns>
public abstract ObjectPropertyTemplate<T> Copy();
public abstract ObjectProperty<T> GenerateProperty();
}
}
| 34.270833 | 108 | 0.609726 | [
"MIT"
] | rbwhitaker/realm-factory | RealmFactory/DataModel/Properties/ObjectPropertyTemplate.cs | 1,647 | C# |
#pragma checksum "\\Mac\Home\Documents\Projects\CoreBB\CoreBB.Web\Views\Forum\Detail.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "f7c5bb5c25dedb0adf4076888df7f718af19dae1"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Forum_Detail), @"mvc.1.0.view", @"/Views/Forum/Detail.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Forum/Detail.cshtml", typeof(AspNetCore.Views_Forum_Detail))]
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 "\\Mac\Home\Documents\Projects\CoreBB\CoreBB.Web\Views\Forum\Detail.cshtml"
using CoreBB.Web.Models;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"f7c5bb5c25dedb0adf4076888df7f718af19dae1", @"/Views/Forum/Detail.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"a9af4978b9c2bfca24ef48e96efe5f8573634464", @"/Views/_ViewImports.cshtml")]
public class Views_Forum_Detail : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<Forum>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(0, 1, true);
WriteLiteral("");
EndContext();
#line 3 "\\Mac\Home\Documents\Projects\CoreBB\CoreBB.Web\Views\Forum\Detail.cshtml"
ViewBag.Title = "Forum Detail";
ViewData["Mode"] = "ShowingDetail";
#line default
#line hidden
BeginContext(126, 2, true);
WriteLiteral("\r\n");
EndContext();
BeginContext(129, 35, false);
#line 8 "\\Mac\Home\Documents\Projects\CoreBB\CoreBB.Web\Views\Forum\Detail.cshtml"
Write(Html.Partial("_ForumDetail", Model));
#line default
#line hidden
EndContext();
BeginContext(164, 2, true);
WriteLiteral("\r\n");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<Forum> Html { get; private set; }
}
}
#pragma warning restore 1591
| 49.924242 | 177 | 0.711684 | [
"Unlicense"
] | SergKorol/C-projects | CoreBB/CoreBB.Web/obj/Debug/netcoreapp2.2/Razor/Views/Forum/Detail.g.cshtml.cs | 3,297 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlogSystem.IBLL
{
public interface IArticleManager
{
Task CreateArticle(string title, string content, Guid[] categoryIds, Guid userId);
Task CreateCategory(string name, Guid userId);
Task<List<Dto.BlogCategoryDto>> GetAllCategories(Guid userId);
Task<List<Dto.ArticleDto>> GetAllArticlesByUserId(Guid userId, int pageIndex, int pageSize);
Task<int> GetDataCount(Guid userId);
Task<List<Dto.ArticleDto>> GetAllArticlesByEmail(string email);
Task<List<Dto.ArticleDto>> GetAllArticlesByCategoryId(Guid categoryId);
Task RemoveCategory(string name);
Task EditCategory(Guid categoryId, string newCategoryName);
Task RemoveArticle(Guid articleId);
Task EditArticle(Guid articleId, string title, string content, Guid[] categoryIds);
Task<bool> ExistsArticle(Guid articleId);
Task<Dto.ArticleDto> GetOneArticleById(Guid articleId);
Task GoodCountAdd(Guid articleId);
Task BadCountAdd(Guid articleId);
Task CreateComment(Guid userId, Guid articleId, string content);
Task<List<Dto.CommentDto>> GetCommentsByArticleId(Guid articleId);
}
}
| 29.333333 | 100 | 0.716667 | [
"MIT"
] | Candou9/BlogSystem | BlogSystem/BlogSystem.IBLL/IArticleManager.cs | 1,322 | C# |
using System;
using System.Collections.Generic;
using System.Text;
//using System.Drawing;
//using System.Drawing.Drawing2D;
namespace Svg.FilterEffects
{
public abstract class SvgFilterPrimitive : SvgElement
{
public const string SourceGraphic = "SourceGraphic";
public const string SourceAlpha = "SourceAlpha";
public const string BackgroundImage = "BackgroundImage";
public const string BackgroundAlpha = "BackgroundAlpha";
public const string FillPaint = "FillPaint";
public const string StrokePaint = "StrokePaint";
[SvgAttribute("in")]
public string Input
{
get { return this.Attributes.GetAttribute<string>("in"); }
set { this.Attributes["in"] = value; }
}
[SvgAttribute("result")]
public string Result
{
get { return this.Attributes.GetAttribute<string>("result"); }
set { this.Attributes["result"] = value; }
}
protected SvgFilter Owner
{
get { return (SvgFilter)this.Parent; }
}
public abstract void Process(ImageBuffer buffer);
}
} | 29.820513 | 74 | 0.622528 | [
"ECL-2.0",
"Apache-2.0"
] | tocsoft/SvgSharp | src/SvgSharp/Filter Effects/SvgFilterPrimitive.cs | 1,163 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera_script : MonoBehaviour
{
[SerializeField]
private float Speed = 0;
private Vector2 Limit;
private void Start()
{
//
}
private void Update()
{
this.GetInput();
}
private void GetInput()
{
if (Input.GetKey(KeyCode.W)) {
this.transform.Translate(Vector3.up * this.Speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
this.transform.Translate(Vector3.left * this.Speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
this.transform.Translate(Vector3.down * this.Speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
this.transform.Translate(Vector3.right * this.Speed * Time.deltaTime);
}
this.transform.position = new Vector3(
Mathf.Clamp(this.transform.position.x, 0, this.Limit.x), Mathf.Clamp(this.transform.position.y, this.Limit.y, 0), -1
);
}
public void SetLimit(Vector3 maxTile)
{
Vector3 bottomRight = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, 0));
this.Limit = new Vector2((maxTile.x - bottomRight.x), (maxTile.y - bottomRight.y));
}
}
| 26.64 | 128 | 0.594595 | [
"MIT"
] | adamajammary/simple-tower-defense | Assets/Scripts/Camera_script.cs | 1,334 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Ripple.TxSigning")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Ripple.TxSigning")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the Id of the typelib if this project is exposed to COM
[assembly: Guid("35a86cb5-9c41-4f6c-8abf-a838acc56da8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.972973 | 84 | 0.745196 | [
"ISC"
] | ZZHGit/ripple-dot-net | Ripple.TxSigning/Properties/AssemblyInfo.cs | 1,408 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/Uxtheme.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public partial struct WTA_OPTIONS
{
[NativeTypeName("DWORD")]
public uint dwFlags;
[NativeTypeName("DWORD")]
public uint dwMask;
}
}
| 28.941176 | 145 | 0.699187 | [
"MIT"
] | Perksey/terrafx.interop.windows | sources/Interop/Windows/um/Uxtheme/WTA_OPTIONS.cs | 494 | C# |
using System.Collections.Generic;
using Windows.UI;
using LottieUWP.Utils;
using LottieUWP.Value;
namespace LottieUWP.Animation.Keyframe
{
internal class ColorKeyframeAnimation : KeyframeAnimation<Color?>
{
internal ColorKeyframeAnimation(List<Keyframe<Color?>> keyframes) : base(keyframes)
{
}
public override Color? GetValue(Keyframe<Color?> keyframe, float keyframeProgress)
{
if (keyframe.StartValue == null || keyframe.EndValue == null)
{
throw new System.InvalidOperationException("Missing values for keyframe.");
}
var startColor = keyframe.StartValue;
var endColor = keyframe.EndValue;
if (ValueCallback != null)
{
var value = ValueCallback.GetValueInternal(keyframe.StartFrame.Value, keyframe.EndFrame.Value, startColor, endColor, keyframeProgress, LinearCurrentKeyframeProgress, Progress);
if (value != null)
{
return value;
}
}
return GammaEvaluator.Evaluate(keyframeProgress, startColor.Value, endColor.Value);
}
}
} | 34.314286 | 192 | 0.616986 | [
"Apache-2.0"
] | 00mjk/LottieUWP | LottieUWP/Animation/Keyframe/ColorKeyframeAnimation.cs | 1,203 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
class NamespaceOutageEmulator
{
readonly string connectionString;
public NamespaceOutageEmulator(string connectionString)
{
this.connectionString = connectionString;
}
public async Task Toggle()
{
var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
var topic1 = await namespaceManager.GetTopicAsync("bundle-1")
.ConfigureAwait(false);
var newStatus = NewStatus(topic1.Status);
topic1.Status = newStatus;
await namespaceManager.UpdateTopicAsync(topic1)
.ConfigureAwait(false);
try
{
var topic2 = await namespaceManager.GetTopicAsync("bundle-2")
.ConfigureAwait(false);
topic2.Status = newStatus;
await namespaceManager.UpdateTopicAsync(topic2)
.ConfigureAwait(false);
}
catch (MessagingEntityNotFoundException)
{
}
var parts = Console.Title.Split(new [] {" ("}, StringSplitOptions.RemoveEmptyEntries);
Console.Title = parts[0] + (topic1.Status == EntityStatus.Active ? "" : " (OUTAGE: Namespace with connection string 'AzureServiceBus.ConnectionString.1' is not available)");
}
public static async Task EnsureNoOutageIsEmulated(string connectionString)
{
var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
try
{
var topic1 = await namespaceManager.GetTopicAsync("bundle-1")
.ConfigureAwait(false);
if (topic1.Status != EntityStatus.Active)
{
topic1.Status = EntityStatus.Active;
await namespaceManager.UpdateTopicAsync(topic1)
.ConfigureAwait(false);
}
}
catch (MessagingEntityNotFoundException)
{
}
try
{
var topic2 = await namespaceManager.GetTopicAsync("bundle-2")
.ConfigureAwait(false);
if (topic2.Status != EntityStatus.Active)
{
topic2.Status = EntityStatus.Active;
await namespaceManager.UpdateTopicAsync(topic2)
.ConfigureAwait(false);
}
}
catch (MessagingEntityNotFoundException)
{
}
}
static EntityStatus NewStatus(EntityStatus currentStatus)
{
return currentStatus == EntityStatus.Disabled
? EntityStatus.Active
: EntityStatus.Disabled;
}
} | 32.470588 | 182 | 0.596014 | [
"Apache-2.0"
] | Cogax/docs.particular.net | samples/azure/custom-partitioning-asb/ASB_10/Publisher/NamespaceOutageEmulator.cs | 2,678 | C# |
using System;
namespace _11_Repaso_POO
{
class Program
{
static void Main(string[] args)
{
//int numero = 5;
//string nombre = "Pedro";
Utilerias u = new Utilerias();
u.FormatoMoneda(100);
Alumno a1 = new Alumno(1, "Juan", "12345");
Alumno a2 = new Alumno(2, "Pedro", "12345");
Alumno a3 = new Alumno(3, "Pablo", "12345");
Alumno a4 = new Alumno(4, "Jose", "12345");
Profesor p = new Profesor(1, "Jose", 20000);
Gerente g = new Gerente(1, "Maria", 80000);
// Persona persona = new Persona();
// persona.EnviarMensaje("Juan");
a1.EnviarMensaje();
p.EnviarMensaje();
g.EnviarMensaje();
Console.WriteLine(a1.Nombre + " " + a1.NoCarnet);
Console.WriteLine(p.Nombre + " " + p.Salario.ToString());
Console.WriteLine(g.Nombre + " " + g.Salario.ToString());
}
}
}
| 27.486486 | 69 | 0.499508 | [
"MIT"
] | andreach13/C-Sharp | Ejercicios/11-Repaso-POO/Program.cs | 1,019 | C# |
namespace Tauron.Application.Localizer.DataModel.Processing
{
public sealed record SaveProject(ProjectFile ProjectFile, string OperationId) : Operation(OperationId);
} | 43 | 107 | 0.825581 | [
"MIT"
] | augustoproiete-bot/Project-Manager-Akka | Tauron.Application.Localizer.DataModel/Processing/Messages/SaveProject.cs | 174 | C# |
using System;
using System.Diagnostics;
namespace Assimalign.Extensions.Primitives;
internal static class ThrowHelper
{
internal static void ThrowArgumentNullException(ExceptionArgument argument)
{
throw new ArgumentNullException(GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument)
{
throw new ArgumentOutOfRangeException(GetArgumentName(argument));
}
internal static void ThrowArgumentException(ExceptionResource resource)
{
throw new ArgumentException(GetResourceText(resource));
}
internal static void ThrowInvalidOperationException(ExceptionResource resource)
{
throw new InvalidOperationException(GetResourceText(resource));
}
internal static void ThrowInvalidOperationException(ExceptionResource resource, params object[] args)
{
string message = string.Format(GetResourceText(resource), args);
throw new InvalidOperationException(message);
}
internal static ArgumentNullException GetArgumentNullException(ExceptionArgument argument)
{
return new ArgumentNullException(GetArgumentName(argument));
}
internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument)
{
return new ArgumentOutOfRangeException(GetArgumentName(argument));
}
internal static ArgumentException GetArgumentException(ExceptionResource resource)
{
return new ArgumentException(GetResourceText(resource));
}
private static string GetResourceText(ExceptionResource resource)
{
return SR.GetResourceString(GetResourceName(resource));
}
private static string GetArgumentName(ExceptionArgument argument)
{
Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
"The enum value is not defined, please check the ExceptionArgument Enum.");
return argument.ToString();
}
private static string GetResourceName(ExceptionResource resource)
{
Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
"The enum value is not defined, please check the ExceptionResource Enum.");
return resource.ToString();
}
}
internal enum ExceptionArgument
{
buffer,
offset,
length,
text,
start,
count,
index,
value,
capacity,
separators,
comparisonType
}
internal enum ExceptionResource
{
Argument_InvalidOffsetLength,
Argument_InvalidOffsetLengthStringSegment,
Capacity_CannotChangeAfterWriteStarted,
Capacity_NotEnough,
Capacity_NotUsedEntirely
}
| 28.063158 | 106 | 0.740435 | [
"MIT"
] | Assimalign-LLC/asal-dotnet-extensions | src/common/src/Assimalign.Extensions.Primitives/Internal/ThrowHelper.cs | 2,668 | C# |
using UnityEngine;
using System.Collections;
using System;
/// <summary>
/// Used to indicate when the stat's current value changes
/// </summary>
public interface IStatCurrentValueChange {
event EventHandler OnCurrentValueChange;
}
| 21.727273 | 58 | 0.76569 | [
"MIT"
] | jkpenner/RPGSystemTutorial | Assets/RPGSystems/Scripts/Stats/Interfaces/IStatCurrentValueChange.cs | 241 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Drawing.Imaging;
namespace AssetImporter {
public class FontLoader {
public void Load(string destinationDirectory, string fontName, BinaryReader binaryReader) {
var destination = Path.Combine(destinationDirectory, fontName);
Directory.CreateDirectory(destination);
var font = new Font();
font.XSpacing = binaryReader.ReadByte();
font.YSpacing = binaryReader.ReadByte();
for (int i = 0; i < font.Characters.Length; ++i) {
var baseFormat = (BaseFormat)binaryReader.ReadInt16();
if (baseFormat == BaseFormat.Unused1) {
continue;
}
var fileName = fontName + "_" + i;
Loader.LoadBaseFormat(baseFormat, destination, fileName, binaryReader);
font.CharacterFileNames[i] = fileName;
}
(new XmlSerializer(typeof(Font)))
.Serialize(File.Open(Path.Combine(destination, fontName + ".xml"), FileMode.Create), font);
}
}
}
| 33.657895 | 108 | 0.595778 | [
"Apache-2.0"
] | asik/Settlers-2-Remake | src/AssetImporter/Loader/FontLoader.cs | 1,281 | C# |
using System;
using System.Collections.Generic;
namespace ARKBreedingStats.miscClasses
{
/// <summary>
/// Provides specific help for extraction-issues
/// </summary>
public static class IssueNotes
{
/// <summary>
/// Returns a list of possible reasons that could cause the issues.
/// </summary>
/// <param name="issues"></param>
/// <returns></returns>
public static string getHelpTexts(Issue issues)
{
List<string> notes = new List<string>();
int n = 1;
int i = (int)issues;
while (i >= n)
{
if ((i & n) != 0)
notes.Add($"{(notes.Count + 1)}. {GetHelpText((Issue)n)}");
n <<= 1;
}
return string.Join("\n\n", notes.ToArray());
}
private static string GetHelpText(Issue issue)
{
switch (issue)
{
case Issue.Typo: return Loc.S("issueCauseTypo");
case Issue.WildTamedBred: return Loc.S("issueCauseWildTamedBred");
case Issue.TamingEffectivenessRange: return Loc.S("issueCauseTamingEffectivenessRange");
case Issue.LockedDom: return Loc.S("issueCauseLockedDomLevel");
case Issue.ImprintingLocked: return Loc.S("issueCauseImprintingLocked");
case Issue.ImprintingNotUpdated: return Loc.S("issueCauseImprintingNotUpdated");
case Issue.ImprintingNotPossible: return Loc.S("issueCauseImprintingNotPossible");
case Issue.Singleplayer: return Loc.S("issueCauseSingleplayer");
case Issue.WildLevelSteps: return Loc.S("issueCauseWildLevelSteps");
case Issue.MaxWildLevel: return Loc.S("issueCauseMaxWildLevel");
case Issue.StatMultipliers: return Loc.S("issueCauseStatMultipliers");
case Issue.ModValues: return Loc.S("issueCauseModValues");
case Issue.ArkStatIssue: return Loc.S("issueCauseArkStatIssue");
case Issue.CreatureLevel: return Loc.S("issueCauseCreatureLevel");
case Issue.OutdatedIngameValues: return Loc.S("issueCauseOutdatedIngameValues");
case Issue.ImpossibleTe: return Loc.S("issueCauseImpossibleTe");
}
return string.Empty;
}
// order the enums according to their desired position in the issue-help, i.e. critical and common issues first
[Flags]
public enum Issue
{
None = 0,
ImprintingNotPossible = 1,
Typo = 2,
CreatureLevel = 4,
WildTamedBred = 8,
LockedDom = 16,
Singleplayer = 32,
MaxWildLevel = 64,
StatMultipliers = 128,
ImprintingNotUpdated = 256,
TamingEffectivenessRange = 512,
ImprintingLocked = 1024,
ModValues = 2048,
WildLevelSteps = 4096,
ArkStatIssue = 8192,
OutdatedIngameValues = 16384,
ImpossibleTe = 32768
}
}
}
| 40.269231 | 119 | 0.571792 | [
"MIT"
] | CataclysmicAngel/ARKStatsExtractor | ARKBreedingStats/miscClasses/IssueNotes.cs | 3,143 | C# |
using Microsoft.UI.Text;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Documents;
using Microsoft.UI.Xaml.Markup;
using Microsoft.UI.Xaml.Media;
using System.Collections.Generic;
using Windows.UI;
using Windows.UI.Text;
namespace MC_Manager.Controls
{
public static class McFormattedTextBlock
{
public static string GetMcFormattedText(DependencyObject obj)
=> (string)obj.GetValue(McFormattedTextProperty);
public static void SetMcFormattedText(DependencyObject obj, string value)
=> obj.SetValue(McFormattedTextProperty, value);
public static readonly DependencyProperty McFormattedTextProperty =
DependencyProperty.RegisterAttached(
"McFormattedText",
typeof(string),
typeof(McFormattedTextBlock),
new PropertyMetadata(null, OnChanged)
);
static Dictionary<char, string> mcColors = new()
{
{ '0', "#000000" },
{ '1', "#0000AA" },
{ '2', "#00AA00" },
{ '3', "#00AAAA" },
{ '4', "#AA0000" },
{ '5', "#AA00AA" },
{ '6', "#FFAA00" },
{ '7', "#AAAAAA" },
{ '8', "#555555" },
{ '9', "#5555FF" },
{ 'a', "#55FF55" },
{ 'b', "#55FFFF" },
{ 'c', "#FF5555" },
{ 'd', "#FF55FF" },
{ 'e', "#FFFF55" },
{ 'f', "#FFFFFF" },
{ 'g', "#FFFFFF" }
};
private static void OnChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var target = dependencyObject as TextBlock;
if (target != null)
{
target.Inlines.Clear();
string input = e.NewValue as string;
Run lastInline = null;
if (!input.Contains('§'))
target.Inlines.Add(new Run() { Text = input });
else
foreach (string section in input.Split('§'))
{
if (section.Length == 0)
continue;
char ctlChar = section[0];
Run currentInline = new();
if (section.Length > 1)
currentInline.Text = section.Substring(1);
if (ctlChar == 'r' /* reset */)
lastInline = null;
if (lastInline != null)
{
currentInline.Foreground = lastInline.Foreground;
currentInline.FontWeight = lastInline.FontWeight;
currentInline.TextDecorations = lastInline.TextDecorations;
currentInline.FontStyle = lastInline.FontStyle;
}
switch (ctlChar)
{
case 'k': // obfuscated
currentInline.Text = "".PadLeft(section.Length - 1, 'Ā');
break;
case 'l': // bold
currentInline.FontWeight = FontWeights.Bold;
break;
case 'm': // strikethrough
currentInline.TextDecorations = TextDecorations.Strikethrough;
break;
case 'n': // underline
currentInline.TextDecorations = TextDecorations.Underline;
break;
case 'o': // italic
currentInline.FontStyle = FontStyle.Italic;
break;
default: // colors
if (mcColors.ContainsKey(ctlChar))
currentInline.Foreground = new SolidColorBrush((Color)XamlBindingHelper.ConvertValue(typeof(Color), mcColors[ctlChar]));
break;
}
lastInline = currentInline;
target.Inlines.Add(currentInline);
}
}
}
}
}
| 37.982759 | 156 | 0.44394 | [
"MIT"
] | ShortDevelopment/MC-Manager | MC Manager/MC Manager/Controls/McFormattedTextBlock.cs | 4,411 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201
{
using static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Extensions;
/// <summary>Parameters allowed to update for a server.</summary>
public partial class ServerUpdateParameters
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IServerUpdateParameters.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IServerUpdateParameters.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IServerUpdateParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject json ? new ServerUpdateParameters(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject into a new instance of <see cref="ServerUpdateParameters" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject instance to deserialize from.</param>
internal ServerUpdateParameters(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_identity = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject>("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ResourceIdentity.FromJson(__jsonIdentity) : Identity;}
{_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ServerUpdateParametersProperties.FromJson(__jsonProperties) : Property;}
{_sku = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject>("sku"), out var __jsonSku) ? Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.Sku.FromJson(__jsonSku) : Sku;}
{_tag = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject>("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ServerUpdateParametersTags.FromJson(__jsonTags) : Tag;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="ServerUpdateParameters" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="ServerUpdateParameters" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add );
AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add );
AddIf( null != this._sku ? (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode) this._sku.ToJson(null,serializationMode) : null, "sku" ,container.Add );
AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 76.205607 | 297 | 0.699289 | [
"MIT"
] | Arsasana/azure-powershell | src/PostgreSql/generated/api/Models/Api20171201/ServerUpdateParameters.json.cs | 8,048 | C# |
/* Copyright 2013-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using MongoDB.Driver.Core.Misc;
using MongoDB.Driver.Core.Servers;
namespace MongoDB.Driver.Core.Clusters.ServerSelectors
{
/// <summary>
/// Represents a selector that selects servers based on a read preference.
/// </summary>
public class ReadPreferenceServerSelector : IServerSelector
{
#region static
// static fields
private static readonly ServerDescription[] __noServers = new ServerDescription[0];
private static readonly ReadPreferenceServerSelector __primary = new ReadPreferenceServerSelector(ReadPreference.Primary);
// static properties
/// <summary>
/// Gets a ReadPreferenceServerSelector that selects the Primary.
/// </summary>
/// <value>
/// A server selector.
/// </value>
public static ReadPreferenceServerSelector Primary
{
get { return __primary; }
}
#endregion
// fields
private readonly TimeSpan? _maxStaleness; // with InfiniteTimespan converted to null
private readonly ReadPreference _readPreference;
// constructors
/// <summary>
/// Initializes a new instance of the <see cref="ReadPreferenceServerSelector"/> class.
/// </summary>
/// <param name="readPreference">The read preference.</param>
public ReadPreferenceServerSelector(ReadPreference readPreference)
{
_readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference));
if (readPreference.MaxStaleness == Timeout.InfiniteTimeSpan)
{
_maxStaleness = null;
}
else
{
_maxStaleness = readPreference.MaxStaleness;
}
}
// methods
/// <inheritdoc/>
public IEnumerable<ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable<ServerDescription> servers)
{
if (_maxStaleness.HasValue)
{
if (cluster.Servers.Any(s => s.Type != ServerType.Unknown && !Feature.MaxStaleness.IsSupported(s.Version)))
{
throw new NotSupportedException("All servers must be version 3.4 or newer to use max staleness.");
}
}
if (cluster.ConnectionMode == ClusterConnectionMode.Direct)
{
return servers;
}
switch (cluster.Type)
{
case ClusterType.ReplicaSet: return SelectForReplicaSet(cluster, servers);
case ClusterType.Sharded: return SelectForShardedCluster(servers);
case ClusterType.Standalone: return SelectForStandaloneCluster(servers);
case ClusterType.Unknown: return __noServers;
default:
var message = string.Format("ReadPreferenceServerSelector is not implemented for cluster of type: {0}.", cluster.Type);
throw new NotImplementedException(message);
}
}
/// <inheritdoc/>
public override string ToString()
{
return string.Format("ReadPreferenceServerSelector{{ ReadPreference = {0} }}", _readPreference);
}
private IEnumerable<ServerDescription> SelectByTagSets(IEnumerable<ServerDescription> servers)
{
var tagSets = _readPreference.TagSets;
if (tagSets == null || !tagSets.Any())
{
return servers;
}
foreach (var tagSet in _readPreference.TagSets)
{
var matchingServers = new List<ServerDescription>();
foreach (var server in servers)
{
if (server.Tags != null && server.Tags.ContainsAll(tagSet))
{
matchingServers.Add(server);
}
}
if (matchingServers.Count > 0)
{
return matchingServers;
}
}
return __noServers;
}
private IEnumerable<ServerDescription> SelectForReplicaSet(ClusterDescription cluster, IEnumerable<ServerDescription> servers)
{
EnsureMaxStalenessIsValid(cluster);
servers = new CachedEnumerable<ServerDescription>(servers); // prevent multiple enumeration
switch (_readPreference.ReadPreferenceMode)
{
case ReadPreferenceMode.Primary:
return SelectPrimary(servers);
case ReadPreferenceMode.PrimaryPreferred:
var primary = SelectPrimary(servers);
if (primary.Count != 0)
{
return primary;
}
else
{
return SelectByTagSets(SelectFreshSecondaries(cluster, servers));
}
case ReadPreferenceMode.Secondary:
return SelectByTagSets(SelectFreshSecondaries(cluster, servers));
case ReadPreferenceMode.SecondaryPreferred:
var selectedSecondaries = SelectByTagSets(SelectFreshSecondaries(cluster, servers)).ToList();
if (selectedSecondaries.Count != 0)
{
return selectedSecondaries;
}
else
{
return SelectPrimary(servers);
}
case ReadPreferenceMode.Nearest:
return SelectByTagSets(SelectPrimary(servers).Concat(SelectFreshSecondaries(cluster, servers)));
default:
throw new ArgumentException("Invalid ReadPreferenceMode.");
}
}
private IEnumerable<ServerDescription> SelectForShardedCluster(IEnumerable<ServerDescription> servers)
{
return servers.Where(n => n.Type == ServerType.ShardRouter); // ReadPreference will be sent to mongos
}
private IEnumerable<ServerDescription> SelectForStandaloneCluster(IEnumerable<ServerDescription> servers)
{
return servers.Where(n => n.Type == ServerType.Standalone); // standalone servers match any ReadPreference (to facilitate testing)
}
private List<ServerDescription> SelectPrimary(IEnumerable<ServerDescription> servers)
{
var primary = servers.Where(s => s.Type == ServerType.ReplicaSetPrimary).ToList();
if (primary.Count > 1)
{
throw new MongoClientException($"More than one primary found: [{string.Join(", ", servers.Select(s => s.ToString()))}].");
}
return primary; // returned as a list because otherwise some callers would have to create a new list
}
private IEnumerable<ServerDescription> SelectSecondaries(IEnumerable<ServerDescription> servers)
{
return servers.Where(s => s.Type == ServerType.ReplicaSetSecondary);
}
private IEnumerable<ServerDescription> SelectFreshSecondaries(ClusterDescription cluster, IEnumerable<ServerDescription> servers)
{
var secondaries = SelectSecondaries(servers);
if (_maxStaleness.HasValue)
{
var primary = SelectPrimary(cluster.Servers).SingleOrDefault();
if (primary == null)
{
return SelectFreshSecondariesWithNoPrimary(secondaries);
}
else
{
return SelectFreshSecondariesWithPrimary(primary, secondaries);
}
}
else
{
return secondaries;
}
}
private IEnumerable<ServerDescription> SelectFreshSecondariesWithNoPrimary(IEnumerable<ServerDescription> secondaries)
{
var smax = secondaries
.OrderByDescending(s => s.LastWriteTimestamp)
.FirstOrDefault();
if (smax == null)
{
return Enumerable.Empty<ServerDescription>();
}
return secondaries
.Where(s =>
{
var estimatedStaleness = smax.LastWriteTimestamp.Value - s.LastWriteTimestamp.Value + s.HeartbeatInterval;
return estimatedStaleness <= _maxStaleness;
});
}
private IEnumerable<ServerDescription> SelectFreshSecondariesWithPrimary(ServerDescription primary, IEnumerable<ServerDescription> secondaries)
{
var p = primary;
return secondaries
.Where(s =>
{
var estimatedStaleness = (s.LastUpdateTimestamp - s.LastWriteTimestamp.Value) - (p.LastUpdateTimestamp - p.LastWriteTimestamp.Value) + s.HeartbeatInterval;
return estimatedStaleness <= _maxStaleness;
});
}
private void EnsureMaxStalenessIsValid(ClusterDescription cluster)
{
if (_maxStaleness.HasValue)
{
if (_maxStaleness.Value < TimeSpan.FromSeconds(90))
{
var message = string.Format(
"Max staleness ({0} seconds) must greater than or equal to 90 seconds.",
(int)_maxStaleness.Value.TotalSeconds);
throw new Exception(message);
}
var anyServer = cluster.Servers.FirstOrDefault();
if (anyServer == null)
{
return;
}
var heartbeatInterval = anyServer.HeartbeatInterval; // all servers have the same HeartbeatInterval
var idleWritePeriod = TimeSpan.FromSeconds(10);
if (_maxStaleness.Value < heartbeatInterval + idleWritePeriod)
{
var message = string.Format(
"Max staleness ({0} seconds) must greater than or equal to heartbeat interval ({1} seconds) plus idle write period ({2} seconds).",
(int)_maxStaleness.Value.TotalSeconds,
(int)heartbeatInterval.TotalSeconds,
(int)idleWritePeriod.TotalSeconds);
throw new Exception(message);
}
}
}
}
}
| 38.986111 | 175 | 0.574813 | [
"MIT"
] | 13294029724/ET | Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Clusters/ServerSelectors/ReadPreferenceServerSelector.cs | 11,228 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
namespace Microsoft.AspNetCore.Razor.Tools
{
/// <summary>
/// Class for logging information about what happens in the server and client parts of the
/// Razor command line compiler and build tasks. Useful for debugging what is going on.
/// </summary>
/// <remarks>
/// To use the logging, set the environment variable RAZORBUILDSERVER_LOG to the name
/// of a file to log to. This file is logged to by both client and server components.
/// </remarks>
internal class ServerLogger
{
// Environment variable, if set, to enable logging and set the file to log to.
private const string EnvironmentVariable = "RAZORBUILDSERVER_LOG";
private static readonly Stream s_loggingStream;
private static string s_prefix = "---";
/// <summary>
/// Static class initializer that initializes logging.
/// </summary>
static ServerLogger()
{
s_loggingStream = null;
try
{
// Check if the environment
var loggingFileName = Environment.GetEnvironmentVariable(EnvironmentVariable);
if (loggingFileName != null)
{
IsLoggingEnabled = true;
// If the environment variable contains the path of a currently existing directory,
// then use a process-specific name for the log file and put it in that directory.
// Otherwise, assume that the environment variable specifies the name of the log file.
if (Directory.Exists(loggingFileName))
{
loggingFileName = Path.Combine(loggingFileName, $"razorserver.{GetCurrentProcessId()}.log");
}
// Open allowing sharing. We allow multiple processes to log to the same file, so we use share mode to allow that.
s_loggingStream = new FileStream(loggingFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
}
}
catch (Exception e)
{
LogException(e, "Failed to create logging stream");
}
}
public static bool IsLoggingEnabled { get; }
/// <summary>
/// Set the logging prefix that describes our role.
/// Typically a 3-letter abbreviation. If logging happens before this, it's logged with "---".
/// </summary>
public static void Initialize(string outputPrefix)
{
s_prefix = outputPrefix;
}
/// <summary>
/// Log an exception. Also logs information about inner exceptions.
/// </summary>
public static void LogException(Exception e, string reason)
{
if (IsLoggingEnabled)
{
Log("Exception '{0}' occurred during '{1}'. Stack trace:\r\n{2}", e.Message, reason, e.StackTrace);
var innerExceptionLevel = 0;
e = e.InnerException;
while (e != null)
{
Log("Inner exception[{0}] '{1}'. Stack trace: \r\n{1}", innerExceptionLevel, e.Message, e.StackTrace);
e = e.InnerException;
innerExceptionLevel += 1;
}
}
}
/// <summary>
/// Log a line of text to the logging file, with string.Format arguments.
/// </summary>
public static void Log(string format, params object[] arguments)
{
if (IsLoggingEnabled)
{
Log(string.Format(CultureInfo.InvariantCulture, format, arguments));
}
}
/// <summary>
/// Log a line of text to the logging file.
/// </summary>
/// <param name="message"></param>
public static void Log(string message)
{
if (IsLoggingEnabled)
{
var prefix = GetLoggingPrefix();
var output = prefix + message + "\r\n";
var bytes = Encoding.UTF8.GetBytes(output);
// Because multiple processes might be logging to the same file, we always seek to the end,
// write, and flush.
s_loggingStream.Seek(0, SeekOrigin.End);
s_loggingStream.Write(bytes, 0, bytes.Length);
s_loggingStream.Flush();
}
}
private static int GetCurrentProcessId()
{
var process = Process.GetCurrentProcess();
return process.Id;
}
private static int GetCurrentThreadId()
{
return Environment.CurrentManagedThreadId;
}
/// <summary>
/// Get the string that prefixes all log entries. Shows the process, thread, and time.
/// </summary>
private static string GetLoggingPrefix()
{
return string.Format(CultureInfo.InvariantCulture, "{0} PID={1} TID={2} Ticks={3}: ", s_prefix, GetCurrentProcessId(), GetCurrentThreadId(), Environment.TickCount);
}
}
}
| 37.040816 | 176 | 0.568595 | [
"Apache-2.0"
] | 1n5an1ty/aspnetcore | src/Razor/Microsoft.AspNetCore.Razor.Tools/src/ServerProtocol/ServerLogger.cs | 5,445 | C# |
namespace ExactOnline.Client.Models.SystemBase
{
using System;
[SupportedActionsSDK(false, true, false, false)]
[DataServiceKey("ID")]
public class AvailableFeature
{
/// <summary>The description of the feature.</summary>
public string Description { get; set; }
/// <summary>The ID of the feature.</summary>
public Int32 ID { get; set; }
}
} | 28.428571 | 62 | 0.635678 | [
"MIT"
] | FWest98/exactonline-api-dotnet-client | src/ExactOnline.Client.Models/SystemBase/AvailableFeature.cs | 398 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.Dingtalkdrive_1_0.Models
{
public class GetFileInfoRequest : TeaModel {
/// <summary>
/// 用户id
/// </summary>
[NameInMap("unionId")]
[Validation(Required=false)]
public string UnionId { get; set; }
}
}
| 19.136364 | 54 | 0.631829 | [
"Apache-2.0"
] | aliyun/dingtalk-sdk | dingtalk/csharp/core/drive_1_0/Models/GetFileInfoRequest.cs | 425 | C# |
using Newtonsoft.Json;
using zPoolMiner.Configs;
using zPoolMiner.Miners.Grouping;
using zPoolMiner.Miners.Parsing;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using zPoolMiner;
using zPoolMiner.Enums;
using System.Windows.Forms;
namespace zPoolMiner.Miners
{
public class MiniZ : Miner
{
#pragma warning disable IDE1006
private class Result
{
public uint gpuid { get; set; }
public uint cudaid { get; set; }
public string busid { get; set; }
public uint gpu_status { get; set; }
public int solver { get; set; }
public int temperature { get; set; }
public uint gpu_power_usage { get; set; }
public double speed_sps { get; set; }
public uint accepted_shares { get; set; }
public uint rejected_shares { get; set; }
}
private class JsonApiResponse
{
public uint id { get; set; }
public string method { get; set; }
public object error { get; set; }
public List<Result> result { get; set; }
}
#pragma warning restore IDE1006
private int _benchmarkTimeWait = 2 * 45;
private int _benchmarkReadCount = 0;
private double _benchmarkSum;
private const string LookForStart = "(";
private const string LookForEnd = ")sol/s";
private double prevSpeed = 0;
#pragma warning disable CS0649 // Field 'MiniZ._started' is never assigned to, and will always have its default value
private DateTime _started;
#pragma warning restore CS0649 // Field 'MiniZ._started' is never assigned to, and will always have its default value
private bool firstStart = true;
//private string[,] myServers = Form_Main.myServers;
public MiniZ() : base("miniZ")
{
//ConectionType = NhmConectionType.NONE;
}
public override void Start(string url, string btcAddress, string worker)
{
IsAPIReadException = false;
firstStart = true;
LastCommandLine = GetStartCommand(url, btcAddress, worker);
ProcessHandle = _Start();
}
static int GetWinVer(Version ver)
{
if (ver.Major == 6 & ver.Minor == 1)
return 7;
else if (ver.Major == 6 & ver.Minor == 2)
return 8;
else
return 10;
}
private string GetStartCommand(string url, string btcAddress, string worker)
{
if (MiningSession.DONATION_SESSION)
{
if (url.Contains("zpool.ca"))
{
btcAddress = Globals.DemoUser;
worker = "c=BTC,ID=Donation";
}
if (url.Contains("ahashpool.com"))
{
btcAddress = Globals.DemoUser;
worker = "c=BTC,ID=Donation";
}
if (url.Contains("hashrefinery.com"))
{
btcAddress = Globals.DemoUser;
worker = "c=BTC,ID=Donation";
}
if (url.Contains("nicehash.com"))
{
btcAddress = Globals.DemoUser;
worker = "c=BTC,ID=Donation";
}
if (url.Contains("zergpool.com"))
{
btcAddress = Globals.DemoUser;
worker = "c=BTC,ID=Donation";
}
if (url.Contains("blockmasters.co"))
{
btcAddress = Globals.DemoUser;
worker = "c=BTC,ID=Donation";
}
if (url.Contains("blazepool.com"))
{
btcAddress = Globals.DemoUser;
worker = "c=BTC,ID=Donation";
}
if (url.Contains("miningpoolhub.com"))
{
btcAddress = "cryptominer.Devfee";
worker = "x";
}
else
{
btcAddress = Globals.DemoUser;
}
}
else
{
if (url.Contains("zpool.ca"))
{
btcAddress = zPoolMiner.Globals.GetzpoolUser();
worker = zPoolMiner.Globals.GetzpoolWorker();
}
if (url.Contains("ahashpool.com"))
{
btcAddress = zPoolMiner.Globals.GetahashUser();
worker = zPoolMiner.Globals.GetahashWorker();
}
if (url.Contains("hashrefinery.com"))
{
btcAddress = zPoolMiner.Globals.GethashrefineryUser();
worker = zPoolMiner.Globals.GethashrefineryWorker();
}
if (url.Contains("nicehash.com"))
{
btcAddress = zPoolMiner.Globals.GetnicehashUser();
worker = zPoolMiner.Globals.GetnicehashWorker();
}
if (url.Contains("zergpool.com"))
{
btcAddress = zPoolMiner.Globals.GetzergUser();
worker = zPoolMiner.Globals.GetzergWorker();
}
if (url.Contains("minemoney.co"))
{
btcAddress = zPoolMiner.Globals.GetminemoneyUser();
worker = zPoolMiner.Globals.GetminemoneyWorker();
}
if (url.Contains("blazepool.com"))
{
btcAddress = zPoolMiner.Globals.GetblazepoolUser();
worker = zPoolMiner.Globals.GetblazepoolWorker();
}
if (url.Contains("blockmasters.co"))
{
btcAddress = zPoolMiner.Globals.GetblockmunchUser();
worker = zPoolMiner.Globals.GetblockmunchWorker();
}
if (url.Contains("miningpoolhub.com"))
{
btcAddress = zPoolMiner.Globals.GetMPHUser();
worker = zPoolMiner.Globals.GetMPHWorker();
}
}
var server = url.Split(':')[0].Replace("stratum+tcp://", "");
var ARG = "";
var pool = "";
string address = btcAddress;
string username = GetUsername(btcAddress, worker);
if (MiningSetup.CurrentAlgorithmType == AlgorithmType.equihash144)
{
ARG = "--algo 144,5 --pers auto --oc1 ";
pool = "equihash144.mine.zergpool.com:2146";
}
if (MiningSetup.CurrentAlgorithmType == AlgorithmType.equihash125)
{
ARG = "--algo 125,4 --oc1 ";
pool = "equihash125.mine.zergpool.com:2150";
}
if (MiningSetup.CurrentAlgorithmType == AlgorithmType.equihash192)
{
ARG = "--algo 192,7 --pers auto --oc1 ";
pool = "equihash192.mine.zergpool.com:2144";
}
if (MiningSetup.CurrentAlgorithmType == AlgorithmType.equihash96)
{
ARG = "--algo 96,5 --pers auto --oc1 ";
pool = "equihash96.mine.zergpool.com:2148";
}
string sColor = "";
if (GetWinVer(Environment.OSVersion.Version) < 8)
{
sColor = " --nocolor";
}
var ret = GetDevicesCommandString()
+ sColor + ARG + "--templimit 95 --intensity 100 --latency --tempunits C " + " --url " + address + "@" + pool + " --pass=" + worker + ",m=party.NPlusMiner" + " --telemetry=" + APIPort;
return ret;
}
protected override string GetDevicesCommandString()
{
var deviceStringCommand = MiningSetup.MiningPairs.Aggregate(" --cuda-devices ",
(current, nvidiaPair) => current + (nvidiaPair.Device.IDByBus + " "));
deviceStringCommand +=
" " + ExtraLaunchParametersParser.ParseForMiningSetup(MiningSetup, DeviceType.NVIDIA);
return deviceStringCommand;
}
// benchmark stuff
protected void KillMinerBase(string exeName)
{
foreach (var process in Process.GetProcessesByName(exeName))
{
try { process.Kill(); }
catch (Exception e) { Helpers.ConsolePrint(MinerDeviceName, e.ToString()); }
}
}
protected override string BenchmarkCreateCommandLine(Algorithm algorithm, int time)
{
//CleanOldLogs();
string url = Globals.GetLocationURL(algorithm.CryptoMiner937ID, Globals.MiningLocation[ConfigManager.GeneralConfig.ServiceLocation], ConectionType);
var server = url.Split(':')[0].Replace("stratum+tcp://", "");
var ARG = "";
var pool = "";
//string address = btcAddress;
//string username = GetUsername(btcAddress, worker);
if (MiningSetup.CurrentAlgorithmType == AlgorithmType.equihash144)
{
ARG = "--algo 144,5 --pers auto --oc1 ";
pool = "equihash144.mine.zergpool.com:2146";
}
if (MiningSetup.CurrentAlgorithmType == AlgorithmType.equihash125)
{
ARG = "--algo 125,4 --oc1 ";
pool = "equihash125.mine.zergpool.com:2150";
}
if (MiningSetup.CurrentAlgorithmType == AlgorithmType.equihash192)
{
ARG = "--algo 192,7 --pers auto --oc1 ";
pool = "equihash192.mine.zergpool.com:2144";
}
if (MiningSetup.CurrentAlgorithmType == AlgorithmType.equihash96)
{
ARG = "--algo 96,5 --pers auto --oc1 ";
pool = "equihash96.mine.zergpool.com:2148";
}
string sColor = "";
if (GetWinVer(Environment.OSVersion.Version) < 8)
{
sColor = " --nocolor";
}
var ret = GetDevicesCommandString()
+ sColor + ARG + "--templimit 95 --intensity 100 --latency --tempunits C " + " --url " + "197LigiMdTnFrVwySeiEtLCiDoaGGzma67" + "@" + pool + " --pass=" + "c=BTC,ID=Benchmark" + ",m=party.NPlusMiner" + " --telemetry=" + APIPort + " --log-file=" + "bench.txt";
return ret;
}
protected override void BenchmarkThreadRoutine(object commandLine)
{
BenchmarkSignalQuit = false;
BenchmarkSignalHanged = false;
BenchmarkSignalFinnished = false;
BenchmarkException = null;
Thread.Sleep(ConfigManager.GeneralConfig.MinerRestartDelayMS);
try
{
Helpers.ConsolePrint("BENCHMARK", "Benchmark starts");
Helpers.ConsolePrint(MinerTAG(), "Benchmark should end in : " + _benchmarkTimeWait + " seconds");
BenchmarkHandle = BenchmarkStartProcess((string)commandLine);
BenchmarkHandle.WaitForExit(_benchmarkTimeWait + 2);
var benchmarkTimer = new Stopwatch();
benchmarkTimer.Reset();
benchmarkTimer.Start();
BenchmarkProcessStatus = BenchmarkProcessStatus.Running;
#pragma warning disable CS0219 // The variable 'keepRunning' is assigned but its value is never used
var keepRunning = true;
#pragma warning restore CS0219 // The variable 'keepRunning' is assigned but its value is never used
while (IsActiveProcess(BenchmarkHandle.Id))
{
if (benchmarkTimer.Elapsed.TotalSeconds >= (_benchmarkTimeWait + 2)
|| BenchmarkSignalQuit
|| BenchmarkSignalFinnished
|| BenchmarkSignalHanged
|| BenchmarkSignalTimedout
|| BenchmarkException != null)
{
var imageName = MinerExeName.Replace(".exe", "");
// maybe will have to KILL process
KillMinerBase(imageName);
if (BenchmarkSignalTimedout)
{
throw new Exception("Benchmark timedout");
}
if (BenchmarkException != null)
{
throw BenchmarkException;
}
if (BenchmarkSignalQuit)
{
throw new Exception("Termined by user request");
}
if (BenchmarkSignalFinnished)
{
break;
}
keepRunning = false;
break;
}
// wait a second reduce CPU load
Thread.Sleep(1000);
}
}
catch (Exception ex)
{
BenchmarkThreadRoutineCatch(ex);
}
finally
{
BenchmarkAlgorithm.BenchmarkSpeed = 0;
// find latest log file
var latestLogFile = "bench.txt";
var dirInfo = new DirectoryInfo(WorkingDirectory);
foreach (var file in dirInfo.GetFiles("bench.txt"))
{
latestLogFile = file.Name;
break;
}
// read file log
if (File.Exists(WorkingDirectory + latestLogFile))
{
var lines = new string[0];
var read = false;
var iteration = 0;
while (!read)
{
if (iteration < 10)
{
try
{
lines = File.ReadAllLines(WorkingDirectory + latestLogFile);
read = true;
Helpers.ConsolePrint(MinerTAG(),
"Successfully read log after " + iteration + " iterations");
}
catch (Exception ex)
{
Helpers.ConsolePrint(MinerTAG(), ex.Message);
Thread.Sleep(1000);
}
iteration++;
}
else
{
read = true; // Give up after 10s
Helpers.ConsolePrint(MinerTAG(), "Gave up on iteration " + iteration);
}
}
var addBenchLines = bench_lines.Count == 0;
foreach (var line in lines)
{
if (line != null)
{
bench_lines.Add(line);
var lineLowered = line.ToLower();
if (lineLowered.Contains(LookForStart) && lineLowered.Contains(LookForEnd))
{
if (_benchmarkReadCount > 2) //3 skip
{
_benchmarkSum += GetNumber(lineLowered);
}
++_benchmarkReadCount;
}
}
}
if (_benchmarkReadCount > 0)
{
BenchmarkAlgorithm.BenchmarkSpeed = _benchmarkSum / (_benchmarkReadCount - 3);
}
}
if (File.Exists(WorkingDirectory + latestLogFile))
{
File.Delete(WorkingDirectory + latestLogFile);
Console.WriteLine("MiniZ benchmark log Deleted.");
}
BenchmarkThreadRoutineFinish();
}
}
// stub benchmarks read from file
protected override void BenchmarkOutputErrorDataReceivedImpl(string outdata)
{
CheckOutdata(outdata);
}
protected override bool BenchmarkParseLine(string outdata)
{
Helpers.ConsolePrint("BENCHMARK", outdata);
return false;
}
protected double GetNumber(string outdata)
{
return GetNumber(outdata, LookForStart, LookForEnd);
}
protected double GetNumber(string outdata, string lookForStart, string lookForEnd)
{
try
{
double mult = 1;
var speedStart = outdata.IndexOf(lookForStart.ToLower());
var speed = outdata.Substring(speedStart, outdata.Length - speedStart);
speed = speed.Replace(lookForStart.ToLower(), "");
speed = speed.Substring(0, speed.IndexOf(lookForEnd.ToLower()));
if (speed.Contains("k"))
{
mult = 1000;
speed = speed.Replace("k", "");
}
else if (speed.Contains("m"))
{
mult = 1000000;
speed = speed.Replace("m", "");
}
//Helpers.ConsolePrint("speed", speed);
speed = speed.Trim();
try
{
return double.Parse(speed, CultureInfo.InvariantCulture) * mult;
}
catch
{
MessageBox.Show("Unsupported miner version - " + MiningSetup.MinerPath,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
BenchmarkSignalFinnished = true;
}
}
catch (Exception ex)
{
Helpers.ConsolePrint("GetNumber",
ex.Message + " | args => " + outdata + " | " + lookForEnd + " | " + lookForStart);
MessageBox.Show("Unsupported miner version - " + MiningSetup.MinerPath,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return 0;
}
public override async Task<APIData> GetSummaryAsync()
{
_currentMinerReadStatus = MinerAPIReadStatus.NONE;
var ad = new APIData(MiningSetup.CurrentAlgorithmType);
var elapsedSeconds = DateTime.Now.Subtract(_started).Seconds; ////PVS-Studio - stupid program!
// if (elapsedSeconds < 15 && firstStart)
if (firstStart)
// if (ad.Speed <= 0.0001)
{
Thread.Sleep(3000);
ad.Speed = 1;
firstStart = false;
return ad;
}
JsonApiResponse resp = null;
try
{
var bytesToSend = Encoding.ASCII.GetBytes("{\"id\":\"0\", \"method\":\"getstat\"}\\n");
var client = new TcpClient("127.0.0.1", APIPort);
var nwStream = client.GetStream();
await nwStream.WriteAsync(bytesToSend, 0, bytesToSend.Length);
var bytesToRead = new byte[client.ReceiveBufferSize];
var bytesRead = await nwStream.ReadAsync(bytesToRead, 0, client.ReceiveBufferSize);
var respStr = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
// Helpers.ConsolePrint("miniZ API:", respStr);
if (!respStr.Contains("speed_sps") && prevSpeed != 0)
{
client.Close();
_currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
ad.Speed = prevSpeed;
return ad;
}
resp = JsonConvert.DeserializeObject<JsonApiResponse>(respStr, Globals.JsonSettings);
client.Close();
}
catch (Exception ex)
{
Helpers.ConsolePrint(MinerTAG(), ex.Message);
_currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
ad.Speed = prevSpeed;
}
if (resp != null && resp.error == null)
{
ad.Speed = resp.result.Aggregate<Result, double>(0, (current, t1) => current + t1.speed_sps);
prevSpeed = ad.Speed;
_currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
if (ad.Speed == 0)
{
_currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
}
}
return ad;
}
protected override void _Stop(MinerStopType willswitch)
{
Stop_cpu_ccminer_sgminer_nheqminer(willswitch);
}
protected override int GET_MAX_CooldownTimeInMilliseconds()
{
return 60 * 1000 * 5; // 5 minute max, whole waiting time 75seconds
}
}
}
| 36.234458 | 280 | 0.509265 | [
"MIT"
] | hash-kings/Hash-Kings-Miner-V3 | zPoolMiner/Miners/Nvidia/miniZ.cs | 20,402 | C# |
using GDLibrary.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
namespace GDLibrary.Components
{
/// <summary>
/// Draws a user-defined array of VertexPositionNormalTexture vertices
/// </summary>
public class MeshRenderer : Renderer
{
//TODO - generalise for any IVertexType
protected Mesh mesh;
//TODO - If mesh data is changed then we must re-set the data in the buffers. Same for ModelRenderer too.
public Mesh Mesh
{
get
{
return mesh;
}
set
{
if (value != mesh && value != null)
{
mesh = value;
//TODO - update if transform changes
//BUG - on clone
// SetBoundingVolume();
}
}
}
public override void Draw(GraphicsDevice device)
{
device.SetVertexBuffer(mesh.VertexBuffer);
device.Indices = mesh.IndexBuffer;
device.DrawIndexedPrimitives(PrimitiveType.TriangleList,
0, 0, mesh.IndexBuffer.IndexCount / 3);
}
public override void SetBoundingVolume()
{
if (mesh == null)
throw new NullReferenceException("No mesh has been set for this renderer!");
var min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
var max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
var vertices = mesh.GetVertices();
foreach (var vertex in vertices)
{
min.X = Math.Min(vertex.X, min.X);
min.Y = Math.Min(vertex.Y, min.Y);
min.Z = Math.Min(vertex.Z, min.Z);
max.X = Math.Max(vertex.X, max.X);
max.Y = Math.Max(vertex.Y, max.Y);
max.Z = Math.Max(vertex.Z, max.Z);
}
boundingBox.Min = min;
boundingBox.Max = max;
var dx = max.X - min.X;
var dy = max.Y - min.Y;
var dz = max.Z - min.Z;
boundingSphere.Radius = (float)Math.Max(Math.Max(dx, dy), dz) / 2.0f;
boundingSphere.Center = transform.LocalTranslation;
}
#region Actions - Housekeeping
//TODO - Dispose
public override object Clone()
{
var clone = new MeshRenderer();
clone.material = material.Clone() as Material;
clone.Mesh = mesh.Clone() as Mesh;
return clone;
}
#endregion Actions - Housekeeping
}
} | 30.590909 | 113 | 0.521174 | [
"MIT"
] | D00225745/SpookyMineshaftProject | GD3_2021_GDLibrary/GD3_2021_GDLibrary/Core/Components/Renderers/MeshRenderer.cs | 2,694 | C# |
// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build sparc64,linux
// package unix -- go2cs converted at 2020 October 09 06:00:42 UTC
// import "cmd/vendor/golang.org/x/sys/unix" ==> using unix = go.cmd.vendor.golang.org.x.sys.unix_package
// Original source: C:\Go\src\cmd\vendor\golang.org\x\sys\unix\ztypes_linux_sparc64.go
using static go.builtin;
namespace go {
namespace cmd {
namespace vendor {
namespace golang.org {
namespace x {
namespace sys
{
public static partial class unix_package
{
public static readonly ulong SizeofPtr = (ulong)0x8UL;
public static readonly ulong SizeofLong = (ulong)0x8UL;
private partial struct _C_long // : long
{
}
public partial struct Timespec
{
public long Sec;
public long Nsec;
}
public partial struct Timeval
{
public long Sec;
public int Usec;
public array<byte> _;
}
public partial struct Timex
{
public uint Modes;
public long Offset;
public long Freq;
public long Maxerror;
public long Esterror;
public int Status;
public long Constant;
public long Precision;
public long Tolerance;
public Timeval Time;
public long Tick;
public long Ppsfreq;
public long Jitter;
public int Shift;
public long Stabil;
public long Jitcnt;
public long Calcnt;
public long Errcnt;
public long Stbcnt;
public int Tai;
public array<byte> _;
}
public partial struct Time_t // : long
{
}
public partial struct Tms
{
public long Utime;
public long Stime;
public long Cutime;
public long Cstime;
}
public partial struct Utimbuf
{
public long Actime;
public long Modtime;
}
public partial struct Rusage
{
public Timeval Utime;
public Timeval Stime;
public long Maxrss;
public long Ixrss;
public long Idrss;
public long Isrss;
public long Minflt;
public long Majflt;
public long Nswap;
public long Inblock;
public long Oublock;
public long Msgsnd;
public long Msgrcv;
public long Nsignals;
public long Nvcsw;
public long Nivcsw;
}
public partial struct Stat_t
{
public ulong Dev;
public ushort _;
public ulong Ino;
public uint Mode;
public uint Nlink;
public uint Uid;
public uint Gid;
public ulong Rdev;
public ushort _;
public long Size;
public long Blksize;
public long Blocks;
public Timespec Atim;
public Timespec Mtim;
public Timespec Ctim;
public ulong _;
public ulong _;
}
public partial struct Dirent
{
public ulong Ino;
public long Off;
public ushort Reclen;
public byte Type;
public array<sbyte> Name;
public array<byte> _;
}
public partial struct Flock_t
{
public short Type;
public short Whence;
public long Start;
public long Len;
public int Pid;
public short _;
public array<byte> _;
}
public static readonly ulong FADV_DONTNEED = (ulong)0x4UL;
public static readonly ulong FADV_NOREUSE = (ulong)0x5UL;
public partial struct RawSockaddr
{
public ushort Family;
public array<sbyte> Data;
}
public partial struct RawSockaddrAny
{
public RawSockaddr Addr;
public array<sbyte> Pad;
}
public partial struct Iovec
{
public ptr<byte> Base;
public ulong Len;
}
public partial struct Msghdr
{
public ptr<byte> Name;
public uint Namelen;
public ptr<Iovec> Iov;
public ulong Iovlen;
public ptr<byte> Control;
public ulong Controllen;
public int Flags;
public array<byte> _;
}
public partial struct Cmsghdr
{
public ulong Len;
public int Level;
public int Type;
}
public static readonly ulong SizeofIovec = (ulong)0x10UL;
public static readonly ulong SizeofMsghdr = (ulong)0x38UL;
public static readonly ulong SizeofCmsghdr = (ulong)0x10UL;
public static readonly ulong SizeofSockFprog = (ulong)0x10UL;
public partial struct PtraceRegs
{
public array<ulong> Regs;
public ulong Tstate;
public ulong Tpc;
public ulong Tnpc;
public uint Y;
public uint Magic;
}
public partial struct FdSet
{
public array<long> Bits;
}
public partial struct Sysinfo_t
{
public long Uptime;
public array<ulong> Loads;
public ulong Totalram;
public ulong Freeram;
public ulong Sharedram;
public ulong Bufferram;
public ulong Totalswap;
public ulong Freeswap;
public ushort Procs;
public ushort Pad;
public ulong Totalhigh;
public ulong Freehigh;
public uint Unit;
public array<sbyte> _;
public array<byte> _;
}
public partial struct Ustat_t
{
public int Tfree;
public ulong Tinode;
public array<sbyte> Fname;
public array<sbyte> Fpack;
public array<byte> _;
}
public partial struct EpollEvent
{
public uint Events;
public int _;
public int Fd;
public int Pad;
}
public static readonly ulong POLLRDHUP = (ulong)0x800UL;
public partial struct Sigset_t
{
public array<ulong> Val;
}
private static readonly ulong _C__NSIG = (ulong)0x41UL;
public partial struct Termios
{
public uint Iflag;
public uint Oflag;
public uint Cflag;
public uint Lflag;
public byte Line;
public array<byte> Cc;
public uint Ispeed;
public uint Ospeed;
}
public partial struct Taskstats
{
public ushort Version;
public uint Ac_exitcode;
public byte Ac_flag;
public byte Ac_nice;
public ulong Cpu_count;
public ulong Cpu_delay_total;
public ulong Blkio_count;
public ulong Blkio_delay_total;
public ulong Swapin_count;
public ulong Swapin_delay_total;
public ulong Cpu_run_real_total;
public ulong Cpu_run_virtual_total;
public array<sbyte> Ac_comm;
public byte Ac_sched;
public array<byte> Ac_pad;
public array<byte> _;
public uint Ac_uid;
public uint Ac_gid;
public uint Ac_pid;
public uint Ac_ppid;
public uint Ac_btime;
public ulong Ac_etime;
public ulong Ac_utime;
public ulong Ac_stime;
public ulong Ac_minflt;
public ulong Ac_majflt;
public ulong Coremem;
public ulong Virtmem;
public ulong Hiwater_rss;
public ulong Hiwater_vm;
public ulong Read_char;
public ulong Write_char;
public ulong Read_syscalls;
public ulong Write_syscalls;
public ulong Read_bytes;
public ulong Write_bytes;
public ulong Cancelled_write_bytes;
public ulong Nvcsw;
public ulong Nivcsw;
public ulong Ac_utimescaled;
public ulong Ac_stimescaled;
public ulong Cpu_scaled_run_real_total;
public ulong Freepages_count;
public ulong Freepages_delay_total;
public ulong Thrashing_count;
public ulong Thrashing_delay_total;
public ulong Ac_btime64;
}
private partial struct cpuMask // : ulong
{
}
private static readonly ulong _NCPUBITS = (ulong)0x40UL;
public static readonly ulong CBitFieldMaskBit0 = (ulong)0x8000000000000000UL;
public static readonly ulong CBitFieldMaskBit1 = (ulong)0x4000000000000000UL;
public static readonly ulong CBitFieldMaskBit2 = (ulong)0x2000000000000000UL;
public static readonly ulong CBitFieldMaskBit3 = (ulong)0x1000000000000000UL;
public static readonly ulong CBitFieldMaskBit4 = (ulong)0x800000000000000UL;
public static readonly ulong CBitFieldMaskBit5 = (ulong)0x400000000000000UL;
public static readonly ulong CBitFieldMaskBit6 = (ulong)0x200000000000000UL;
public static readonly ulong CBitFieldMaskBit7 = (ulong)0x100000000000000UL;
public static readonly ulong CBitFieldMaskBit8 = (ulong)0x80000000000000UL;
public static readonly ulong CBitFieldMaskBit9 = (ulong)0x40000000000000UL;
public static readonly ulong CBitFieldMaskBit10 = (ulong)0x20000000000000UL;
public static readonly ulong CBitFieldMaskBit11 = (ulong)0x10000000000000UL;
public static readonly ulong CBitFieldMaskBit12 = (ulong)0x8000000000000UL;
public static readonly ulong CBitFieldMaskBit13 = (ulong)0x4000000000000UL;
public static readonly ulong CBitFieldMaskBit14 = (ulong)0x2000000000000UL;
public static readonly ulong CBitFieldMaskBit15 = (ulong)0x1000000000000UL;
public static readonly ulong CBitFieldMaskBit16 = (ulong)0x800000000000UL;
public static readonly ulong CBitFieldMaskBit17 = (ulong)0x400000000000UL;
public static readonly ulong CBitFieldMaskBit18 = (ulong)0x200000000000UL;
public static readonly ulong CBitFieldMaskBit19 = (ulong)0x100000000000UL;
public static readonly ulong CBitFieldMaskBit20 = (ulong)0x80000000000UL;
public static readonly ulong CBitFieldMaskBit21 = (ulong)0x40000000000UL;
public static readonly ulong CBitFieldMaskBit22 = (ulong)0x20000000000UL;
public static readonly ulong CBitFieldMaskBit23 = (ulong)0x10000000000UL;
public static readonly ulong CBitFieldMaskBit24 = (ulong)0x8000000000UL;
public static readonly ulong CBitFieldMaskBit25 = (ulong)0x4000000000UL;
public static readonly ulong CBitFieldMaskBit26 = (ulong)0x2000000000UL;
public static readonly ulong CBitFieldMaskBit27 = (ulong)0x1000000000UL;
public static readonly ulong CBitFieldMaskBit28 = (ulong)0x800000000UL;
public static readonly ulong CBitFieldMaskBit29 = (ulong)0x400000000UL;
public static readonly ulong CBitFieldMaskBit30 = (ulong)0x200000000UL;
public static readonly ulong CBitFieldMaskBit31 = (ulong)0x100000000UL;
public static readonly ulong CBitFieldMaskBit32 = (ulong)0x80000000UL;
public static readonly ulong CBitFieldMaskBit33 = (ulong)0x40000000UL;
public static readonly ulong CBitFieldMaskBit34 = (ulong)0x20000000UL;
public static readonly ulong CBitFieldMaskBit35 = (ulong)0x10000000UL;
public static readonly ulong CBitFieldMaskBit36 = (ulong)0x8000000UL;
public static readonly ulong CBitFieldMaskBit37 = (ulong)0x4000000UL;
public static readonly ulong CBitFieldMaskBit38 = (ulong)0x2000000UL;
public static readonly ulong CBitFieldMaskBit39 = (ulong)0x1000000UL;
public static readonly ulong CBitFieldMaskBit40 = (ulong)0x800000UL;
public static readonly ulong CBitFieldMaskBit41 = (ulong)0x400000UL;
public static readonly ulong CBitFieldMaskBit42 = (ulong)0x200000UL;
public static readonly ulong CBitFieldMaskBit43 = (ulong)0x100000UL;
public static readonly ulong CBitFieldMaskBit44 = (ulong)0x80000UL;
public static readonly ulong CBitFieldMaskBit45 = (ulong)0x40000UL;
public static readonly ulong CBitFieldMaskBit46 = (ulong)0x20000UL;
public static readonly ulong CBitFieldMaskBit47 = (ulong)0x10000UL;
public static readonly ulong CBitFieldMaskBit48 = (ulong)0x8000UL;
public static readonly ulong CBitFieldMaskBit49 = (ulong)0x4000UL;
public static readonly ulong CBitFieldMaskBit50 = (ulong)0x2000UL;
public static readonly ulong CBitFieldMaskBit51 = (ulong)0x1000UL;
public static readonly ulong CBitFieldMaskBit52 = (ulong)0x800UL;
public static readonly ulong CBitFieldMaskBit53 = (ulong)0x400UL;
public static readonly ulong CBitFieldMaskBit54 = (ulong)0x200UL;
public static readonly ulong CBitFieldMaskBit55 = (ulong)0x100UL;
public static readonly ulong CBitFieldMaskBit56 = (ulong)0x80UL;
public static readonly ulong CBitFieldMaskBit57 = (ulong)0x40UL;
public static readonly ulong CBitFieldMaskBit58 = (ulong)0x20UL;
public static readonly ulong CBitFieldMaskBit59 = (ulong)0x10UL;
public static readonly ulong CBitFieldMaskBit60 = (ulong)0x8UL;
public static readonly ulong CBitFieldMaskBit61 = (ulong)0x4UL;
public static readonly ulong CBitFieldMaskBit62 = (ulong)0x2UL;
public static readonly ulong CBitFieldMaskBit63 = (ulong)0x1UL;
public partial struct SockaddrStorage
{
public ushort Family;
public array<sbyte> _;
public ulong _;
}
public partial struct HDGeometry
{
public byte Heads;
public byte Sectors;
public ushort Cylinders;
public ulong Start;
}
public partial struct Statfs_t
{
public long Type;
public long Bsize;
public ulong Blocks;
public ulong Bfree;
public ulong Bavail;
public ulong Files;
public ulong Ffree;
public Fsid Fsid;
public long Namelen;
public long Frsize;
public long Flags;
public array<long> Spare;
}
public partial struct TpacketHdr
{
public ulong Status;
public uint Len;
public uint Snaplen;
public ushort Mac;
public ushort Net;
public uint Sec;
public uint Usec;
public array<byte> _;
}
public static readonly ulong SizeofTpacketHdr = (ulong)0x20UL;
public partial struct RTCPLLInfo
{
public int Ctrl;
public int Value;
public int Max;
public int Min;
public int Posmult;
public int Negmult;
public long Clock;
}
public partial struct BlkpgPartition
{
public long Start;
public long Length;
public int Pno;
public array<byte> Devname;
public array<byte> Volname;
public array<byte> _;
}
public static readonly ulong BLKPG = (ulong)0x20001269UL;
public partial struct XDPUmemReg
{
public ulong Addr;
public ulong Len;
public uint Size;
public uint Headroom;
public uint Flags;
public array<byte> _;
}
public partial struct CryptoUserAlg
{
public array<sbyte> Name;
public array<sbyte> Driver_name;
public array<sbyte> Module_name;
public uint Type;
public uint Mask;
public uint Refcnt;
public uint Flags;
}
public partial struct CryptoStatAEAD
{
public array<sbyte> Type;
public ulong Encrypt_cnt;
public ulong Encrypt_tlen;
public ulong Decrypt_cnt;
public ulong Decrypt_tlen;
public ulong Err_cnt;
}
public partial struct CryptoStatAKCipher
{
public array<sbyte> Type;
public ulong Encrypt_cnt;
public ulong Encrypt_tlen;
public ulong Decrypt_cnt;
public ulong Decrypt_tlen;
public ulong Verify_cnt;
public ulong Sign_cnt;
public ulong Err_cnt;
}
public partial struct CryptoStatCipher
{
public array<sbyte> Type;
public ulong Encrypt_cnt;
public ulong Encrypt_tlen;
public ulong Decrypt_cnt;
public ulong Decrypt_tlen;
public ulong Err_cnt;
}
public partial struct CryptoStatCompress
{
public array<sbyte> Type;
public ulong Compress_cnt;
public ulong Compress_tlen;
public ulong Decompress_cnt;
public ulong Decompress_tlen;
public ulong Err_cnt;
}
public partial struct CryptoStatHash
{
public array<sbyte> Type;
public ulong Hash_cnt;
public ulong Hash_tlen;
public ulong Err_cnt;
}
public partial struct CryptoStatKPP
{
public array<sbyte> Type;
public ulong Setsecret_cnt;
public ulong Generate_public_key_cnt;
public ulong Compute_shared_secret_cnt;
public ulong Err_cnt;
}
public partial struct CryptoStatRNG
{
public array<sbyte> Type;
public ulong Generate_cnt;
public ulong Generate_tlen;
public ulong Seed_cnt;
public ulong Err_cnt;
}
public partial struct CryptoStatLarval
{
public array<sbyte> Type;
}
public partial struct CryptoReportLarval
{
public array<sbyte> Type;
}
public partial struct CryptoReportHash
{
public array<sbyte> Type;
public uint Blocksize;
public uint Digestsize;
}
public partial struct CryptoReportCipher
{
public array<sbyte> Type;
public uint Blocksize;
public uint Min_keysize;
public uint Max_keysize;
}
public partial struct CryptoReportBlkCipher
{
public array<sbyte> Type;
public array<sbyte> Geniv;
public uint Blocksize;
public uint Min_keysize;
public uint Max_keysize;
public uint Ivsize;
}
public partial struct CryptoReportAEAD
{
public array<sbyte> Type;
public array<sbyte> Geniv;
public uint Blocksize;
public uint Maxauthsize;
public uint Ivsize;
}
public partial struct CryptoReportComp
{
public array<sbyte> Type;
}
public partial struct CryptoReportRNG
{
public array<sbyte> Type;
public uint Seedsize;
}
public partial struct CryptoReportAKCipher
{
public array<sbyte> Type;
}
public partial struct CryptoReportKPP
{
public array<sbyte> Type;
}
public partial struct CryptoReportAcomp
{
public array<sbyte> Type;
}
public partial struct LoopInfo
{
public int Number;
public uint Device;
public ulong Inode;
public uint Rdevice;
public int Offset;
public int Encrypt_type;
public int Encrypt_key_size;
public int Flags;
public array<sbyte> Name;
public array<byte> Encrypt_key;
public array<ulong> Init;
public array<sbyte> Reserved;
public array<byte> _;
}
public partial struct TIPCSubscr
{
public TIPCServiceRange Seq;
public uint Timeout;
public uint Filter;
public array<sbyte> Handle;
}
public partial struct TIPCSIOCLNReq
{
public uint Peer;
public uint Id;
public array<sbyte> Linkname;
}
public partial struct TIPCSIOCNodeIDReq
{
public uint Peer;
public array<sbyte> Id;
}
}
}}}}}}
| 32.089124 | 105 | 0.586217 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/cmd/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.cs | 21,243 | 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 Float = System.Single;
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.Data;
using System.Runtime.InteropServices;
namespace Microsoft.ML.Runtime.Internal.Internallearn
{
/// <summary>
/// Represents some common global operations over a type
/// including many unsafe operations.
/// </summary>
/// <typeparam name="T"></typeparam>
internal abstract class UnsafeTypeOps<T>
{
public abstract int Size { get; }
public abstract void Apply(ReadOnlySpan<T> array, Action<IntPtr> func);
public abstract void Write(T a, BinaryWriter writer);
public abstract T Read(BinaryReader reader);
}
internal static class UnsafeTypeOpsFactory
{
private static Dictionary<Type, object> _type2ops;
static UnsafeTypeOpsFactory()
{
_type2ops = new Dictionary<Type, object>();
_type2ops[typeof(sbyte)] = new SByteUnsafeTypeOps();
_type2ops[typeof(Byte)] = new ByteUnsafeTypeOps();
_type2ops[typeof(short)] = new Int16UnsafeTypeOps();
_type2ops[typeof(UInt16)] = new UInt16UnsafeTypeOps();
_type2ops[typeof(int)] = new Int32UnsafeTypeOps();
_type2ops[typeof(UInt32)] = new UInt32UnsafeTypeOps();
_type2ops[typeof(long)] = new Int64UnsafeTypeOps();
_type2ops[typeof(UInt64)] = new UInt64UnsafeTypeOps();
_type2ops[typeof(Single)] = new SingleUnsafeTypeOps();
_type2ops[typeof(Double)] = new DoubleUnsafeTypeOps();
_type2ops[typeof(TimeSpan)] = new TimeSpanUnsafeTypeOps();
_type2ops[typeof(RowId)] = new UgUnsafeTypeOps();
}
public static UnsafeTypeOps<T> Get<T>()
{
return (UnsafeTypeOps<T>)_type2ops[typeof(T)];
}
private sealed class SByteUnsafeTypeOps : UnsafeTypeOps<sbyte>
{
public override int Size { get { return sizeof(sbyte); } }
public override unsafe void Apply(ReadOnlySpan<sbyte> array, Action<IntPtr> func)
{
fixed (sbyte* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(sbyte a, BinaryWriter writer) { writer.Write(a); }
public override sbyte Read(BinaryReader reader) { return reader.ReadSByte(); }
}
private sealed class ByteUnsafeTypeOps : UnsafeTypeOps<Byte>
{
public override int Size { get { return sizeof(Byte); } }
public override unsafe void Apply(ReadOnlySpan<Byte> array, Action<IntPtr> func)
{
fixed (Byte* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(Byte a, BinaryWriter writer) { writer.Write(a); }
public override Byte Read(BinaryReader reader) { return reader.ReadByte(); }
}
private sealed class Int16UnsafeTypeOps : UnsafeTypeOps<short>
{
public override int Size { get { return sizeof(short); } }
public override unsafe void Apply(ReadOnlySpan<short> array, Action<IntPtr> func)
{
fixed (short* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(short a, BinaryWriter writer) { writer.Write(a); }
public override short Read(BinaryReader reader) { return reader.ReadInt16(); }
}
private sealed class UInt16UnsafeTypeOps : UnsafeTypeOps<UInt16>
{
public override int Size { get { return sizeof(UInt16); } }
public override unsafe void Apply(ReadOnlySpan<UInt16> array, Action<IntPtr> func)
{
fixed (UInt16* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(UInt16 a, BinaryWriter writer) { writer.Write(a); }
public override UInt16 Read(BinaryReader reader) { return reader.ReadUInt16(); }
}
private sealed class Int32UnsafeTypeOps : UnsafeTypeOps<int>
{
public override int Size { get { return sizeof(int); } }
public override unsafe void Apply(ReadOnlySpan<int> array, Action<IntPtr> func)
{
fixed (int* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(int a, BinaryWriter writer) { writer.Write(a); }
public override int Read(BinaryReader reader) { return reader.ReadInt32(); }
}
private sealed class UInt32UnsafeTypeOps : UnsafeTypeOps<UInt32>
{
public override int Size { get { return sizeof(UInt32); } }
public override unsafe void Apply(ReadOnlySpan<UInt32> array, Action<IntPtr> func)
{
fixed (UInt32* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(UInt32 a, BinaryWriter writer) { writer.Write(a); }
public override UInt32 Read(BinaryReader reader) { return reader.ReadUInt32(); }
}
private sealed class Int64UnsafeTypeOps : UnsafeTypeOps<long>
{
public override int Size { get { return sizeof(long); } }
public override unsafe void Apply(ReadOnlySpan<long> array, Action<IntPtr> func)
{
fixed (long* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(long a, BinaryWriter writer) { writer.Write(a); }
public override long Read(BinaryReader reader) { return reader.ReadInt64(); }
}
private sealed class UInt64UnsafeTypeOps : UnsafeTypeOps<UInt64>
{
public override int Size { get { return sizeof(UInt64); } }
public override unsafe void Apply(ReadOnlySpan<UInt64> array, Action<IntPtr> func)
{
fixed (UInt64* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(UInt64 a, BinaryWriter writer) { writer.Write(a); }
public override UInt64 Read(BinaryReader reader) { return reader.ReadUInt64(); }
}
private sealed class SingleUnsafeTypeOps : UnsafeTypeOps<Single>
{
public override int Size { get { return sizeof(Single); } }
public override unsafe void Apply(ReadOnlySpan<Single> array, Action<IntPtr> func)
{
fixed (Single* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(Single a, BinaryWriter writer) { writer.Write(a); }
public override Single Read(BinaryReader reader) { return reader.ReadSingle(); }
}
private sealed class DoubleUnsafeTypeOps : UnsafeTypeOps<Double>
{
public override int Size { get { return sizeof(Double); } }
public override unsafe void Apply(ReadOnlySpan<Double> array, Action<IntPtr> func)
{
fixed (Double* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(Double a, BinaryWriter writer) { writer.Write(a); }
public override Double Read(BinaryReader reader) { return reader.ReadDouble(); }
}
private sealed class TimeSpanUnsafeTypeOps : UnsafeTypeOps<TimeSpan>
{
public override int Size { get { return sizeof(long); } }
public override unsafe void Apply(ReadOnlySpan<TimeSpan> array, Action<IntPtr> func)
{
fixed (TimeSpan* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(TimeSpan a, BinaryWriter writer) { writer.Write(a.Ticks); }
public override TimeSpan Read(BinaryReader reader)
{
var ticks = reader.ReadInt64();
return new TimeSpan(ticks == long.MinValue ? default : ticks);
}
}
private sealed class UgUnsafeTypeOps : UnsafeTypeOps<RowId>
{
public override int Size { get { return 2 * sizeof(ulong); } }
public override unsafe void Apply(ReadOnlySpan<RowId> array, Action<IntPtr> func)
{
fixed (RowId* pArray = &MemoryMarshal.GetReference(array))
func(new IntPtr(pArray));
}
public override void Write(RowId a, BinaryWriter writer) { writer.Write(a.Low); writer.Write(a.High); }
public override RowId Read(BinaryReader reader)
{
ulong lo = reader.ReadUInt64();
ulong hi = reader.ReadUInt64();
return new RowId(lo, hi);
}
}
}
}
| 44.791469 | 115 | 0.602476 | [
"MIT"
] | Zruty0/machinelearning | src/Microsoft.ML.Data/DataLoadSave/Binary/UnsafeTypeOps.cs | 9,451 | C# |
public class FireNation : Nation
{
public FireNation()
{
}
public override string Name => "Fire";
} | 14.625 | 42 | 0.606838 | [
"MIT"
] | DimchoLakov/CSharpOOPBasics | Exams/04.12-July-2017-Avatar-DotNetFramework/Avatar/Entities/Nations/FireNation.cs | 119 | C# |
using Chisel.Core;
using Chisel.Components;
using UnitySceneExtensions;
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor.EditorTools;
using UnityEngine.Profiling;
#if !UNITY_2020_2_OR_NEWER
using ToolManager = UnityEditor.EditorTools;
#endif
namespace Chisel.Editors
{
public sealed class ChiselUnityEventsManager
{
[UnityEditor.InitializeOnLoadMethod]
[RuntimeInitializeOnLoadMethod]
public static void Initialize()
{
// Note that it's always safer to first unregister an event before
// assigning it, since this will avoid double assigning / leaking events
// whenever this code is, for whatever reason, run more than once.
// Update loop
UnityEditor.EditorApplication.update -= OnEditorApplicationUpdate;
UnityEditor.EditorApplication.update += OnEditorApplicationUpdate;
// Called after prefab instances in the scene have been updated.
UnityEditor.PrefabUtility.prefabInstanceUpdated -= OnPrefabInstanceUpdated;
UnityEditor.PrefabUtility.prefabInstanceUpdated += OnPrefabInstanceUpdated;
// OnGUI events for every visible list item in the HierarchyWindow.
UnityEditor.EditorApplication.hierarchyWindowItemOnGUI -= OnHierarchyWindowItemOnGUI;
UnityEditor.EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyWindowItemOnGUI;
// Triggered when currently active/selected item has changed.
UnityEditor.Selection.selectionChanged -= OnSelectionChanged;
UnityEditor.Selection.selectionChanged += OnSelectionChanged;
// Triggered when currently active/selected item has changed.
ChiselSurfaceSelectionManager.selectionChanged -= OnSurfaceSelectionChanged;
ChiselSurfaceSelectionManager.selectionChanged += OnSurfaceSelectionChanged;
ChiselSurfaceSelectionManager.hoverChanged -= OnSurfaceHoverChanged;
ChiselSurfaceSelectionManager.hoverChanged += OnSurfaceHoverChanged;
UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
UnityEditor.EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
// Triggered when changing visibility/picking in hierarchy
UnityEditor.SceneVisibilityManager.visibilityChanged += OnVisibilityChanged;
UnityEditor.SceneVisibilityManager.pickingChanged += OnPickingChanged;
// Callback that is triggered after an undo or redo was executed.
UnityEditor.Undo.undoRedoPerformed -= OnUndoRedoPerformed;
UnityEditor.Undo.undoRedoPerformed += OnUndoRedoPerformed;
UnityEditor.Undo.postprocessModifications -= OnPostprocessModifications;
UnityEditor.Undo.postprocessModifications += OnPostprocessModifications;
UnityEditor.Undo.willFlushUndoRecord -= OnWillFlushUndoRecord;
UnityEditor.Undo.willFlushUndoRecord += OnWillFlushUndoRecord;
UnityEditor.SceneView.beforeSceneGui -= OnBeforeSceneGUI;
UnityEditor.SceneView.beforeSceneGui += OnBeforeSceneGUI;
UnityEditor.SceneView.duringSceneGui -= OnDuringSceneGUI;
UnityEditor.SceneView.duringSceneGui += OnDuringSceneGUI;
UnityEditor.SceneManagement.EditorSceneManager.activeSceneChangedInEditMode += OnActiveSceneChanged;
ChiselNodeHierarchyManager.NodeHierarchyReset -= OnHierarchyReset;
ChiselNodeHierarchyManager.NodeHierarchyReset += OnHierarchyReset;
ChiselNodeHierarchyManager.NodeHierarchyModified -= OnNodeHierarchyModified;
ChiselNodeHierarchyManager.NodeHierarchyModified += OnNodeHierarchyModified;
ChiselNodeHierarchyManager.TransformationChanged -= OnTransformationChanged;
ChiselNodeHierarchyManager.TransformationChanged += OnTransformationChanged;
ChiselGeneratedModelMeshManager.PostUpdateModels -= OnPostUpdateModels;
ChiselGeneratedModelMeshManager.PostUpdateModels += OnPostUpdateModels;
ChiselGeneratedModelMeshManager.PostReset -= OnPostResetModels;
ChiselGeneratedModelMeshManager.PostReset += OnPostResetModels;
ToolManager.activeToolChanged -= OnEditModeChanged;
ToolManager.activeToolChanged += OnEditModeChanged;
ChiselClickSelectionManager.Instance.OnReset();
ChiselOutlineRenderer.Instance.OnReset();
// TODO: clean this up
ChiselGeneratorComponent.GetSelectedVariantsOfBrushOrSelf = ChiselSyncSelection.GetSelectedVariantsOfBrushOrSelf;
}
private static void OnPickingChanged()
{
ChiselGeneratedComponentManager.OnVisibilityChanged();
}
private static void OnVisibilityChanged()
{
ChiselGeneratedComponentManager.OnVisibilityChanged();
}
private static void OnActiveSceneChanged(Scene prevScene, Scene newScene)
{
ChiselModelManager.OnActiveSceneChanged(prevScene, newScene);
}
static void OnTransformationChanged()
{
ChiselOutlineRenderer.Instance.OnTransformationChanged();
}
static void OnBeforeSceneGUI(SceneView sceneView)
{
Profiler.BeginSample("OnBeforeSceneGUI");
ChiselDrawModes.HandleDrawMode(sceneView);
Profiler.EndSample();
}
static void OnDuringSceneGUI(SceneView sceneView)
{
Profiler.BeginSample("OnDuringSceneGUI");
// Workaround where Unity stops redrawing sceneview after a second, which makes hovering over edge visualization stop working
if (Event.current.type == EventType.MouseMove)
sceneView.Repaint();
var prevSkin = GUI.skin;
GUI.skin = ChiselSceneGUIStyle.GetSceneSkin();
try
{
ChiselSceneGUIStyle.Update();
ChiselGridSettings.GridOnSceneGUI(sceneView);
ChiselOutlineRenderer.Instance.OnSceneGUI(sceneView);
if (EditorWindow.mouseOverWindow == sceneView || // This helps prevent weird issues with overlapping sceneviews + avoid some performance issues with multiple sceneviews open
(Event.current.type != EventType.MouseMove && Event.current.type != EventType.Layout))
{
ChiselDragAndDropManager.Instance.OnSceneGUI(sceneView);
ChiselClickSelectionManager.Instance.OnSceneGUI(sceneView);
}
if (Tools.current != Tool.Custom)
ChiselEditToolBase.ShowDefaultOverlay();
}
finally
{
GUI.skin = prevSkin;
}
Profiler.EndSample();
}
private static void OnEditModeChanged()//IChiselToolMode prevEditMode, IChiselToolMode newEditMode)
{
ChiselOutlineRenderer.Instance.OnEditModeChanged();
if (Tools.current != Tool.Custom)
{
ChiselGeneratorManager.ActivateTool(null);
}
ChiselGeneratorManager.ActivateTool(ChiselGeneratorManager.GeneratorMode);
}
private static void OnSelectionChanged()
{
ChiselClickSelectionManager.Instance.OnSelectionChanged();
ChiselOutlineRenderer.Instance.OnSelectionChanged();
ChiselEditToolBase.NotifyOnSelectionChanged();
}
private static void OnSurfaceSelectionChanged()
{
ChiselOutlineRenderer.Instance.OnSurfaceSelectionChanged();
}
private static void OnSurfaceHoverChanged()
{
ChiselOutlineRenderer.Instance.OnSurfaceHoverChanged();
}
private static void OnPostUpdateModels()
{
ChiselOutlineRenderer.Instance.OnGeneratedMeshesChanged();
}
private static void OnPostResetModels()
{
ChiselOutlineRenderer.Instance.OnReset();
}
private static void OnNodeHierarchyModified()
{
ChiselOutlineRenderer.Instance.OnReset();
// Prevent infinite loops
if (Event.current != null &&
Event.current.type == EventType.Repaint)
return;
Editors.ChiselManagedHierarchyView.RepaintAll();
Editors.ChiselInternalHierarchyView.RepaintAll();
// THIS IS SLOW! DON'T DO THIS
//UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
}
private static void OnHierarchyReset()
{
// Prevent infinite loops
if (Event.current != null &&
Event.current.type == EventType.Repaint)
return;
Editors.ChiselManagedHierarchyView.RepaintAll();
Editors.ChiselInternalHierarchyView.RepaintAll();
}
private static void OnPrefabInstanceUpdated(GameObject instance)
{
ChiselNodeHierarchyManager.OnPrefabInstanceUpdated(instance);
}
private static void OnEditorApplicationUpdate()
{
if (EditorApplication.isPlayingOrWillChangePlaymode)
return;
ChiselNodeHierarchyManager.Update();
ChiselGeneratedModelMeshManager.UpdateModels();
ChiselNodeEditorBase.HandleCancelEvent();
}
private static void OnHierarchyWindowItemOnGUI(int instanceID, Rect selectionRect)
{
Profiler.BeginSample("OnHierarchyWindowItemOnGUI");
try
{
var obj = UnityEditor.EditorUtility.InstanceIDToObject(instanceID);
if (!obj)
return;
var gameObject = (GameObject)obj;
// TODO: implement material drag & drop support for meshes
var component = gameObject.GetComponent<ChiselNode>();
if (!component)
return;
Editors.ChiselHierarchyWindowManager.OnHierarchyWindowItemGUI(instanceID, component, selectionRect);
}
finally { Profiler.EndSample(); }
}
private static void OnPlayModeStateChanged(PlayModeStateChange state)
{
ChiselNodeHierarchyManager.firstStart = false;
}
private static void OnUndoRedoPerformed()
{
ChiselNodeHierarchyManager.UpdateAllTransformations();
ChiselOutlineRenderer.Instance.OnTransformationChanged();
ChiselOutlineRenderer.OnUndoRedoPerformed();
}
static readonly HashSet<ChiselNode> modifiedNodes = new HashSet<ChiselNode>();
static readonly HashSet<Transform> processedTransforms = new HashSet<Transform>();
private static void OnWillFlushUndoRecord()
{
ChiselModelManager.OnWillFlushUndoRecord();
}
static readonly List<ChiselNode> s_ChildNodes = new List<ChiselNode>();
private static UnityEditor.UndoPropertyModification[] OnPostprocessModifications(UnityEditor.UndoPropertyModification[] modifications)
{
// Note: this is not always properly called
// - when? can't remember? maybe prefab related?
modifiedNodes.Clear();
processedTransforms.Clear();
for (int i = 0; i < modifications.Length; i++)
{
var currentValue = modifications[i].currentValue;
var transform = currentValue.target as Transform;
if (object.Equals(null, transform))
continue;
if (processedTransforms.Contains(transform))
continue;
var propertyPath = currentValue.propertyPath;
if (!propertyPath.StartsWith("m_Local"))
continue;
processedTransforms.Add(transform);
s_ChildNodes.Clear();
transform.GetComponentsInChildren<ChiselNode>(false, s_ChildNodes);
if (s_ChildNodes.Count == 0)
continue;
if (s_ChildNodes[0] is ChiselModel)
continue;
for (int n = 0; n < s_ChildNodes.Count; n++)
modifiedNodes.Add(s_ChildNodes[n]);
}
if (modifiedNodes.Count > 0)
{
ChiselNodeHierarchyManager.NotifyTransformationChanged(modifiedNodes);
}
return modifications;
}
}
} | 40.688474 | 189 | 0.634791 | [
"MIT"
] | cr4yz/Chisel.Prototype | Packages/com.chisel.editor/Chisel/Editor/Editor/ChiselUnityEventsManager.cs | 13,061 | C# |
using UnityEngine;
using UnityEngine;
using System.Collections;
namespace Shooter {
public class MapLoader : MonoBehaviour {
public string scenePath;
public void LoadMap() {
Loading.levelName = scenePath;
GlobalVars.currentMap = scenePath;
Application.LoadLevelAsync("Shooter/Scenes/loading");
}
}
} | 23.692308 | 55 | 0.779221 | [
"MIT"
] | hakur/shooter | Assets/Shooter/Scripts/Shooter/MapLoader.cs | 308 | C# |
namespace WsprInspector
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.tbCallsign = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.tbLocation = new System.Windows.Forms.TextBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.cbPower = new System.Windows.Forms.ComboBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.tbMessage = new System.Windows.Forms.TextBox();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.rtbLevels = new System.Windows.Forms.RichTextBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox4.SuspendLayout();
this.groupBox5.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.tbCallsign);
this.groupBox1.Location = new System.Drawing.Point(14, 14);
this.groupBox1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.groupBox1.Size = new System.Drawing.Size(107, 54);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Callsign";
//
// tbCallsign
//
this.tbCallsign.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbCallsign.Location = new System.Drawing.Point(7, 22);
this.tbCallsign.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.tbCallsign.Name = "tbCallsign";
this.tbCallsign.Size = new System.Drawing.Size(93, 23);
this.tbCallsign.TabIndex = 0;
this.tbCallsign.Text = "AJ4VD";
this.tbCallsign.TextChanged += new System.EventHandler(this.tbCallsign_TextChanged);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.tbLocation);
this.groupBox2.Location = new System.Drawing.Point(128, 14);
this.groupBox2.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.groupBox2.Size = new System.Drawing.Size(97, 54);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Location";
//
// tbLocation
//
this.tbLocation.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbLocation.Location = new System.Drawing.Point(7, 22);
this.tbLocation.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.tbLocation.Name = "tbLocation";
this.tbLocation.Size = new System.Drawing.Size(82, 23);
this.tbLocation.TabIndex = 0;
this.tbLocation.Text = "EL89";
this.tbLocation.TextChanged += new System.EventHandler(this.tbLocation_TextChanged);
//
// groupBox3
//
this.groupBox3.Controls.Add(this.cbPower);
this.groupBox3.Location = new System.Drawing.Point(232, 14);
this.groupBox3.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.groupBox3.Size = new System.Drawing.Size(99, 54);
this.groupBox3.TabIndex = 2;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Power (dB)";
//
// cbPower
//
this.cbPower.FormattingEnabled = true;
this.cbPower.Items.AddRange(new object[] {
"0",
"3",
"7",
"10",
"13",
"17",
"20",
"23",
"27",
"30",
"33",
"37",
"40",
"43",
"47",
"50",
"53",
"57",
"60"});
this.cbPower.Location = new System.Drawing.Point(7, 22);
this.cbPower.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.cbPower.Name = "cbPower";
this.cbPower.Size = new System.Drawing.Size(84, 23);
this.cbPower.TabIndex = 5;
this.cbPower.Text = "3";
this.cbPower.SelectedIndexChanged += new System.EventHandler(this.cbPower_SelectedIndexChanged);
//
// groupBox4
//
this.groupBox4.Controls.Add(this.tbMessage);
this.groupBox4.Location = new System.Drawing.Point(338, 14);
this.groupBox4.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.groupBox4.Size = new System.Drawing.Size(203, 54);
this.groupBox4.TabIndex = 1;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Message (hex)";
//
// tbMessage
//
this.tbMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbMessage.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.tbMessage.Location = new System.Drawing.Point(7, 22);
this.tbMessage.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.tbMessage.Name = "tbMessage";
this.tbMessage.ReadOnly = true;
this.tbMessage.Size = new System.Drawing.Size(188, 20);
this.tbMessage.TabIndex = 0;
this.tbMessage.Text = "F9 72 F2 8F BB 90 C0 ";
//
// groupBox5
//
this.groupBox5.Controls.Add(this.rtbLevels);
this.groupBox5.Location = new System.Drawing.Point(14, 75);
this.groupBox5.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.groupBox5.Size = new System.Drawing.Size(527, 128);
this.groupBox5.TabIndex = 3;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Transmission Packet";
//
// rtbLevels
//
this.rtbLevels.BackColor = System.Drawing.SystemColors.Control;
this.rtbLevels.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rtbLevels.Dock = System.Windows.Forms.DockStyle.Fill;
this.rtbLevels.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.rtbLevels.Location = new System.Drawing.Point(4, 19);
this.rtbLevels.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.rtbLevels.Name = "rtbLevels";
this.rtbLevels.ReadOnly = true;
this.rtbLevels.Size = new System.Drawing.Size(519, 106);
this.rtbLevels.TabIndex = 0;
this.rtbLevels.Text = resources.GetString("rtbLevels.Text");
//
// pictureBox1
//
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox1.BackColor = System.Drawing.Color.Navy;
this.pictureBox1.Location = new System.Drawing.Point(14, 207);
this.pictureBox1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(905, 208);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.pictureBox1.TabIndex = 4;
this.pictureBox1.TabStop = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(933, 428);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.groupBox5);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.Name = "Form1";
this.Text = "WSPR Inspector";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.groupBox5.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox tbCallsign;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.TextBox tbLocation;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.TextBox tbMessage;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.RichTextBox rtbLevels;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ComboBox cbPower;
}
}
| 47.621514 | 160 | 0.58797 | [
"MIT"
] | swharden/WsprSharp | src/WsprInspector/Form1.Designer.cs | 11,955 | C# |
using FluentNHibernate.Automapping;
using FluentNHibernate.Automapping.Alterations;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using HibernatingRhinos.Profiler.Appender.NHibernate;
using NHibernate.Cfg;
using NHibernate.Driver;
using NHibernate.SqlAzure.Tests.Entities;
using NHibernate.Tool.hbm2ddl;
namespace NHibernate.SqlAzure.Tests.Config
{
public class NHibernateConfiguration<T> where T : SqlClientDriver
{
private readonly string _connectionString;
private readonly IPersistenceConfigurer _databaseConfig;
public NHibernateConfiguration(string connectionString, IPersistenceConfigurer databaseConfig = null)
{
_connectionString = connectionString;
_databaseConfig = databaseConfig ?? MsSqlConfiguration.MsSql2008.ConnectionString(_connectionString).Driver<T>();
}
public ISessionFactory GetSessionFactory()
{
NHibernateProfiler.Initialize();
var config = Fluently.Configure()
.Database(_databaseConfig)
.Mappings(m => m.AutoMappings
.Add(AutoMap.AssemblyOf<NHibernateConfiguration<SqlClientDriver>>()
.Where(type => type.Namespace != null && type.Namespace.EndsWith("Entities"))
.UseOverridesFromAssemblyOf<NHibernateConfiguration<SqlClientDriver>>()
)
)
// Ensure batching is used
.ExposeConfiguration(c => c.SetProperty(Environment.BatchSize, "10"))
// Turn off cache to make sure all calls actually go to the database
.ExposeConfiguration(c => c.SetProperty(Environment.UseQueryCache, "false"))
.ExposeConfiguration(c => c.SetProperty(Environment.UseSecondLevelCache, "false"));
//if (typeof(LocalTestingReliableSql2008ClientDriver).IsAssignableFrom(typeof(T)))
// config.ExposeConfiguration(c => c.SetProperty(Environment.TransactionStrategy,
// typeof(ReliableAdoNetWithDistributedTransactionFactory).AssemblyQualifiedName));
var nhConfig = config.BuildConfiguration();
SchemaMetadataUpdater.QuoteTableAndColumns(nhConfig);
var validator = new SchemaValidator(nhConfig);
validator.Validate();
return config.BuildSessionFactory();
}
}
public class UserPropertyOverride : IAutoMappingOverride<UserProperty>
{
public void Override(AutoMapping<UserProperty> mapping)
{
mapping.CompositeId().KeyProperty(u => u.Name).KeyReference(u => u.User, "UserId");
}
}
public class UserOverride : IAutoMappingOverride<User>
{
public void Override(AutoMapping<User> mapping)
{
mapping.HasMany(u => u.Properties).KeyColumn("UserId").Cascade.All();
}
}
} | 41.657143 | 125 | 0.664266 | [
"MIT"
] | milestonetg/transient-fault-handling | test/MilestoneTG.NHibernate.TransientFaultHandling.SqlServer.Tests/Config/NHibernateConfiguration.cs | 2,918 | C# |
namespace PackSite.Library.Modeling.Specifications
{
using System;
using System.Linq.Expressions;
/// <summary>
/// Specification that can be satisfied by any object.
/// </summary>
/// <typeparam name="T">The type of the object to which the specification is applied.</typeparam>
public sealed class AnySpecification<T> : Specification<T>
{
/// <summary>
/// Instance.
/// </summary>
public static AnySpecification<T> Instance { get; } = new();
/// <inheritdoc/>
public override Expression<Func<T, bool>> Expression => x => true;
/// <summary>
/// Initializes an instance of <see cref="AnySpecification{T}"/>.
/// </summary>
private AnySpecification() : base()
{
}
}
}
| 27.793103 | 101 | 0.584367 | [
"MIT"
] | PackSite/Library.Modeling | src/PackSite.Library.Modeling.Specifications/AnySpecification.cs | 808 | C# |
using System;
namespace PS.IoC.Attributes
{
public abstract class DependencyRegisterAttribute : Attribute
{
}
} | 15.625 | 65 | 0.72 | [
"MIT"
] | BlackGad/PS.Framework | PS.IoC/Attributes/DependencyRegisterAttribute.cs | 127 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
namespace BackgroundTask
{
public sealed class PreInstalledTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
ToastHelper.PopToast("Pre-Install Task", "Pre install task is running", "OK");
}
}
}
| 24.111111 | 90 | 0.714286 | [
"MIT"
] | pradithya/UwpSamplePreInstalledApp | BackgroundTask/PreInstalledTask.cs | 436 | C# |
namespace CollectorHub.Data.Models.Common
{
using System;
using CollectorHub.Data.Common.Models;
public class Image : BaseDeletableModel<string>
{
public Image()
{
this.Id = Guid.NewGuid().ToString();
}
}
}
| 17.733333 | 51 | 0.590226 | [
"MIT"
] | itIsEazy/CollectorHub | Data/CollectorHub.Data.Models/Common/Image.cs | 268 | C# |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
{
public class UnsafeCode
{
private struct SimpleStruct
{
public int X;
public double Y;
}
static void Main()
{
// TODO: test behavior, or convert this into a pretty-test
// (but for now, it's already valuable knowing whether the decompiled code can be re-compiled)
}
public unsafe int MultipleExitsOutOfFixedBlock(int[] arr)
{
fixed (int* ptr = &arr[0]) {
if (*ptr < 0)
return *ptr;
if (*ptr == 21)
return 42;
if (*ptr == 42)
goto outside;
}
return 1;
outside:
Console.WriteLine("outside");
return 2;
}
public unsafe void FixMultipleStrings(string text)
{
fixed (char* ptr = text, userName = Environment.UserName, ptr2 = text) {
*ptr = 'c';
*userName = 'd';
*ptr2 = 'e';
}
}
public unsafe byte* PointerArithmetic2(long* p, int y, int x)
{
return (byte*)((short*)p + (y * x));
}
}
} | 31.462687 | 97 | 0.698767 | [
"MIT"
] | 164306530/ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Correctness/UnsafeCode.cs | 2,110 | C# |
using System;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace RegistroServizi.Areas.Identity.Pages.Account.Manage
{
public static class ManageNavPages
{
public static string Index => "Index";
public static string Email => "Email";
public static string ChangePassword => "ChangePassword";
public static string DownloadPersonalData => "DownloadPersonalData";
public static string DeletePersonalData => "DeletePersonalData";
public static string ExternalLogins => "ExternalLogins";
public static string PersonalData => "PersonalData";
public static string TwoFactorAuthentication => "TwoFactorAuthentication";
public static string IndexNavClass(ViewContext viewContext) => PageNavClass(viewContext, Index);
public static string EmailNavClass(ViewContext viewContext) => PageNavClass(viewContext, Email);
public static string ChangePasswordNavClass(ViewContext viewContext) => PageNavClass(viewContext, ChangePassword);
public static string DownloadPersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, DownloadPersonalData);
public static string DeletePersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, DeletePersonalData);
public static string ExternalLoginsNavClass(ViewContext viewContext) => PageNavClass(viewContext, ExternalLogins);
public static string PersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, PersonalData);
public static string TwoFactorAuthenticationNavClass(ViewContext viewContext) => PageNavClass(viewContext, TwoFactorAuthentication);
private static string PageNavClass(ViewContext viewContext, string page)
{
var activePage = viewContext.ViewData["ActivePage"] as string
?? System.IO.Path.GetFileNameWithoutExtension(viewContext.ActionDescriptor.DisplayName);
return string.Equals(activePage, page, StringComparison.OrdinalIgnoreCase) ? "active" : null;
}
}
}
| 43.25 | 140 | 0.748555 | [
"MIT"
] | AngeloDotNet/RegistroServizi | Areas/Identity/Pages/Account/Manage/ManageNavPages.cs | 2,076 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Windows;
namespace ICSharpCode.SharpSnippetCompiler
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
} | 43.709677 | 94 | 0.749077 | [
"MIT"
] | Darthseid/SharpDevelop | MainWindow.xaml.cs | 1,357 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
namespace CloudFoundryJwtAuthentication.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
[Authorize(Policy = "testgroup")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
| 21.765957 | 55 | 0.546432 | [
"Apache-2.0"
] | Aegaina/Samples | Security/src/AspDotNetCore/CloudFoundryJwtAuthentication/Controllers/ValuesController.cs | 1,025 | C# |
using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors.ValueConverters;
namespace MediaCopy.Extensions
{
public static class MediaExtensions
{
public static string GetUrl(this IMedia media, string propertyAlias = "umbracoFile") => media.GetMediaUrlWithTypeChecking(propertyAlias);
public static string GetMediaUrlWithTypeChecking(this IMedia media, string propertyAlias)
{
PropertyType propertyType = media.PropertyTypes.FirstOrDefault(x => x.Alias.InvariantEquals(propertyAlias));
if (propertyType == null) return string.Empty;
Property val = media.Properties[propertyType.Alias];
var jsonString = val?.Value as string;
if (jsonString == null) return string.Empty;
switch (propertyType.PropertyEditorAlias)
{
case Constants.PropertyEditors.ImageCropperAlias:
if (jsonString.DetectIsJson())
{
try
{
var json = JsonConvert.DeserializeObject<JObject>(jsonString);
if (json["src"] != null)
return json["src"].Value<string>();
}
catch (Exception ex)
{
LogHelper.Error<ImageCropperValueConverter>("Could not parse the string " + jsonString + " to a json object", ex);
return string.Empty;
}
}
else
return jsonString;
break;
case Constants.PropertyEditors.UploadFieldAlias:
return jsonString;
}
return string.Empty;
}
}
} | 38.72549 | 145 | 0.546329 | [
"MIT"
] | Jaywing/UmbracoMediaCopy | MediaCopy/Extensions/MediaExtensions.cs | 1,977 | C# |
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using CefSharp.Example;
using CefSharp.Wpf.Example.Mvvm;
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
namespace CefSharp.Wpf.Example.ViewModels
{
public class BrowserTabViewModel : INotifyPropertyChanged
{
private string address;
public string Address
{
get { return address; }
set { PropertyChanged.ChangeAndNotify(ref address, value, () => Address); }
}
private string addressEditable;
public string AddressEditable
{
get { return addressEditable; }
set { PropertyChanged.ChangeAndNotify(ref addressEditable, value, () => AddressEditable); }
}
private string outputMessage;
public string OutputMessage
{
get { return outputMessage; }
set { PropertyChanged.ChangeAndNotify(ref outputMessage, value, () => OutputMessage); }
}
private string statusMessage;
public string StatusMessage
{
get { return statusMessage; }
set { PropertyChanged.ChangeAndNotify(ref statusMessage, value, () => StatusMessage); }
}
private string title;
public string Title
{
get { return title; }
set { PropertyChanged.ChangeAndNotify(ref title, value, () => Title); }
}
private IWpfWebBrowser webBrowser;
public IWpfWebBrowser WebBrowser
{
get { return webBrowser; }
set { PropertyChanged.ChangeAndNotify(ref webBrowser, value, () => WebBrowser); }
}
private object evaluateJavaScriptResult;
public object EvaluateJavaScriptResult
{
get { return evaluateJavaScriptResult; }
set { PropertyChanged.ChangeAndNotify(ref evaluateJavaScriptResult, value, () => EvaluateJavaScriptResult); }
}
private bool showSidebar;
public bool ShowSidebar
{
get { return showSidebar; }
set { PropertyChanged.ChangeAndNotify(ref showSidebar, value, () => ShowSidebar); }
}
public ICommand GoCommand { get; set; }
public ICommand HomeCommand { get; set; }
public ICommand ExecuteJavaScriptCommand { get; set; }
public ICommand EvaluateJavaScriptCommand { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public BrowserTabViewModel(string address)
{
Address = address;
AddressEditable = Address;
GoCommand = new DelegateCommand(Go, () => !String.IsNullOrWhiteSpace(Address));
HomeCommand = new DelegateCommand(() => AddressEditable = Address = CefExample.DefaultUrl);
ExecuteJavaScriptCommand = new DelegateCommand<string>(ExecuteJavaScript, s => !String.IsNullOrWhiteSpace(s));
EvaluateJavaScriptCommand = new DelegateCommand<string>(EvaluateJavaScript, s => !String.IsNullOrWhiteSpace(s));
PropertyChanged += OnPropertyChanged;
var version = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);
OutputMessage = version;
}
private void EvaluateJavaScript(string s)
{
try
{
EvaluateJavaScriptResult = webBrowser.EvaluateScript(s) ?? "null";
}
catch (Exception e)
{
MessageBox.Show("Error while evaluating Javascript: " + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void ExecuteJavaScript(string s)
{
try
{
webBrowser.ExecuteScriptAsync(s);
}
catch (Exception e)
{
MessageBox.Show("Error while executing Javascript: " + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "Address":
AddressEditable = Address;
break;
case "WebBrowser":
if (WebBrowser != null)
{
WebBrowser.ConsoleMessage += OnWebBrowserConsoleMessage;
WebBrowser.StatusMessage += OnWebBrowserStatusMessage;
WebBrowser.LoadError += OnWebBrowserLoadError;
// TODO: This is a bit of a hack. It would be nicer/cleaner to give the webBrowser focus in the Go()
// TODO: method, but it seems like "something" gets messed up (= doesn't work correctly) if we give it
// TODO: focus "too early" in the loading process...
WebBrowser.FrameLoadEnd += delegate { Application.Current.Dispatcher.BeginInvoke((Action)(() => webBrowser.Focus())); };
}
break;
}
}
private void OnWebBrowserConsoleMessage(object sender, ConsoleMessageEventArgs e)
{
OutputMessage = e.Message;
}
private void OnWebBrowserStatusMessage(object sender, StatusMessageEventArgs e)
{
StatusMessage = e.Value;
}
private void OnWebBrowserLoadError(object sender, LoadErrorEventArgs args)
{
// Don't display an error for downloaded files where the user aborted the download.
if (args.ErrorCode == CefErrorCode.Aborted)
return;
var errorMessage = "<html><body><h2>Failed to load URL " + args.FailedUrl +
" with error " + args.ErrorText + " (" + args.ErrorCode +
").</h2></body></html>";
webBrowser.LoadHtml(errorMessage, args.FailedUrl);
}
private void Go()
{
Address = AddressEditable;
// Part of the Focus hack further described in the OnPropertyChanged() method...
Keyboard.ClearFocus();
}
}
}
| 36.056497 | 144 | 0.58571 | [
"BSD-3-Clause"
] | git-thinh/CefSharp-33.0.2 | CefSharp.Wpf.Example/ViewModels/BrowserTabViewModel.cs | 6,385 | C# |
namespace gpro_desktop_windows
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.metroPanelMF = new MetroFramework.Controls.MetroPanel();
this.metroPanel2 = new MetroFramework.Controls.MetroPanel();
this.metroLabelRole = new MetroFramework.Controls.MetroLabel();
this.metroPanel1 = new MetroFramework.Controls.MetroPanel();
this.metroLabelUsername = new MetroFramework.Controls.MetroLabel();
this.mlBack = new MetroFramework.Controls.MetroLink();
this.metroPanel3 = new MetroFramework.Controls.MetroPanel();
this.btnSalirGpro = new MetroFramework.Controls.MetroButton();
this.btnCerrarSesion = new MetroFramework.Controls.MetroButton();
this.metroPanel2.SuspendLayout();
this.metroPanel1.SuspendLayout();
this.metroPanel3.SuspendLayout();
this.SuspendLayout();
//
// metroPanelMF
//
this.metroPanelMF.Dock = System.Windows.Forms.DockStyle.Fill;
this.metroPanelMF.HorizontalScrollbarBarColor = true;
this.metroPanelMF.HorizontalScrollbarHighlightOnWheel = false;
this.metroPanelMF.HorizontalScrollbarSize = 10;
this.metroPanelMF.Location = new System.Drawing.Point(20, 60);
this.metroPanelMF.Name = "metroPanelMF";
this.metroPanelMF.Size = new System.Drawing.Size(984, 520);
this.metroPanelMF.TabIndex = 0;
this.metroPanelMF.VerticalScrollbarBarColor = true;
this.metroPanelMF.VerticalScrollbarHighlightOnWheel = false;
this.metroPanelMF.VerticalScrollbarSize = 10;
//
// metroPanel2
//
this.metroPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.metroPanel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(174)))), ((int)(((byte)(219)))));
this.metroPanel2.Controls.Add(this.metroLabelRole);
this.metroPanel2.HorizontalScrollbarBarColor = true;
this.metroPanel2.HorizontalScrollbarHighlightOnWheel = false;
this.metroPanel2.HorizontalScrollbarSize = 10;
this.metroPanel2.Location = new System.Drawing.Point(31, 74);
this.metroPanel2.Name = "metroPanel2";
this.metroPanel2.Size = new System.Drawing.Size(177, 48);
this.metroPanel2.TabIndex = 2;
this.metroPanel2.UseCustomBackColor = true;
this.metroPanel2.VerticalScrollbarBarColor = true;
this.metroPanel2.VerticalScrollbarHighlightOnWheel = false;
this.metroPanel2.VerticalScrollbarSize = 10;
//
// metroLabelRole
//
this.metroLabelRole.AutoSize = true;
this.metroLabelRole.BackColor = System.Drawing.Color.Transparent;
this.metroLabelRole.ForeColor = System.Drawing.Color.White;
this.metroLabelRole.Location = new System.Drawing.Point(8, 21);
this.metroLabelRole.Name = "metroLabelRole";
this.metroLabelRole.Size = new System.Drawing.Size(62, 19);
this.metroLabelRole.TabIndex = 2;
this.metroLabelRole.Text = "role: role";
this.metroLabelRole.UseCustomBackColor = true;
this.metroLabelRole.UseCustomForeColor = true;
//
// metroPanel1
//
this.metroPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.metroPanel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(174)))), ((int)(((byte)(219)))));
this.metroPanel1.Controls.Add(this.metroLabelUsername);
this.metroPanel1.HorizontalScrollbarBarColor = true;
this.metroPanel1.HorizontalScrollbarHighlightOnWheel = false;
this.metroPanel1.HorizontalScrollbarSize = 10;
this.metroPanel1.Location = new System.Drawing.Point(31, 20);
this.metroPanel1.Name = "metroPanel1";
this.metroPanel1.Size = new System.Drawing.Size(177, 48);
this.metroPanel1.TabIndex = 2;
this.metroPanel1.UseCustomBackColor = true;
this.metroPanel1.VerticalScrollbarBarColor = true;
this.metroPanel1.VerticalScrollbarHighlightOnWheel = false;
this.metroPanel1.VerticalScrollbarSize = 10;
//
// metroLabelUsername
//
this.metroLabelUsername.AutoSize = true;
this.metroLabelUsername.BackColor = System.Drawing.Color.Transparent;
this.metroLabelUsername.ForeColor = System.Drawing.Color.White;
this.metroLabelUsername.Location = new System.Drawing.Point(8, 21);
this.metroLabelUsername.Name = "metroLabelUsername";
this.metroLabelUsername.Size = new System.Drawing.Size(98, 19);
this.metroLabelUsername.TabIndex = 2;
this.metroLabelUsername.Text = "user: username";
this.metroLabelUsername.UseCustomBackColor = true;
this.metroLabelUsername.UseCustomForeColor = true;
//
// mlBack
//
this.mlBack.Cursor = System.Windows.Forms.Cursors.Default;
this.mlBack.Image = ((System.Drawing.Image)(resources.GetObject("mlBack.Image")));
this.mlBack.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.mlBack.Location = new System.Drawing.Point(119, 24);
this.mlBack.Name = "mlBack";
this.mlBack.Size = new System.Drawing.Size(91, 27);
this.mlBack.TabIndex = 1;
this.mlBack.Text = " Volver";
this.mlBack.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.mlBack.UseSelectable = true;
this.mlBack.Click += new System.EventHandler(this.mlBack_Click);
//
// metroPanel3
//
this.metroPanel3.Controls.Add(this.btnCerrarSesion);
this.metroPanel3.Controls.Add(this.btnSalirGpro);
this.metroPanel3.Controls.Add(this.metroPanel1);
this.metroPanel3.Controls.Add(this.metroPanel2);
this.metroPanel3.Dock = System.Windows.Forms.DockStyle.Right;
this.metroPanel3.HorizontalScrollbarBarColor = true;
this.metroPanel3.HorizontalScrollbarHighlightOnWheel = false;
this.metroPanel3.HorizontalScrollbarSize = 10;
this.metroPanel3.Location = new System.Drawing.Point(780, 60);
this.metroPanel3.Name = "metroPanel3";
this.metroPanel3.Size = new System.Drawing.Size(224, 520);
this.metroPanel3.TabIndex = 2;
this.metroPanel3.VerticalScrollbarBarColor = true;
this.metroPanel3.VerticalScrollbarHighlightOnWheel = false;
this.metroPanel3.VerticalScrollbarSize = 10;
//
// btnSalirGpro
//
this.btnSalirGpro.Cursor = System.Windows.Forms.Cursors.Default;
this.btnSalirGpro.Location = new System.Drawing.Point(31, 138);
this.btnSalirGpro.Name = "btnSalirGpro";
this.btnSalirGpro.Size = new System.Drawing.Size(177, 30);
this.btnSalirGpro.TabIndex = 4;
this.btnSalirGpro.Text = "Salir";
this.btnSalirGpro.UseSelectable = true;
this.btnSalirGpro.UseStyleColors = true;
this.btnSalirGpro.Click += new System.EventHandler(this.btnSalirGpro_Click);
//
// btnCerrarSesion
//
this.btnCerrarSesion.Cursor = System.Windows.Forms.Cursors.Default;
this.btnCerrarSesion.Location = new System.Drawing.Point(31, 183);
this.btnCerrarSesion.Name = "btnCerrarSesion";
this.btnCerrarSesion.Size = new System.Drawing.Size(177, 30);
this.btnCerrarSesion.TabIndex = 5;
this.btnCerrarSesion.Text = "Cerrar Sesión";
this.btnCerrarSesion.UseSelectable = true;
this.btnCerrarSesion.UseStyleColors = true;
this.btnCerrarSesion.Click += new System.EventHandler(this.btnCerrarSesion_Click);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1024, 600);
this.Controls.Add(this.metroPanel3);
this.Controls.Add(this.mlBack);
this.Controls.Add(this.metroPanelMF);
this.Name = "MainForm";
this.ShadowType = MetroFramework.Forms.MetroFormShadowType.None;
this.Text = "GPRO";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
this.Load += new System.EventHandler(this.MainForm_Load);
this.metroPanel2.ResumeLayout(false);
this.metroPanel2.PerformLayout();
this.metroPanel1.ResumeLayout(false);
this.metroPanel1.PerformLayout();
this.metroPanel3.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private MetroFramework.Controls.MetroPanel metroPanelMF;
private MetroFramework.Controls.MetroPanel metroPanel1;
private MetroFramework.Controls.MetroLabel metroLabelUsername;
private MetroFramework.Controls.MetroPanel metroPanel2;
private MetroFramework.Controls.MetroLabel metroLabelRole;
private MetroFramework.Controls.MetroLink mlBack;
private MetroFramework.Controls.MetroPanel metroPanel3;
private MetroFramework.Controls.MetroButton btnSalirGpro;
private MetroFramework.Controls.MetroButton btnCerrarSesion;
}
} | 47.461905 | 153 | 0.708538 | [
"MIT"
] | dardonosti/gpro-desktop-windows | gpro-desktop-windows/MainForm.Designer.cs | 9,970 | C# |
using System.Collections.Generic;
using System.Globalization;
using Abp.Configuration.Startup;
using Abp.Dependency;
namespace Abp.Localization.Sources
{
/// <summary>
/// Null object pattern for <see cref="ILocalizationSource"/>.
/// </summary>
internal class NullLocalizationSource : ILocalizationSource
{
/// <summary>
/// Singleton instance.
/// </summary>
public static NullLocalizationSource Instance { get; } = new NullLocalizationSource();
public string Name { get { return null; } }
private readonly IReadOnlyList<LocalizedString> _emptyStringArray = new LocalizedString[0];
private NullLocalizationSource()
{
}
public void Initialize(ILocalizationConfiguration configuration, IIocResolver iocResolver)
{
}
public string GetString(string name)
{
return name;
}
public string GetString(string name, CultureInfo culture)
{
return name;
}
public string GetStringOrNull(string name, bool tryDefaults = true)
{
return null;
}
public string GetStringOrNull(string name, CultureInfo culture, bool tryDefaults = true)
{
return null;
}
public List<string> GetStrings(List<string> names)
{
return names;
}
public List<string> GetStrings(List<string> names, CultureInfo culture)
{
return names;
}
public List<string> GetStringsOrNull(List<string> names, bool tryDefaults = true)
{
return null;
}
public List<string> GetStringsOrNull(List<string> names, CultureInfo culture, bool tryDefaults = true)
{
return null;
}
public IReadOnlyList<LocalizedString> GetAllStrings(bool includeDefaults = true)
{
return _emptyStringArray;
}
public IReadOnlyList<LocalizedString> GetAllStrings(CultureInfo culture, bool includeDefaults = true)
{
return _emptyStringArray;
}
}
}
| 26 | 110 | 0.607044 | [
"MIT"
] | 861191244/aspnetboilerplate | src/Abp/Localization/Sources/NullLocalizationSource.cs | 2,158 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using db.models;
using Mapster;
namespace SS.Db.models.auth
{
[AdaptTo("[name]Dto")]
public class Permission : BaseEntity
{
public const string Login = nameof(Login);
public const string ViewOwnProfile = nameof(ViewOwnProfile);
public const string ViewProfilesInOwnLocation = nameof(ViewProfilesInOwnLocation);
public const string ViewProfilesInAllLocation = nameof(ViewProfilesInAllLocation);
public const string CreateUsers = nameof(CreateUsers);
public const string ExpireUsers = nameof(ExpireUsers);
public const string EditUsers = nameof(EditUsers);
public const string ViewRoles = nameof(ViewRoles);
public const string CreateAndAssignRoles = nameof(CreateAndAssignRoles);
public const string ExpireRoles = nameof(ExpireRoles);
public const string EditRoles = nameof(EditRoles);
public const string ViewManageTypes = nameof(ViewManageTypes);
public const string CreateTypes = nameof(CreateTypes);
public const string EditTypes = nameof(EditTypes);
public const string ExpireTypes = nameof(ExpireTypes);
public const string ViewMyShifts = nameof(ViewMyShifts);
public const string ViewAllShiftsAtMyLocation = nameof(ViewAllShiftsAtMyLocation);
public const string ViewAllShifts = nameof(ViewAllShifts);
public const string CreateAndAssignShifts = nameof(CreateAndAssignShifts);
public const string ExpireShifts = nameof(ExpireShifts);
public const string EditShifts = nameof(EditShifts);
public const string ImportShifts = nameof(ImportShifts);
public const string ViewDistributeSchedule = nameof(ViewDistributeSchedule);
public const string ViewHomeLocation = nameof(ViewHomeLocation);
public const string ViewAssignedLocation = nameof(ViewAssignedLocation);
public const string ViewRegion = nameof(ViewRegion);
public const string ViewProvince = nameof(ViewProvince);
public const string ExpireLocation = nameof(ExpireLocation);
public const string ViewAssignments = nameof(ViewAssignments);
public const string CreateAssignments = nameof(CreateAssignments);
public const string EditAssignments = nameof(EditAssignments);
public const string ExpireAssignments = nameof(ExpireAssignments);
public const string ViewDuties = nameof(ViewDuties);
public const string CreateAndAssignDuties = nameof(CreateAndAssignDuties);
public const string EditDuties = nameof(EditDuties);
public const string ExpireDuties = nameof(ExpireDuties);
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
| 51.482143 | 90 | 0.727714 | [
"Apache-2.0"
] | seeker25/sheriff-scheduling | db/models/auth/Permission.cs | 2,885 | 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.Globalization;
using Xunit;
namespace System.ComponentModel.Tests
{
public class UInt64ConverterTests : ConverterTestBase
{
private static TypeConverter s_converter = new UInt64Converter();
[Fact]
public static void ConvertFrom_WithContext()
{
ConvertFrom_WithContext(new object[3, 3]
{
{ "1 ", (ulong)1, null },
{ "#2", (ulong)2, null },
{ "+7", (ulong)7, CultureInfo.InvariantCulture }
},
UInt64ConverterTests.s_converter);
}
[Fact]
public static void ConvertFrom_WithContext_Negative()
{
AssertExtensions.Throws<ArgumentException, Exception>(
() => UInt64ConverterTests.s_converter.ConvertFrom(TypeConverterTests.s_context, null, "-8"));
}
[Fact]
public static void ConvertTo_WithContext()
{
ConvertTo_WithContext(new object[3, 3]
{
{ (ulong)1, "1", null },
{ (ulong)2, (ulong)2, CultureInfo.InvariantCulture },
{ (ulong)3, (float)3.0, null }
},
UInt64ConverterTests.s_converter);
}
}
}
| 32.521739 | 110 | 0.558824 | [
"MIT"
] | 2E0PGS/corefx | src/System.ComponentModel.TypeConverter/tests/UInt64ConverterTests.cs | 1,496 | C# |
using System.Threading.Tasks;
using NorthLion.Zero.Web.Controllers;
using System.Web.Mvc;
using NorthLion.Zero.MultiTenancy;
namespace NorthLion.Zero.Web.Areas.AdminMpa.Controllers
{
public class TenantsController : ZeroControllerBase
{
private readonly ITenantAppService _tenantAppService;
public TenantsController(ITenantAppService tenantAppService)
{
_tenantAppService = tenantAppService;
}
// GET: AdminMpa/Tenants
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> SetEdition(int id)
{
var editions = await _tenantAppService.GetEditionsForTenant(id);
return View(editions);
}
public async Task<ActionResult> SetFeatures(int id)
{
var features = await _tenantAppService.GetFeaturesForTenant(id);
return View(features);
}
public ActionResult EditTenant(int id)
{
return View();
}
}
} | 26.974359 | 76 | 0.629278 | [
"MIT"
] | CodefyMX/NorthLionAbpZero | NorthLion.Zero.Web/Areas/AdminMpa/Controllers/TenantsController.cs | 1,054 | C# |
using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;
public class AudioClipPlayer : MonoBehaviour, IMixedRealityPointerHandler, IMixedRealityFocusHandler
{
[SerializeField] private AudioId onFocus;
[SerializeField] private AudioId onClick;
private IAudioService audioService;
void Awake()
{
audioService = MixedRealityToolkit.Instance.GetService<IAudioService>();
audioService = MixedRealityToolkit.Instance.GetService<IAudioService>();
}
#region IMixedRealityPointerHandlerFunctions
public void OnPointerUp(MixedRealityPointerEventData eventData)
{
}
public void OnPointerDown(MixedRealityPointerEventData eventData)
{
audioService.PlayClip(onClick);
}
public void OnPointerClicked(MixedRealityPointerEventData eventData)
{
}
#endregion
#region IMixedRealityFocusHandlerFunctions
public void OnBeforeFocusChange(FocusEventData eventData)
{
}
public void OnFocusChanged(FocusEventData eventData)
{
}
public void OnFocusEnter(FocusEventData eventData)
{
audioService.PlayClip(onFocus);
}
public void OnFocusExit(FocusEventData eventData)
{
}
#endregion
}
| 24.480769 | 100 | 0.735271 | [
"MIT"
] | Bhaskers-Blu-Org2/GalaxyExplorer | Assets/scripts/AudioService/AudioClipPlayer.cs | 1,275 | C# |
using DomainModels;
using ViewModels;
namespace Mappers
{
public static class OrderItemMapper
{
public static OrderItemViewModel ToViewModel(this OrderItem orderItem)
{
return new OrderItemViewModel
{
Id = orderItem.Id,
Quantity = orderItem.Quantity,
OrderId = orderItem.OrderId,
PizzaSize = orderItem.PizzaSize == null ? new PizzaSizeViewModel() : orderItem.PizzaSize.ToViewModel()
};
}
}
}
| 25.285714 | 118 | 0.587571 | [
"MIT"
] | sedc-codecademy/skwd8-08-aspnetmvc | g5/PizzaApp - Architecture/PizzaApp/Mappers/OrderItemMapper.cs | 533 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AspnetWebApi2Helpers.Serialization.Tests.Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AspnetWebApi2Helpers.Serialization.Tests.Common")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("de59dd40-c5e2-432f-9a27-8a6a72bd3860")]
// 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")]
| 39.648649 | 84 | 0.753238 | [
"MIT"
] | tonysneed/aspnet-webapi-2-contrib | test/AspnetWebApi2Helpers.Serialization.Tests.Common/Properties/AssemblyInfo.cs | 1,470 | C# |
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using TCG.BusinessRules;
using TCG.Models;
namespace TCG.Identity.Controllers
{
[Route("api/owner")]
[ApiController]
public class OwnerController : ControllerBase
{
[HttpGet]
public IActionResult GetAllOwners()
{
try
{
var owners= new OwnerRules().GetAll();
return Ok(owners);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
[HttpGet("{id}", Name = "OwnerById")]
public IActionResult GetOwnerById(Guid id)
{
try
{
var owner = new OwnerRules().GetById(id);
if (owner == null)
{
return NotFound();
}
else
{
return Ok(owner);
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
[HttpGet("{id}/account")]
public IActionResult GetOwnerWithDetails(Guid id)
{
try
{
var owner = new OwnerRules().GetOwnerWithDetails(id);
if (owner == null)
{
return NotFound();
}
else
{
return Ok(owner);
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
[HttpPost]
public IActionResult CreateOwner([FromBody] Owner owner)
{
try
{
if (owner == null)
{
return BadRequest("Owner object is null");
}
if (!ModelState.IsValid)
{
return BadRequest("Invalid model object");
}
new OwnerRules().CreateOwner(owner);
//return CreatedAtRoute("OwnerById", new { id = owner.Id }, owner);
return Ok();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
[HttpPut]
public IActionResult UpdateOwner([FromBody] Owner owner)
{
try
{
if (owner == null)
{
return BadRequest("Owner object is null");
}
if (!ModelState.IsValid)
{
return BadRequest("Invalid model object");
}
new OwnerRules().UpdateOwner(owner);
return Ok();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
[HttpDelete("{id}")]
public IActionResult DeleteOwner(Guid id)
{
try
{
var owner = new OwnerRules().GetById(id);
if (owner ==null)
{
return NotFound();
}
if (owner.Accounts.Any())
{
return BadRequest("Cannot delete owner. It has related accounts. Delete those accounts first.");
}
new OwnerRules().DeleteOwner(owner);
return Ok();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
}
}
| 24.826923 | 116 | 0.412084 | [
"MIT"
] | qanle/TCGPrimus | TCGPrimusServer/TCG.Identity/Controllers/OwnerController.cs | 3,875 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Text.Json;
using JetBrains.Annotations;
namespace BigBuffers.JsonParsing
{
[PublicAPI]
internal sealed class JsonEnumVectorParser<TModel, TEnum> : IJsonVectorParser<TEnum>
where TModel : struct, IBigBufferEntity
where TEnum : System.Enum
{
private readonly JsonParser<TModel> _model;
private Placeholder _placeholder;
public JsonEnumVectorParser(JsonParser<TModel> model, Placeholder placeholder)
{
_model = model;
_placeholder = placeholder;
}
public void Parse(JsonElement element)
=> Runtime.Assert(_model.DeferredActions.TryAdd(
() => {
var items = new TEnum[element.GetArrayLength()];
var i = -1;
foreach (var item in element.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.String)
{
items[++i] = (TEnum)Enum.Parse(typeof(TEnum), item.GetString()!);
}
else if (item.ValueKind == JsonValueKind.Number)
{
var v = item.GetDouble();
if (v < 0)
{
var sv = (long)v;
items[++i] = Unsafe.As<long, TEnum>(ref sv);
}
else
{
var uv = (ulong)v;
items[++i] = Unsafe.As<ulong, TEnum>(ref uv);
}
}
else throw new NotImplementedException();
}
_placeholder.Fill(items);
}));
}
}
| 28 | 86 | 0.551948 | [
"Apache-2.0"
] | StirlingLabs/BigBuffers | net/BigBuffers.JsonParsing/JsonEnumVectorParser.cs | 1,540 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.AppService.Fluent
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AppServiceCertificateOrdersOperations operations.
/// </summary>
public partial interface IAppServiceCertificateOrdersOperations
{
/// <summary>
/// List all certificate orders in a subscription.
/// </summary>
/// <remarks>
/// Description for List all certificate orders in a subscription.
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AppServiceCertificateOrderInner>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Validate information for a certificate order.
/// </summary>
/// <remarks>
/// Description for Validate information for a certificate order.
/// </remarks>
/// <param name='appServiceCertificateOrder'>
/// Information for a certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> ValidatePurchaseInformationWithHttpMessagesAsync(AppServiceCertificateOrderInner appServiceCertificateOrder, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get certificate orders in a resource group.
/// </summary>
/// <remarks>
/// Description for Get certificate orders in a resource group.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AppServiceCertificateOrderInner>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a certificate order.
/// </summary>
/// <remarks>
/// Description for Get a certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order..
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AppServiceCertificateOrderInner>> GetWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Description for Create or update a certificate purchase order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to use for the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AppServiceCertificateOrderInner>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, AppServiceCertificateOrderInner certificateDistinguishedName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete an existing certificate order.
/// </summary>
/// <remarks>
/// Description for Delete an existing certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Description for Create or update a certificate purchase order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to use for the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AppServiceCertificateOrderInner>> UpdateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, AppServiceCertificateOrderPatchResource certificateDistinguishedName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all certificates associated with a certificate order.
/// </summary>
/// <remarks>
/// Description for List all certificates associated with a certificate
/// order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AppServiceCertificateResourceInner>>> ListCertificatesWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the certificate associated with a certificate order.
/// </summary>
/// <remarks>
/// Description for Get the certificate associated with a certificate
/// order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AppServiceCertificateResourceInner>> GetCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </summary>
/// <remarks>
/// Description for Creates or updates a certificate and associates
/// with key vault secret.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AppServiceCertificateResourceInner>> CreateOrUpdateCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, AppServiceCertificateResourceInner keyVaultCertificate, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete the certificate associated with a certificate order.
/// </summary>
/// <remarks>
/// Description for Delete the certificate associated with a
/// certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </summary>
/// <remarks>
/// Description for Creates or updates a certificate and associates
/// with key vault secret.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AppServiceCertificateResourceInner>> UpdateCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, AppServiceCertificatePatchResource keyVaultCertificate, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Reissue an existing certificate order.
/// </summary>
/// <remarks>
/// Description for Reissue an existing certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='reissueCertificateOrderRequest'>
/// Parameters for the reissue.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> ReissueWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, ReissueCertificateOrderRequest reissueCertificateOrderRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Renew an existing certificate order.
/// </summary>
/// <remarks>
/// Description for Renew an existing certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='renewCertificateOrderRequest'>
/// Renew parameters
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> RenewWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, RenewCertificateOrderRequest renewCertificateOrderRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Resend certificate email.
/// </summary>
/// <remarks>
/// Description for Resend certificate email.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> ResendEmailWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Description for Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the object.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> ResendRequestEmailsWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Description for Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='siteSealRequest'>
/// Site seal request.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SiteSealInner>> RetrieveSiteSealWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, SiteSealRequest siteSealRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Description for Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> VerifyDomainOwnershipWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve the list of certificate actions.
/// </summary>
/// <remarks>
/// Description for Retrieve the list of certificate actions.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IList<CertificateOrderActionInner>>> RetrieveCertificateActionsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve email history.
/// </summary>
/// <remarks>
/// Description for Retrieve email history.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IList<CertificateEmailInner>>> RetrieveCertificateEmailHistoryWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Description for Create or update a certificate purchase order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to use for the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AppServiceCertificateOrderInner>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, AppServiceCertificateOrderInner certificateDistinguishedName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </summary>
/// <remarks>
/// Description for Creates or updates a certificate and associates
/// with key vault secret.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AppServiceCertificateResourceInner>> BeginCreateOrUpdateCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, AppServiceCertificateResourceInner keyVaultCertificate, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all certificate orders in a subscription.
/// </summary>
/// <remarks>
/// Description for List all certificate orders in a subscription.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AppServiceCertificateOrderInner>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get certificate orders in a resource group.
/// </summary>
/// <remarks>
/// Description for Get certificate orders in a resource group.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AppServiceCertificateOrderInner>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all certificates associated with a certificate order.
/// </summary>
/// <remarks>
/// Description for List all certificates associated with a certificate
/// order.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DefaultErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AppServiceCertificateResourceInner>>> ListCertificatesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 49.389946 | 370 | 0.626585 | [
"MIT"
] | Azure/azure-libraries-for-net | src/ResourceManagement/AppService/Generated/IAppServiceCertificateOrdersOperations.cs | 36,351 | 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.Sql;
using System.Data.SqlClient;
using System.Xml;
using System.Data;
using System.Web.Configuration;
using System.Configuration;
namespace PatanHospital
{
public partial class DeleteDoctor : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Table2.Visible = false;
Label1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Table2.Visible = true;
Fill_Data();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Text = "There is no data in the database";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("AdminHome.aspx");
}
protected void Button4_Click(object sender, EventArgs e)
{
Response.Redirect("AdminHome.aspx");
}
public void Fill_Data()
{
Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/HospitalServer");
ConnectionStringSettings connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["HospitalServerConnectionString"];
SqlConnection sqlConnection = new SqlConnection(connectionString.ToString());
sqlConnection.Open();
string Query = "Select Fname+' '+Lname as Name, SSN, Phone, email from Doctorcrediantials where SSN ='" + this.DropDownList1.SelectedValue + "'; ";
SqlCommand cmd = new SqlCommand(Query, sqlConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Doctorcrediantials");
sqlConnection.Close();
TextBox1.Text = ds.Tables["Doctorcrediantials"].Rows[0]["Name"].ToString();
TextBox2.Text = ds.Tables["Doctorcrediantials"].Rows[0]["SSN"].ToString();
TextBox3.Text = ds.Tables["Doctorcrediantials"].Rows[0]["Phone"].ToString();
TextBox4.Text = ds.Tables["Doctorcrediantials"].Rows[0]["email"].ToString();
}
public void Delete_Doctor_Data()
{
Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/HospitalServer");
ConnectionStringSettings connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["HospitalServerConnectionString"];
SqlConnection sqlConnection = new SqlConnection(connectionString.ToString());
sqlConnection.Open();
string Query = "Delete from DoctorCrediantials where SSN ='" + this.DropDownList1.SelectedValue + "'; ";
SqlCommand cmd = new SqlCommand(Query, sqlConnection);
cmd.ExecuteNonQuery();
sqlConnection.Close();
DropDownList1.Items.Remove(DropDownList1.SelectedItem);
}
public void Clear_TextBox()
{
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
}
protected void Button3_Click(object sender, EventArgs e)
{
Delete_Doctor_Data();
Clear_TextBox();
}
}
} | 35.505051 | 159 | 0.613371 | [
"Apache-2.0"
] | richa615/PatanHospital | PatanHospital/Backup/DeleteDoctor.aspx.cs | 3,517 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SageMaker.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SageMaker.Model.Internal.MarshallTransformations
{
/// <summary>
/// ModelQuality Marshaller
/// </summary>
public class ModelQualityMarshaller : IRequestMarshaller<ModelQuality, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(ModelQuality requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetConstraints())
{
context.Writer.WritePropertyName("Constraints");
context.Writer.WriteObjectStart();
var marshaller = MetricsSourceMarshaller.Instance;
marshaller.Marshall(requestObject.Constraints, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetStatistics())
{
context.Writer.WritePropertyName("Statistics");
context.Writer.WriteObjectStart();
var marshaller = MetricsSourceMarshaller.Instance;
marshaller.Marshall(requestObject.Statistics, context);
context.Writer.WriteObjectEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static ModelQualityMarshaller Instance = new ModelQualityMarshaller();
}
} | 33.076923 | 107 | 0.663953 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/SageMaker/Generated/Model/Internal/MarshallTransformations/ModelQualityMarshaller.cs | 2,580 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Threading;
namespace Shapp.Communications.Protocol {
[Serializable]
public class HelloFromParent : ISystemMessage {
public delegate void Callback(Socket client, HelloFromParent helloFromChild);
public static event Callback OnReceive;
public void Dispatch(Socket sender) {
Shapp.C.log.Info("HelloFromParent received");
//Thread.Sleep(1000);
OnReceive?.Invoke(sender, this);
}
}
}
| 29.333333 | 85 | 0.699675 | [
"MIT"
] | saleph/shapp | Shapp/Communications/Protocol/HelloFromParent.cs | 618 | C# |
namespace NetCoreStack.Contracts
{
public class ColumnOrder
{
public int Column { get; set; }
public string Dir { get; set; }
}
}
| 17.666667 | 39 | 0.591195 | [
"Apache-2.0"
] | NetCoreStack/Contracts | src/NetCoreStack.Contracts/Types/ColumnOrder.cs | 161 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Pchp.Core
{
#region SetOperations
/// <summary>
/// Implemented operations.
/// </summary>
public enum SetOperations
{
Difference,
Intersection
}
#endregion
#region IntStringKey
/// <summary>
/// Represents both integer or string array key.
/// </summary>
[DebuggerNonUserCode]
public struct IntStringKey : IEquatable<IntStringKey>, IComparable<IntStringKey>
{
/// <summary>
/// <pre>new IntStringKey( "" )</pre>
/// </summary>
internal readonly static IntStringKey EmptyStringKey = new IntStringKey(string.Empty);
[DebuggerNonUserCode]
public class EqualityComparer : IEqualityComparer<IntStringKey>
{
public static readonly EqualityComparer/*!*/ Default = new EqualityComparer();
public bool Equals(IntStringKey x, IntStringKey y)
{
return x._ikey == y._ikey && x._skey == y._skey;
}
public int GetHashCode(IntStringKey x)
{
return x._ikey;
}
}
/// <summary>
/// Integer value iff <see cref="IsString"/> return <B>false</B>.
/// </summary>
public int Integer => _ikey;
private int _ikey; // Holds string hashcode if skey != null
/// <summary>
/// String value iff <see cref="IsString"/> return <B>true</B>.
/// </summary>
public string String => _skey;
private string _skey;
/// <summary>
/// Gets array key, string or int as object.
/// </summary>
public object Object => _skey ?? (object)_ikey;
public IntStringKey(int key)
{
_ikey = key;
_skey = null;
}
public IntStringKey(string/*!*/ key)
{
Debug.Assert(key != null);
_skey = key;
_ikey = key.GetHashCode();
}
public static implicit operator IntStringKey(int value) => new IntStringKey(value);
public static implicit operator IntStringKey(string value) => new IntStringKey(value ?? throw new ArgumentNullException());
internal static IntStringKey FromObject(object key)
{
Debug.Assert(key is string || key is int);
if (key != null && key.GetType() == typeof(int))
{
return new IntStringKey((int)key);
}
else
{
return new IntStringKey((string)key);
}
}
public bool IsString => _skey != null;
public bool IsInteger => _skey == null;
public override int GetHashCode() => _ikey;
public bool Equals(IntStringKey other) => Equals(ref other);
public bool Equals(ref IntStringKey other)
{
return _ikey == other._ikey && _skey == other._skey;
}
public bool Equals(int ikey)
{
return _ikey == ikey && _skey == null;
}
public override string ToString() => _skey ?? _ikey.ToString();
public int CompareTo(IntStringKey other)
{
if (this.IsString)
{
if (other.IsString)
return string.CompareOrdinal(_skey, other._skey);
else
return string.CompareOrdinal(_skey, other._ikey.ToString());
}
else
{
if (other.IsString)
return string.CompareOrdinal(_ikey.ToString(), other._skey);
else
return (_ikey == other._ikey) ? 0 : (_ikey < other._ikey ? -1 : +1);
}
}
}
#endregion
/// <summary>
/// Dictionary preserving order of entries.
/// Provides methods for access, ensuring, ordering and PHP library functions support.
/// </summary>
[DebuggerNonUserCode]
public sealed class OrderedDictionary : IDictionary<IntStringKey, PhpValue>, IDictionary
{
#region Fields
private int tableMask; // Mask = (tableSize - 1)
private int tableSize; // Table size = (1 << n)
private int count, // Used entries (0..count)
freeCount, // Amount of free entries within (0..count)
freeList; // first free Entry
private int listHead; // first Entry
private int listTail; // last Entry
private int[]/*!*/buckets; // indexes to Entries (buckets[ hash & tableMask ])
private Entry[] entries; // initialized lazily
/// <summary>
/// Used as intial value for <see cref="buckets"/> if array is empty.
/// With this as buckets, all the operators work and they do not have to check whether the collection is empty.
/// </summary>
private readonly static int[] emptyBuckets = new int[] { -1 };
// TODO: int flags = 0; // heuristics
/* e.g.:
* DeletionPerformed (whether nextNewIndex has to be recomputed when DeepCopied)
* HasDeepCopiableObjects (whether DeepCopy of values is necessary when cloned)
* IsSorted (only if all the items were added by [] operator or as a collection in ctor)
*/
/// <summary>
/// Keep track of additional references. Increased when a copy is made, decreased is a copy is released.
/// </summary>
private int copiesCount = 0;
/// <summary>
/// Additional information about this instance creator.
/// </summary>
internal readonly object owner;
#endregion
#region Constructor
/// <summary>
/// Initialize new instance of <see cref="OrderedDictionary"/> as a duplicate of given <paramref name="copyfrom"/>.
/// </summary>
/// <param name="owner">Instance creator.</param>
/// <param name="copyfrom">Instance of an existing <see cref="OrderedDictionary"/>.</param>
internal OrderedDictionary(object owner, OrderedDictionary/*!*/copyfrom)
{
Debug.Assert(copyfrom != null);
// duplicate internal structure as it is,
// there are no references, so walk through the array is not necessary,
// also rehashing is not necessary.
this.tableSize = copyfrom.tableSize;
this.tableMask = copyfrom.tableMask;
if (copyfrom.buckets != emptyBuckets)
{
this.buckets = new int[this.tableSize];
Buffer.BlockCopy(copyfrom.buckets, 0, this.buckets, 0, this.tableSize * sizeof(int));
//Array.Copy(copyfrom.buckets, 0, this.buckets, 0, this.tableSize);
// TODO: check whether Array.Copy is faster
}
else
{
this.buckets = emptyBuckets;
}
this.listHead = copyfrom.listHead;
this.listTail = copyfrom.listTail;
this.count = copyfrom.count;
this.freeCount = copyfrom.freeCount;
this.freeList = copyfrom.freeList;
//this.nextNewIndex = copyfrom.nextNewIndex;
if (copyfrom.entries != null)
{
this.entries = new Entry[this.tableSize];
Array.Copy(copyfrom.entries, 0, this.entries, 0, this.count);
}
else
{
this.entries = null;
}
//
this.owner = owner;
//
_debug_check_consistency();
}
public OrderedDictionary(object owner, int size)
{
this.tableSize = CalculatetableSize(size);
this.tableMask = 0; /* 0 means that this.buckets is uninitialized */
this.buckets = emptyBuckets; // proper instance initialized lazily
this.listHead = -1;
this.listTail = -1;
this.count = this.freeCount = 0;
this.freeList = -1;
//this.nextNewIndex = 0;
this.entries = null; // initialized lazily
this.owner = owner; // instance creator
//
_debug_check_consistency();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int CalculatetableSize(int size)
{
if (size < (1 << 30))
{
int i = (1 << 2); // how big is our smallest possible array? "1" is min, do not put "0" here! Smaller number makes initialization faster, but slows down expanding. However the size is known mostly ...
while (i < size)
i <<= 1;
return i;
}
/* prevent overflow */
return (1 << 30);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureInitialized()
{
if (this.tableMask == 0)
InitializeBuckets();
}
private void InitializeBuckets()
{
Debug.Assert(this.entries == null, "Initialized already!");
//
this.buckets = new int[this.tableSize];
this.tableMask = this.tableSize - 1;
this.entries = new Entry[this.tableSize];
//
this.buckets.AsSpan().Fill(-1);
}
#endregion
#region Inner class: Entry
/// <summary>
/// An element stored in the table.
/// </summary>
[DebuggerNonUserCode]
struct Entry
{
/// <summary>
/// Key associated with the element.
/// </summary>
internal IntStringKey _key;
// linked list of entries:
internal int
next, last, // within bucket
listNext, listLast; // within the whole ordered dictionary list
/// <summary>
/// Value associated with the element.
/// </summary>
internal PhpValue _value;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool KeyEquals(ref IntStringKey other)
{
return _key.Equals(ref other);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool KeyEquals(int ikey)
{
return _key.Equals(ikey);
}
public KeyValuePair<IntStringKey, PhpValue> KeyValuePair => new KeyValuePair<IntStringKey, PhpValue>(_key, _value);
}
#endregion
#region Inner class: Enumerator
/// <summary>
/// The dictionary enumerator according to PHP semantic, allowing to change underlaying collection during the enumeration.
/// </summary>
public class Enumerator : IDictionaryEnumerator, IPhpEnumerator, IEnumerator<KeyValuePair<IntStringKey, PhpValue>>, IEnumerator<PhpValue>, IDisposable
{
/// <summary>
/// Enumerated table.
/// </summary>
internal OrderedDictionary/*!*/_table;
/// <summary>
/// Reference to associated <see cref="PhpHashtable"/>. Used to unregister enumerator.
/// </summary>
internal readonly PhpHashtable _hashtable;
/// <summary>
/// Current element index.
/// </summary>
private int _element;
/// <summary>
/// Whether enumeration is on the start.
/// </summary>
bool _start;
/// <summary>
/// A reference to another <see cref="Enumerator"/>, allows to link existing enumerators into a linked list.
/// </summary>
internal Enumerator _next;
public Enumerator(OrderedDictionary/*!*/table)
{
Debug.Assert(table != null);
_table = table;
_element = -1;
_start = true;
}
public Enumerator(PhpHashtable/*!*/hashtable)
: this(hashtable.table)
{
_hashtable = hashtable;
hashtable.RegisterEnumerator(this);
}
internal Enumerator/*!*/WithTable(PhpHashtable/*!*/hashtable)
{
Debug.Assert(hashtable != null);
Debug.Assert(hashtable.Count == _table.Count);
if (ReferenceEquals(hashtable, _hashtable))
{
return this;
}
else
{
return new Enumerator(hashtable)
{
_start = _start,
_element = _element,
};
}
}
/// <summary>
/// Gets value indicating the enumerator has current value.
/// </summary>
bool HasEntry => _element >= 0;
private bool FetchCurrent() => HasEntry;
//{
// if (_element >= 0)
// {
// _current = _table.entries[_element].KeyValuePair;
// return true;
// }
// _current = new KeyValuePair<IntStringKey, PhpValue>();
// return false;
//}
/// <summary>
/// Callback method caled by <see cref="_del_key_or_index"/> when an entry has been deleted.
/// </summary>
/// <param name="entry_index">Deleted entry index.</param>
/// <param name="next_entry_index">Next entry index as a replacement.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void EntryDeleted(int entry_index, int next_entry_index)
{
if (entry_index == _element)
{
_element = next_entry_index;
FetchCurrent();
}
}
/// <summary>
/// Called when underlaying table has been changed (Unshare() called).
/// </summary>
internal void TableChanged()
{
Debug.Assert(_hashtable != null, "Enumerator was not registered!");
Debug.Assert(_table != _hashtable.table, "Table was not changed!");
_table = _hashtable.table;
}
#region IEnumerator
protected virtual object CurrentObject => CurrentValue.ToClr();
object IEnumerator.Current => CurrentObject;
public bool MoveNext()
{
Debug.Assert(_hashtable == null || _hashtable.table == _table, "Underlaying table has been changed without updating Enumerator!");
if (_element >= 0)
{
_element = _table.entries[_element].listNext;
}
else if (_start)
{
_start = false;
_element = _table.listHead;
}
return FetchCurrent();
}
public void Reset()
{
_element = -1;
_start = true;
}
#endregion
#region IEnumerator<PhpValue>
PhpValue IEnumerator<PhpValue>.Current => CurrentValue;
#endregion
#region IDisposable
public virtual void Dispose()
{
_element = -1;
_hashtable?.UnregisterEnumerator(this);
//_hashtable = null;
}
#endregion
#region IDictionaryEnumerator Members
DictionaryEntry IDictionaryEnumerator.Entry => new DictionaryEntry(((IDictionaryEnumerator)this).Key, ((IDictionaryEnumerator)this).Value);
object IDictionaryEnumerator.Key => CurrentKey.Object;
object IDictionaryEnumerator.Value => CurrentValue.ToClr();
#endregion
#region IEnumerator<KeyValuePair<IntStringKey, PhpValue>>
public KeyValuePair<IntStringKey, PhpValue> Current =>
new KeyValuePair<IntStringKey, PhpValue>(_table.entries[_element]._key, CurrentValue);
#endregion
#region IPhpEnumerator
public virtual PhpValue CurrentValue => (_element >= 0) ? _table.entries[_element]._value.GetValue() : PhpValue.Void;
public PhpValue CurrentKey => (_element >= 0) ? PhpValue.Create(_table.entries[_element]._key) : PhpValue.Void;
public PhpAlias CurrentValueAliased => (_element >= 0) ? _table.entries[_element]._value.EnsureAlias() : new PhpAlias(PhpValue.Void);
KeyValuePair<PhpValue, PhpValue> IEnumerator<KeyValuePair<PhpValue, PhpValue>>.Current => new KeyValuePair<PhpValue, PhpValue>(CurrentKey, CurrentValue);
public bool MoveLast()
{
_start = false;
_element = _table.listTail;
return FetchCurrent();
}
public bool MoveFirst()
{
_start = false;
_element = _table.listHead;
return FetchCurrent();
}
public bool MovePrevious()
{
if (_element >= 0)
{
_element = _table.entries[_element].listLast;
}
else if (_start)
{
_element = _table.listTail;
_start = false;
}
return FetchCurrent();
}
public bool AtEnd
{
get
{
// if the enumerator is in starting state, it's not considered to be at the end:
if (_start) return false;
return (_element < 0);
}
}
#endregion
}
/// <summary>
/// Performs enumeration on the current state of the array.
/// Array can be changed during the enumeration with no effect to this enumerator.
/// </summary>
internal class ReadonlyEnumerator : Enumerator
{
public ReadonlyEnumerator(PhpHashtable/*!*/hashtable)
: base(hashtable.table.Share()) // enumerates over readonly copy of given array
{
}
public override PhpValue CurrentValue => base.CurrentValue.DeepCopy();
public override void Dispose()
{
_table.Unshare(); // return the shared copy
base.Dispose();
}
}
/// <summary>
/// <see cref="Enumerator"/> behaving as <see cref="IDictionaryEnumerator"/>.
/// </summary>
internal class DictionaryEnumerator : Enumerator
{
public DictionaryEnumerator(OrderedDictionary/*!*/table)
: base(table)
{
}
protected override object CurrentObject => ((IDictionaryEnumerator)this).Entry;
}
#endregion
#region Inner class: EmptyEnumerator
/// <summary>
/// An enumerator representing an empty collection. Single instance can be reused.
/// </summary>
internal sealed class EmptyEnumerator : IEnumerator<KeyValuePair<IntStringKey, PhpValue>>, IEnumerator<PhpValue>, IDictionaryEnumerator, IDisposable // , IPhpEnumerator
{
/// <summary>
/// Singleton instance of this class. Can be reused.
/// </summary>
internal readonly static EmptyEnumerator/*!*/SingletonInstance = new EmptyEnumerator();
private EmptyEnumerator()
{
}
public PhpValue CurrentValue { get { throw new InvalidOperationException(); } }
public IntStringKey CurrentKey { get { throw new InvalidOperationException(); } }
#region IEnumerator<KeyValuePair<IntStringKey, PhpValue>>
public KeyValuePair<IntStringKey, PhpValue> Current { get { throw new InvalidOperationException(); } }
object IEnumerator.Current { get { throw new InvalidOperationException(); } }
PhpValue IEnumerator<PhpValue>.Current => PhpValue.Void;
public bool MoveNext()
{
return false;
}
public void Reset()
{
// nothing
}
#endregion
#region IDisposable
public void Dispose()
{
}
#endregion
#region IDictionaryEnumerator Members
DictionaryEntry IDictionaryEnumerator.Entry { get { throw new InvalidOperationException(); } }
object IDictionaryEnumerator.Key { get { throw new InvalidOperationException(); } }
object IDictionaryEnumerator.Value { get { throw new InvalidOperationException(); } }
#endregion
#region IPhpEnumerator
public bool MoveLast()
{
return false;
}
public bool MoveFirst()
{
return false;
}
public bool MovePrevious()
{
return false;
}
public bool AtEnd
{
get
{
return false;
}
}
#endregion
}
#endregion
#region Inner class: FastEnumerator
internal FastEnumerator GetFastEnumerator()
{
return new FastEnumerator(this);
}
public struct FastEnumerator : IDisposable, IEnumerator<PhpValue>
{
private readonly OrderedDictionary/*!*/_table;
private int _currentEntry;
public FastEnumerator(OrderedDictionary/*!*/table)
{
Debug.Assert(table != null);
_table = table;
_currentEntry = -1;
}
public bool MoveNext()
{
return ((_currentEntry = (_currentEntry >= 0)
? _table.entries[_currentEntry].listNext
: _table.listHead // start // note after unsuccessful MoveNext() enumerator is restarted
) >= 0);
//{
// _current = _table.entries[_currentEntry].KeyValuePair;
// return true;
//}
//else
//{
// _current = new KeyValuePair<IntStringKey, PhpValue>();
// return false;
//}
}
public bool MovePrevious()
{
_currentEntry = (_currentEntry >= 0)
? _table.entries[_currentEntry].listLast
: _table.listTail; // start // note after unsuccessful MovePrevious() enumerator is restarted
return _currentEntry >= 0;
}
public IntStringKey CurrentKey => _table.entries[_currentEntry]._key;
public PhpValue CurrentValue
{
get
{
return _table.entries[_currentEntry]._value;
}
set
{
ModifyCurrentValue(value);
}
}
public KeyValuePair<IntStringKey, PhpValue> Current => _table.entries[_currentEntry].KeyValuePair;
/// <summary>
/// Ensures current value is aliased and gets reference to it.
/// </summary>
public PhpAlias CurrentValueAliased => _table.entries[_currentEntry]._value.EnsureAlias();
public void Reset()
{
_currentEntry = -1;
}
/// <summary>
/// Creates an enumerator that wont reset after unsuccessful <see cref="MoveNext"/>.
/// </summary>
public FastEnumeratorWithStop WithStop() => new FastEnumeratorWithStop(this);
#region IDisposable
public void Dispose()
{
_currentEntry = -1;
}
#endregion
#region IEnumerator<PhpValue>
/// <summary>
/// Gets the element as a PHP value in the collection at the current position of the enumerator.
/// </summary>
PhpValue IEnumerator<PhpValue>.Current => _table.entries[_currentEntry]._value;
/// <summary>
/// Gets the element converted to a CLR object in the collection at the current position of the enumerator.
/// </summary>
object IEnumerator.Current => _table.entries[_currentEntry]._value.ToClr();
#endregion
#region internal: Helper methods
/// <summary>
/// Checks whether enumerator points to an entry.
/// </summary>
public bool IsValid => _currentEntry >= 0 && _table != null;
/// <summary>
/// Gets value indicating that the structure was not initializated.
/// </summary>
public bool IsDefault => _table == null && _currentEntry == 0;
/// <summary>
/// Gets or sets current entry's <see cref="Entry.listLast"/> field.
/// </summary>
internal int CurrentEntryListLast
{
get { Debug.Assert(this.IsValid); return _table.entries[_currentEntry].listLast; }
set
{
Debug.Assert(this.IsValid);
_table.entries[_currentEntry].listLast = value;
}
}
/// <summary>
/// Gets or sets current entry's <see cref="Entry.listNext"/> field or <see cref="OrderedDictionary.listHead"/> if enumerator is not started yet.
/// </summary>
internal int CurrentEntryListNext
{
get
{
if (this.IsValid)
return _table.entries[_currentEntry].listNext;
else
return _table.listHead;
}
set
{
if (this.IsValid)
_table.entries[_currentEntry].listNext = value;
else
_table.listHead = value;
}
}
/// <summary>
/// Modifies key of current entry in the table.
/// </summary>
/// <param name="newkey">New key for the current entry.</param>
/// <remarks>This function does not change the <see cref="CurrentKey"/> and <see cref="Current"/>, since both there values are already fetched.
/// Note the table must be rehashed manually after this operation.</remarks>
internal void ModifyCurrentEntryKey(IntStringKey newkey)
{
Debug.Assert(this.IsValid);
_table.entries[_currentEntry]._key = newkey;
}
private void ModifyCurrentValue(PhpValue newvalue)
{
Debug.Assert(IsValid);
_table.entries[_currentEntry]._value = newvalue;
}
/// <summary>
/// Delete current entry from the table and advances enumerator to the next entry.
/// </summary>
/// <param name="activeEnumerators">List of active enumerators so they can be updated.</param>
/// <returns>Whether there is another entry in the table.</returns>
internal bool DeleteCurrentEntryAndMove(OrderedDictionary.Enumerator activeEnumerators)
{
Debug.Assert(IsValid);
int p = _currentEntry;
int nIndex = _table._index(CurrentKey.Integer);
bool hasMore = MoveNext();
_table._remove_entry(ref _table.entries[p], p, nIndex, activeEnumerators);
return hasMore;
}
/// <summary>
/// Insert new entry before current entry.
/// </summary>
/// <param name="key">New item key.</param>
/// <param name="value">New item value.</param>
internal void InsertBeforeCurrentEntry(IntStringKey key, PhpValue value)
{
_table._add_before(ref key, value, _currentEntry); // is not this.IsValid, new entry is added at the end.
}
/// <summary>
/// Gets current entry index within the <see cref="OrderedDictionary.entries"/> array.
/// </summary>
internal int CurrentEntryIndex
{
get { return _currentEntry; }
set
{
_currentEntry = value;
}
}
#endregion
}
/// <summary>
/// Helper enumerator that enumerates underlaying <see cref="FastEnumerator"/> and does not reset after an unsuccessful <b>MoveNext</b>.
/// </summary>
public struct FastEnumeratorWithStop : IDisposable
{
FastEnumerator _enumerator;
bool _valid;
internal FastEnumeratorWithStop(FastEnumerator enumerator)
{
_enumerator = enumerator;
_valid = true;
}
public bool MoveNext() => _valid && (_valid = _enumerator.MoveNext());
public IntStringKey CurrentKey => _enumerator.CurrentKey;
public PhpValue CurrentValue => _enumerator.CurrentValue;
public void Dispose() => _enumerator.Dispose();
}
#endregion
#region table operations
#region _enlist_*, _debug_check_consistency
/// <summary>
/// Calculates bucket index.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int _index(ref IntStringKey key)
{
return _index(key.Integer);
}
/// <summary>
/// Calculates bucket index.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int _index(int ikey)
{
return this.tableMask & ikey;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void _enlist_to_bucket(ref Entry entry, int entry_index, int list_head)
{
entry.last = -1;
entry.next = list_head;
if (list_head >= 0)
this.entries[list_head].last = entry_index;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void _enlist_to_global(ref Entry entry, int entry_index)
{
entry.listNext = -1;
entry.listLast = this.listTail;
if (this.listTail >= 0)
this.entries[this.listTail].listNext = entry_index;
this.listTail = entry_index;
if (this.listHead < 0)
this.listHead = entry_index;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void _enlist(ref Entry entry, int entry_index, int list_head)
{
//_enlist_to_bucket(ref entry, entry_index, list_head);
//_enlist_to_global(ref entry, entry_index);
entry.next = list_head;
entry.last = -1;
entry.listNext = -1;
entry.listLast = this.listTail;
if (list_head >= 0)
this.entries[list_head].last = entry_index;
if (this.listTail >= 0)
this.entries[this.listTail].listNext = entry_index;
this.listTail = entry_index;
if (this.listHead < 0)
this.listHead = entry_index;
}
/// <summary>
/// Enlists <paramref name="element"/> before given <paramref name="p"/>.
/// </summary>
/// <param name="element"></param>
/// <param name="elementIndex"></param>
/// <param name="p"></param>
/// <param name="pIndex"></param>
private void _enlist_to_global_before(ref Entry element, int elementIndex, ref Entry p, int pIndex)
{
element.listLast = p.listLast;
element.listNext = pIndex;
if (p.listLast >= 0)
this.entries[p.listLast].listNext = elementIndex;
else
this.listHead = elementIndex;
p.listLast = elementIndex;
}
[Conditional("DEBUG")]
internal void _debug_check_consistency()
{
Debug.Assert((this.listHead >= 0 && this.listTail >= 0) || (this.listHead < 0 && this.listTail < 0), "listHead, listTail");
Debug.Assert(this.entries == null || this.entries.Length == this.tableSize, "this.entries.Length != this.tableSize");
var _entries = this.entries;
var _buckets = this.buckets;
// check global list
int count = 0;
int last = -1;
for (int p = this.listHead; p >= 0; p = _entries[p].listNext)
{
Debug.Assert(last != p, "global list cycled!");
Debug.Assert(_entries[p].listLast == last, "_entries[p].listLast != last");
last = p;
++count;
}
Debug.Assert(last == this.listTail, "last == this.listTail");
Debug.Assert(count == this.Count, "count != this.Count");
// check bucket lists
count = 0;
for (int i = 0; i < _buckets.Length; i++)
{
last = -1;
for (int p = _buckets[i]; p >= 0; p = _entries[p].next)
{
Debug.Assert(last != p, "bucket list cycled!");
Debug.Assert(_entries[p].last == last, "_entries[p].last != last");
last = p;
++count;
}
}
Debug.Assert(count == this.Count, "count != this.Count (sum of bucket lists)");
// check free list
if (this.freeCount > 0)
{
last = -1;
Debug.Assert(this.freeList >= 0, "this.freeCount > 0 && this.freeList < 0");
for (int p = this.freeList; p >= 0; p = _entries[p].next)
{
Debug.Assert(last != p, "freeList cycled!");
//Debug.Assert(_entries[p]._value == null, "free entry has not disposed value");
last = p;
}
}
else
{
Debug.Assert(this.freeList < 0, "this.freeCount == 0 && this.freeList >= 0");
}
}
#endregion
#region _do_resize, _rehash
/// <summary>
/// Double the size of internal structures. Rehash entries.
/// </summary>
/// <remarks><see cref="entries"/> has to be initialized already.</remarks>
/// <exception cref="OverflowException">Table size cannot be doubled more.</exception>
private void _do_resize()
{
Debug.Assert(this.entries != null);
// double the table size:
int new_size = checked(this.tableSize << 1);
int new_mask = new_size - 1;
var new_buckets = new int[new_size];
new_buckets.AsSpan().Fill(-1);
var new_entries = new Entry[new_size];
Array.Copy(this.entries, 0, new_entries, 0, this.count);
//
this.tableSize = new_size;
this.tableMask = new_mask;
this.buckets = new_buckets;
this.entries = new_entries;
// _rehash():
var p = this.listHead;
while (p >= 0)
{
ref var pentry = ref new_entries[p];
ref var pbucket = ref new_buckets[pentry._key.Integer & new_mask];
//
_enlist_to_bucket(ref pentry, p, pbucket);
pbucket = p;
//
p = pentry.listNext;
}
// check
_debug_check_consistency();
}
/// <summary>
/// Rehashes all the entries according to their current key. Preserves the order.
/// </summary>
internal void _rehash()
{
// use locals instead of fields:
var _buckets = this.buckets;
var _mask = this.tableMask;
var _entries = this.entries;
// empty buckets
for (int i = 0; i < _buckets.Length; i++)
{
_buckets[i] = -1;
}
// rehash all the entries:
var p = this.listHead;
while (p >= 0)
{
ref Entry pentry = ref _entries[p];
ref int pbucket = ref _buckets[pentry._key.Integer & _mask];
_enlist_to_bucket(ref pentry, p, pbucket);
pbucket = p;
//
p = pentry.listNext;
}
// check
_debug_check_consistency();
}
#endregion
#region _add_or_update, _add_or_update_preserve_ref, _add_first, _add_last
/// <summary>
/// Set <paramref name="value"/> onto given <paramref name="key"/> position.
/// </summary>
/// <param name="key">Key of the item to be added or upudated.</param>
/// <param name="value">Value of the item.</param>
/// <returns>Value indicating whether new key was added.</returns>
/// <remarks>If <paramref name="key"/> is not contained in the table yet, newly added entry is added at the end.</remarks>
public bool _add_or_update(ref IntStringKey key, PhpValue value/*, bool add*/)
{
//ulong h;// = key.Integer
EnsureInitialized();
var _entries = this.entries;
// find
int p = this.buckets[_index(ref key)];
while (p >= 0)
{
ref var pentry = ref _entries[p];
if (pentry.KeyEquals(ref key))
{
pentry._value = value;
return false;
}
//
p = pentry.next;
}
// not found, _add_last:
_add_last(ref key, value);
return true;
}
/// <summary>
/// Checks if the updated entry contains an alias
/// and if so, it updates its value instead of entry's value.
///
/// Otherwise new item is added at the end of the array.
/// </summary>
/// <returns>Value indicating whether new key was added.</returns>
public bool _add_or_update_preserve_ref(ref IntStringKey key, PhpValue value)
{
Debug.Assert(!value.IsAlias);
this.ThrowIfShared();
EnsureInitialized();
// find
int p = buckets[_index(ref key)];
while (p >= 0)
{
ref var pentry = ref entries[p];
if (pentry.KeyEquals(ref key))
{
Operators.SetValue(ref pentry._value, value);
return false;
}
//
p = pentry.next;
}
// not found, _add_last:
_add_last(ref key, value);
return true;
}
//private void _add_no_check(int intKey, object value)
//{
//
//}
/// <summary>
/// Add new entry at the begining of the array.
/// </summary>
/// <param name="key">Entry key.</param>
/// <param name="value">Entry value.</param>
/// <exception cref="ArgumentException">An element with the same key already exists.</exception>
internal void _add_first(ref IntStringKey key, PhpValue value)
{
if (_findEntry(ref key) >= 0)
throw new ArgumentException();
EnsureInitialized();
var _entries = this.entries;
// add:
int p; // index of entry to be used for new item
// find an empty Entry to be used
if (this.freeCount > 0)
{
p = this.freeList;
this.freeList = _entries[p].next;
--this.freeCount;
}
else
{
if (this.count == _entries.Length)
{
_do_resize(); // double the capacity
// update locals affected by resize:
_entries = this.entries;
}
p = this.count++;
}
//
var nIndex = _index(ref key);
//
_entries[p]._key = key;
// enlist into bucket
_enlist_to_bucket(ref _entries[p], p, this.buckets[nIndex]);
// enlist into global
_entries[p].listLast = -1;
_entries[p].listNext = this.listHead;
if (this.listHead >= 0)
_entries[this.listHead].listLast = p;
if (this.listTail < 0)
this.listTail = p;
this.listHead = p;
this.buckets[nIndex] = p;
_entries[p]._value = value;
//// update nextNewIndex: // moved to PhpArray
//if (key.IsInteger && key.Integer >= this.nextNewIndex)
// this.nextNewIndex = key.Integer + 1;
return;// true;
}
/// <summary>
/// Add specified item at the end of the array.
/// </summary>
/// <param name="key">New item key.</param>
/// <param name="value">New item value.</param>
/// <remarks>The function does not check if the item already exists.</remarks>
internal void _add_last(ref IntStringKey key, PhpValue value)
{
Debug.Assert(!_contains(ref key), "Item with given key already exists!");
this.EnsureInitialized();
var _entries = this.entries;
int p;
// find an empty Entry to be used
if (this.freeCount > 0)
{
p = this.freeList;
this.freeList = _entries[p].next;
--this.freeCount;
}
else
{
if (this.count == _entries.Length)
{
_do_resize(); // double the capacity
// update locals affected by resize:
_entries = this.entries;
}
p = this.count++;
}
//
ref var pentry = ref _entries[p];
ref var pbucket = ref buckets[_index(ref key)];
pentry._key = key;
pentry._value = value;
_enlist(ref pentry, p, pbucket);
pbucket = p;
//// update nextNewIndex: // moved to PhpArray
//if (key.IsInteger && key.Integer >= this.nextNewIndex)
// this.nextNewIndex = key.Integer + 1;
return;// true;
}
/// <summary>
/// Add new entry before given <paramref name="entry_index"/>. If <paramref name="entry_index"/> is invalid, new item is added at the end of the table.
/// Note given <paramref name="key"/> must not exist in the table yet.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="entry_index"></param>
private void _add_before(ref IntStringKey key, PhpValue value, int entry_index)
{
this.EnsureInitialized();
if (entry_index < 0)
{
_add_last(ref key, value);
return;
}
var _entries = this.entries;
int p;
// find an empty Entry to be used
if (this.freeCount > 0)
{
p = this.freeList;
this.freeList = _entries[p].next;
--this.freeCount;
}
else
{
if (this.count == _entries.Length)
{
_do_resize(); // double the capacity
// update locals affected by resize:
_entries = this.entries;
}
p = this.count++;
}
//
var nIndex = _index(ref key);
_entries[p]._key = key;
// enlist to bucket:
_enlist_to_bucket(ref _entries[p], p, this.buckets[nIndex]);
// enlist to global
_enlist_to_global_before(ref _entries[p], p, ref _entries[entry_index], entry_index);
_entries[p]._value = value;
this.buckets[nIndex] = p;
}
#endregion
#region _del_key_or_index, _remove_first, _remove_last
//[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void _remove_entry(ref Entry entry, int entry_index, int bucket_index, Enumerator active_enumerators)
{
#if DEBUG
Debug.Assert(entry._key.Equals(ref this.entries[entry_index]._key), "entry != entries[entry_index");
int p;
for (p = this.buckets[bucket_index]; p >= 0; p = this.entries[p].next)
if (p == entry_index)
break;
Debug.Assert(p >= 0, "entry_index not found");
Debug.Assert(freeCount > 0 || freeList < 0, "freeCount == 0 && freeList >= 0,");
#endif
// update active enumerators, so they won't point to the item being deleted:
for (; active_enumerators != null; active_enumerators = active_enumerators._next)
active_enumerators.EntryDeleted(entry_index, entry.listNext);
// unlink entry from the bucket list:
if (entry.last >= 0)
this.entries[entry.last].next = entry.next;
else
this.buckets[bucket_index] = entry.next;
if (entry.next >= 0)
this.entries[entry.next].last = entry.last;
// unlink entry from global list:
if (entry.listLast >= 0)
this.entries[entry.listLast].listNext = entry.listNext;
else // Deleting the head of the list
this.listHead = entry.listNext;
if (entry.listNext >= 0)
this.entries[entry.listNext].listLast = entry.listLast;
else
this.listTail = entry.listLast;
// link entry to freeList:
entry.next = this.freeList;
//ignoring: entry.last, entry.listNext, entry.listLast
entry._value = PhpValue.Void;
this.freeList = entry_index;
++this.freeCount;
}
/// <summary>
/// Removes given <paramref name="key"/> from the collection.
/// </summary>
/// <param name="key">Key to be removed from the collection.</param>
/// <param name="active_enumerators">List of active enumerators so they can be updated if they point to the item being deleted.</param>
/// <returns><c>True</c> if specified key was found and the item removed.</returns>
/// <remarks>This operation can invalidate an existing enumerator. You can prevent this
/// by passing <paramref name="active_enumerators"/>List of active enumerators do they can be updated.</remarks>
public bool _del_key_or_index(ref IntStringKey key, Enumerator active_enumerators)
{
var nIndex = _index(ref key);
var p = buckets[nIndex];
while (p >= 0)
{
ref var pentry = ref entries[p];
if (pentry.KeyEquals(ref key))
{
_remove_entry(ref pentry, p, nIndex, active_enumerators);
return true;
}
p = pentry.next;
}
return false;
}
/// <summary>
/// Removes specified entry from the array.
/// </summary>
/// <param name="p">Index of the entry within the <see cref="entries"/> array.</param>
/// <param name="active_enumerators">List of active enumerators so they can be updated if they point to the item being deleted.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void _remove_entry(int p, Enumerator active_enumerators)
{
ref var pentry = ref entries[p];
_remove_entry(ref pentry, p, _index(ref pentry._key), active_enumerators); // remove the entry
}
/// <summary>
/// Removes the last entry of the array and returns it.
/// </summary>
/// <param name="active_enumerators">List of active enumerators so they can be updated if they point to deleted item.</param>
/// <returns>The last entry of the array.</returns>
/// <exception cref="InvalidOperationException">The table is empty.</exception>
public KeyValuePair<IntStringKey, PhpValue> _remove_last(Enumerator active_enumerators)
{
var p = this.listTail; // entry to be removed from the collection
if (p < 0)
throw new InvalidOperationException();
var result = this.entries[p].KeyValuePair;
_remove_entry(p, active_enumerators);
//
return result;
}
/// <summary>
/// Removes the first entry of the array and returns it.
/// </summary>
/// <param name="active_enumerators">List of active enumerators so they can be updated if they point to deleted item.</param>
/// <returns>The first entry of the array.</returns>
/// <exception cref="InvalidOperationException">The table is empty.</exception>
public KeyValuePair<IntStringKey, PhpValue> _remove_first(Enumerator active_enumerators)
{
var p = this.listHead; // entry to be removed from the collection
if (p < 0)
throw new InvalidOperationException();
var result = this.entries[p].KeyValuePair;
_remove_entry(p, active_enumerators);
//
return result;
}
#endregion
#region _findEntry, _tryGetValue, _get, _contains
private int _findEntry(ref IntStringKey key)
{
var p = buckets[_index(ref key)];
while (p >= 0 && !entries[p].KeyEquals(ref key))
{
p = entries[p].next;
}
return p; // -1 in case entry was not found
}
private bool _tryGetValue(IntStringKey key, out PhpValue value)
{
var p = buckets[_index(ref key)];
while (p >= 0)
{
ref var pentry = ref entries[p];
if (pentry.KeyEquals(ref key))
{
value = pentry._value;
return true;
}
p = pentry.next;
}
value = PhpValue.Void;
return false;
}
private bool _tryGetValue(int ikey, out PhpValue value)
{
var p = this.buckets[_index(ikey)];
while (p >= 0)
{
ref var pentry = ref this.entries[p];
if (pentry.KeyEquals(ikey))
{
value = pentry._value;
return true;
}
p = pentry.next;
}
value = PhpValue.Void;
return false;
}
internal PhpValue _get(ref IntStringKey key)
{
var p = this.buckets[_index(ref key)];
while (p >= 0)
{
ref var pentry = ref this.entries[p];
if (pentry.KeyEquals(ref key))
{
return pentry._value;
}
p = pentry.next;
}
// not found:
return PhpValue.Void;// throw new KeyNotFoundException();
}
/// <summary>
/// Gets reference to value at given index.
/// </summary>
/// <remarks>
/// The method does not "unshare" the collection in case there are more arrays using this data structure.
/// Caller should be responsible for ensuring it is writeable.
/// </remarks>
/// <exception cref="KeyNotFoundException">In case the item at given index is not found.</exception>
internal ref PhpValue _getref(IntStringKey key)
{
var p = this.buckets[_index(ref key)];
while (p >= 0)
{
ref var pentry = ref this.entries[p];
if (pentry.KeyEquals(ref key))
{
return ref pentry._value;
}
p = pentry.next;
}
// not found, create the entry:
_add_last(ref key, PhpValue.Void); // changes this.entries, this.buckets, this.tableMask
return ref this.entries[this.buckets[_index(ref key)]]._value;
}
internal bool _contains(ref IntStringKey key)
{
return _findEntry(ref key) >= 0;
}
#endregion
#region _clear, _shuffle_data, _merge_sort, _sort, _reverse, _find_max_int_key, _merge_sort
/// <summary>
/// Reset internal data structure (fast).
/// </summary>
private void _clear()
{
// nullify entries, so their values can be disposed:
if (this.count > 0)
Array.Clear(this.entries, 0, this.count);
// destroy lists, reset counts:
this.listHead = -1;
this.listTail = -1;
this.count = this.freeCount = 0;
//this.nextNewIndex = 0;
}
/// <summary>
/// Shuffles entries order, while keys and data are preserved.
/// </summary>
/// <param name="generator">Random number generator used to randomize the order.</param>
public void _shuffle_data(Random/*!*/generator)
{
if (generator == null)
throw new ArgumentNullException("generator");
var n_elems = this.Count;
if (n_elems <= 1)
return;
var elems = new int[n_elems];
var n_left = n_elems;
int j, p;
var _entries = this.entries;
// store indices of active entries
for (j = 0, p = this.listHead; p >= 0; p = _entries[p].listNext)
elems[j++] = p;
// shuffle indices randomly
while ((--n_left) > 0)
{
// swap elems[n_left] randomly with another entry:
int rnd = generator.Next(0, n_left + 1);
if (rnd < n_left)
{
p = elems[n_left];
elems[n_left] = elems[rnd];
elems[rnd] = p;
}
}
// reconnect the global list
this.listHead = elems[0];
this.listTail = -1;
// TODO: reset instrict enumerators within the shuffle() operation
for (j = 0; j < elems.Length; j++) // JIT optimization
{
var elems_j = elems[j];
_enlist_to_global(ref _entries[elems_j], elems_j);
//if (this.listTail >= 0)
// _entries[this.listTail].listNext = elems_j;
//entries[elems_j].listLast = this.listTail;
//entries[elems_j].listNext = -1;
//this.listTail = elems_j;
}
// check
_debug_check_consistency();
}
/// <summary>
/// Reverses entries order.
/// </summary>
public void _reverse()
{
var _entries = this.entries;
int tmp;
for (var p = this.listHead; p >= 0; p = _entries[p].listLast)
{
// swap prev/next
tmp = _entries[p].listNext;
_entries[p].listNext = _entries[p].listLast;
_entries[p].listLast = tmp;
}
// swap head/tail
tmp = this.listHead;
this.listHead = this.listTail;
this.listTail = tmp;
//
_debug_check_consistency();
}
///// <summary>
///// Iterate through the array and find the max integer key.
///// </summary>
///// <returns>Max integer key or <c>-1</c> if no positive integer key is found.</returns>
//public int _find_max_int_key()
//{
// var _entries = this.entries;
// // TODO: check flags, whether it is a simple sorted array (0..N)
// int max_key = -1;
// // iterate backwards, find the max faster
// int p = this.listTail;
// while (p >= 0)
// {
// ref var pentry = ref _entries[p];
// if (pentry._key.Integer > max_key && pentry._key.IsInteger)
// {
// max_key = pentry._key.Integer;
// }
// //
// p = pentry.listLast;
// }
// //
// return max_key;
//}
/// <summary>
/// Sort sequence of entries using merge sort. Only changes <see cref="Entry.listNext"/> fields, <see cref="Entry.listLast"/> are not modified at all.
/// </summary>
/// <param name="comparer">Comparer.</param>
/// <param name="entries"><see cref="OrderedDictionary.entries"/> of table being sorted.</param>
/// <param name="first">Index of an entry to start sorting from.</param>
/// <param name="count">Amount if entries to sort.</param>
/// <param name="after">Index of the entry after the sorted sequence.</param>
/// <returns>New first entry index.</returns>
private static int _merge_sort(IComparer<KeyValuePair<IntStringKey, PhpValue>>/*!*/ comparer, Entry[] entries, int first, int count, out int after)
{
Debug.Assert(first >= 0 && count > 0);
// recursion end:
if (count == 1)
{
after = entries[first].listNext;
entries[first].listNext = -1;
return first;
}
// sort recursively:
int alen = count >> 1;
int blen = count - alen;
Debug.Assert(alen <= blen && alen > 0);
// divides the portion into two lists (a and b) and sorts them:
int result;
var a = _merge_sort(comparer, entries, first, alen, out result);
var b = _merge_sort(comparer, entries, result, blen, out after);
// initializes merging - sets the first element of the result list:
if (comparer.Compare(entries[a].KeyValuePair, entries[b].KeyValuePair) <= 0)
{
// if there is exactly one element in the "a" list returns (a,b) list:
if (--alen == 0) { entries[a].listNext = b; return a; }
result = a;
a = entries[a].listNext;
}
else
{
// if there is exactly one element in the "b" list returns (b,a) list:
if (--blen == 0) { entries[b].listNext = a; return b; }
result = b;
b = entries[b].listNext;
}
// merges "a" and "b" lists into the "result";
// "iterator" points to the last element added to the "result",
// "a" and "b" references moves along the respective lists:
var iterator = result;
Debug.Assert(alen > 0 && blen > 0);
for (; ; )
{
if (comparer.Compare(entries[a].KeyValuePair, entries[b].KeyValuePair) <= 0)
{
// adds element from list "a" to the "result":
iterator = entries[iterator].listNext = a;
if (--alen == 0)
{
// adds remaining elements to the result:
if (blen > 0) entries[iterator].listNext = b;
break;
}
// advances "a" pointer:
a = entries[a].listNext;
}
else
{
// adds element from list "b" to the "result":
iterator = entries[iterator].listNext = b;
if (--blen == 0)
{
// adds remaining elements to the result:
if (alen > 0) entries[iterator].listNext = a;
break;
}
// advances "a" pointer:
b = entries[b].listNext;
}
}
return result;
}
#endregion
#region sortops: _sort, _multisort
internal struct sortops
{
/// <summary>
/// Sorts items according to given <paramref name="comparer"/>. This changes only the order of items.
/// </summary>
/// <param name="table"><see cref="OrderedDictionary"/> instance to be sorted.</param>
/// <param name="comparer">Comparer used to sort items.</param>
internal static void _sort(OrderedDictionary/*!*/table, IComparer<KeyValuePair<IntStringKey, PhpValue>>/*!*/ comparer)
{
Debug.Assert(table != null);
Debug.Assert(comparer != null);
var count = table.Count;
if (count <= 1) return;
int after;
table.listHead = _merge_sort(comparer, table.entries, table.listHead, count, out after);
Debug.Assert(after < 0);
// update double-linked list (prev):
table._link_prevs_by_nexts();
// check
table._debug_check_consistency();
}
/// <summary>
/// Sorts multiple lists given comparer for each hashtable.
/// </summary>
/// <param name="count">The number of items in each and every list.</param>
/// <param name="hashtables">The lists.</param>
/// <param name="comparers">Comparers to be used for lexicographical comparison.</param>
internal static void _multisort(int count, PhpHashtable[]/*!!*/ hashtables, IComparer<KeyValuePair<IntStringKey, PhpValue>>[]/*!!*/ comparers)
{
int next;
int length = hashtables.Length;
int last = length - 1;
OrderedDictionary table;
// nothing to do:
if (count == 0 || hashtables.Length <= 1) return;
// interconnects all lists into a grid, heads are unchanged:
InterconnectGrid(count, hashtables);
// lists are only single-linked cyclic and "heads" are unchanged from here on:
for (int i = last; i > 0; i--)
{
table = hashtables[i].table;
// sorts i-th list (doesn't modify Prev and keeps the list cyclic):
table.listHead = _merge_sort(comparers[i], table.entries, table.listHead, count, out next);
Debug.Assert(next < 0);
// reorders the (i-1)-the list according to the the i-th one:
ReorderList(count, hashtables[i - 1].table, hashtables[i].table);
}
// sorts the 0-th list (its order will determine the order of whole grid rows):
table = hashtables[0].table;
table.listHead = _merge_sort(comparers[0], table.entries, table.listHead, count, out next);
Debug.Assert(next < 0);
// reorders the last list according to the 0-th one:
ReorderList(count, hashtables[last].table, hashtables[0].table);
// reorders remaining lists (if any):
for (int i = last; i >= 2; i--)
ReorderList(count, hashtables[i - 1].table, hashtables[i].table);
// disconnects lists from each other and reconstructs their double-linked structure:
DisconnectGrid(count, hashtables);
//
#if DEBUG
for (int i = 0; i < hashtables.Length; i++)
hashtables[i].table._debug_check_consistency();
#endif
}
/// <summary>
/// Interconnects elements of given lists into a grid using their <see cref="Entry.listLast"/> fields. <see cref="OrderedDictionary.listHead"/> is preserved.
/// </summary>
/// <param name="count">The number of elements in each and every list.</param>
/// <param name="hashtables">Lists to be interconnected.</param>
/// <remarks>
/// The grid: <BR/>
/// <PRE>
/// H H H
/// | | |
/// ~o~o~o~
/// | | | ~ = Prev (right to left), cyclic without a head (necessary)
/// ~o~o~o~ - = Next (top to bottom), cyclic with a head (not necessary)
/// | | |
/// </PRE>
/// </remarks>
private static void InterconnectGrid(int count, PhpHashtable[]/*!!*/ hashtables)
{
int last = hashtables.Length - 1;
var enumerators = new FastEnumerator[hashtables.Length];
// initialize enumerators and moves them to the respective first elements:
for (int i = 0; i < enumerators.Length; i++)
{
enumerators[i] = hashtables[i].GetFastEnumerator();
enumerators[i].MoveNext(); // advance enumerator to first entry
}
while (count-- > 0)
{
// sets Prev field of the first iterator:
enumerators[0].CurrentEntryListLast = enumerators[last].CurrentEntryIndex;
// all iterators except for the last one:
for (int i = 0; i < last; i++)
{
enumerators[i + 1].CurrentEntryListLast = enumerators[i].CurrentEntryIndex;
enumerators[i].MoveNext();
}
// advances the last iterator:
enumerators[last].MoveNext();
}
}
/// <summary>
/// Disconnects elements of lists each from other.
/// </summary>
/// <param name="count">The number of elements in each and every list.</param>
/// <param name="hashtables">The lists.</param>
private static void DisconnectGrid(int count, PhpHashtable[]/*!!*/hashtables)
{
for (int i = 0; i < hashtables.Length; i++)
{
// restores Prev references in all elements of the i-th list except for the head:
hashtables[i].table._link_prevs_by_nexts();
}
}
/// <summary>
/// Reorders a minor list according to the major one. "Straightens" horizontal interconnection.
/// </summary>
/// <param name="count">The number of elements in each and every list.</param>
/// <param name="minorHead">The head of a minor list (i).</param>
/// <param name="majorHead">The head of a major list (i + 1).</param>
/// <remarks><paramref name="minorHead"/> is the array before <paramref name="majorHead"/>.</remarks>
private static void ReorderList(int count, OrderedDictionary minorHead, OrderedDictionary majorHead)
{
var major = majorHead.GetFastEnumerator(); major.MoveNext();
var minor = minorHead.GetFastEnumerator();
while (count-- > 0)
{
minor.CurrentEntryListNext = major.CurrentEntryListLast; // major.listLast points to minor, so we can set these links
minor.MoveNext();
major.MoveNext();
}
minor.CurrentEntryListNext = -1;
}
}
#endregion
#region private: _link_prevs_by_nexts, _link_nexts_by_prevs, _reverse_prev_links
/// <summary>
/// Update <see cref="Entry.listLast"/> and <see cref="listTail"/> according to <see cref="Entry.listNext"/>s.
/// </summary>
/// <remarks>Makes global list valid.</remarks>
private void _link_prevs_by_nexts()
{
var _entries = this.entries;
int last = -1;
for (int p = this.listHead; p >= 0; p = _entries[p].listNext)
{
_entries[p].listLast = last;
last = p;
}
this.listTail = last;
// global list is valid now
}
/// <summary>
/// Update <see cref="Entry.listNext"/> and <see cref="listHead"/> according to <see cref="Entry.listLast"/>s.
/// </summary>
/// <remarks>Makes global list valid.</remarks>
private void _link_nexts_by_prevs()
{
var _entries = this.entries;
int next = -1;
for (int p = this.listTail; p >= 0; p = _entries[p].listLast)
{
_entries[p].listNext = next;
next = p;
}
this.listHead = next;
// global list is valid now
}
/// <summary>
/// Reverses <see cref="Entry.listLast"/> links.
/// </summary>
/// <remarks>Global list won't be valid after this operation. However this operation reverts itself when called twice.</remarks>
private void _reverse_prev_links()
{
var _entries = this.entries;
int p, next = -1, prev;
// reverse the listLast links
for (p = this.listTail; p >= 0; p = prev)
{
ref var pentry = ref _entries[p];
prev = pentry.listLast;
pentry.listLast = next;
next = p;
}
// listTail now points to previously first entry
this.listTail = next;
}
#endregion
#region _deep_copy_*
/// <summary>
/// Perform inplace deep copy of all values.
/// </summary>
public void _deep_copy_inplace()
{
var entries = this.entries;
var p = this.listHead;
while (p >= 0)
{
ref var pentry = ref entries[p];
_deep_copy_entry_value(ref pentry);
p = pentry.listNext;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void _deep_copy_entry_value(ref Entry entry)
{
entry._value = entry._value.DeepCopy();
}
/// <summary>
/// Perform inplace deep copy of all values.
/// This overload replaces <paramref name="oldref"/> with <paramref name="newref"/>
/// within aliased values; only if <paramref name="oldref"/> is not <c>null</c>.
/// </summary>
public void _deep_copy_inplace(PhpArray oldref, PhpArray newref)
{
if (oldref == null || oldref == newref)
{
_deep_copy_inplace();
}
else
{
var entries = this.entries;
var p = this.listHead;
while (p >= 0)
{
ref var pentry = ref entries[p];
_deep_copy_entry_value(ref pentry, oldref, newref);
p = pentry.listNext;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void _deep_copy_entry_value(ref Entry entry, PhpArray oldref, PhpArray newref)
{
if (entry._value.Object is PhpAlias alias && alias.Value.Object is PhpArray array && array == oldref)
{
Debug.Assert(newref != null);
entry._value = PhpValue.Create(new PhpAlias(PhpValue.Create(newref)));
}
else
{
_deep_copy_entry_value(ref entry);
}
}
#endregion
#region _ensure_item_alias, _ensure_item_object, _ensure_item_array
/// <summary>
/// Ensures item at specified key is aliased.
/// If there is no such item, new one is created.
/// </summary>
/// <param name="key">Index of item to be checked.</param>
/// <param name="array">Caller. Used to lazy copy if necessary.</param>
/// <returns><see cref="PhpAlias"/> of specified item.</returns>
public PhpAlias/*!*/_ensure_item_alias(ref IntStringKey key, PhpHashtable/*!*/array)
{
Debug.Assert(array != null, "array == null");
Debug.Assert(array.table == this, "array.table != this");
var p = buckets[_index(ref key)];
while (p >= 0)
{
ref var pentry = ref entries[p];
if (pentry.KeyEquals(ref key))
{
if (pentry._value.Object is PhpAlias alias)
{
return alias;
//// if valueref references the array itself, array must be lazily copied:
//if (this.IsShared && valueref.Value.Object == this.owner)
//{
// // shared table references itself, must be deepcopied:
// array.EnsureWritable();
// // "this" is not "array.table" anymore!
// Debug.Assert(!array.table.IsShared, "array.table.IsShared");
// Debug.Assert(array.table.entries[p]._value.IsAlias, "array.table.entries[p].Value is not aliased!");
// Debug.Assert(array.table != this, "array.table == this; but it shouldn't after deep copying!");
// valueref = array.table.entries[p]._value.Alias;
//}
}
else
{
// make the value aliased:
if (this.IsShared)
{
// we have to unshare this, so we can modify the content:
array.EnsureWritable();
// IMPORTANT: "this" != "array.table" anymore!
return array.table.entries[p]._value.EnsureAlias(); // C# 7.3: pentry = ref array.table.entries[p];
}
// wrap _entries[p].Value into PhpAlias
return pentry._value.EnsureAlias();
}
}
//
p = pentry.next;
}
// not found, create new item:
var valueref = new PhpAlias(PhpValue.Void);
array.Add(key, PhpValue.Create(valueref)); // we have to adjust maxIntKey and make the array writable; do not call _add_last directly
return valueref;
}
/// <summary>
/// Ensures specified item is a class object.
/// </summary>
/// <param name="key">Index of item to be checked.</param>
/// <param name="array">Caller. Used to lazy copy if necessary.</param>
/// <returns><see cref="object"/> ensured to be at given <paramref name="key"/>.</returns>
public object/*!*/_ensure_item_object(ref IntStringKey key, PhpArray/*!*/array)
{
Debug.Assert(array != null, "array == null");
Debug.Assert(array.table == this, "array.table != this");
var _entries = this.entries;
for (var p = this.buckets[_index(ref key)]; p >= 0; p = _entries[p].next)
if (_entries[p].KeyEquals(ref key))
{
if (this.IsShared)
{
// we have to unshare this, so we can modify the content:
array.EnsureWritable();
// "this" is not "array.table" anymore!
_entries = array.table.entries;
}
return _entries[p]._value.EnsureObject();
}
// not found, create new item:
var valueobj = new stdClass();
array.Add(key, PhpValue.FromClass(valueobj)); // we have to adjust maxIntKey and make the array writable; do not call _add_last directly
return valueobj;
}
/// <summary>
/// Ensures specified item is <see cref="PhpArray"/>.
/// </summary>
/// <param name="key">Index of item to be checked.</param>
/// <param name="array">Caller. Used to lazy copy if necessary.</param>
/// <returns><see cref="PhpArray"/> ensured to be at given <paramref name="key"/>.</returns>
public IPhpArray/*!*/_ensure_item_array(ref IntStringKey key, PhpArray/*!*/array)
{
Debug.Assert(array != null, "array == null");
Debug.Assert(array.table == this, "array.table != this");
var _entries = this.entries;
for (var p = this.buckets[_index(ref key)]; p >= 0; p = _entries[p].next)
if (_entries[p].KeyEquals(ref key))
{
if (this.IsShared)
{
// we have to unshare this, so we can modify the content:
array.EnsureWritable();
// "this" is not "array.table" anymore!
_entries = array.table.entries;
}
return _entries[p]._value.EnsureArray();
}
// not found, create new item:
var newarr = new PhpArray();
array.Add(key, PhpValue.Create(newarr)); // we have to adjust maxIntKey and make the array writable; do not call _add_last directly
return newarr;
}
#endregion
#region _set_operation
/// <summary>
/// Performs diff operation on the list of this instance and the other list.
/// </summary>
/// <param name="op">The operation.</param>
/// <param name="other">The other list.</param>
/// <param name="comparer">A comparer.</param>
/// <param name="deleted_dummy_next">Value to be assigned to <see cref="Entry.listNext"/> to be marked as deleted.</param>
/// <remarks>Updates only <see cref="Entry.listNext"/> links. <see cref="Entry.listLast"/>s are preserved so the operation can be reverted eventually.</remarks>
private void _set_operation(SetOperations op, OrderedDictionary/*!*/ other, IComparer<KeyValuePair<IntStringKey, PhpValue>>/*!*/comparer, int deleted_dummy_next)
{
Debug.Assert(other != null && comparer != null);
Debug.Assert(deleted_dummy_next < -1, "deleted_dummy_next has to be different than end-of-list value!");
var _entries = this.entries;
var other_iterator = other.GetFastEnumerator();
var iterator = this.GetFastEnumerator();
int iterator_prev_entry = -1;
// advances iterators onto the first element:
iterator.MoveNext();
other_iterator.MoveNext();
while (iterator.IsValid && other_iterator.IsValid)
{
int cmp = comparer.Compare(iterator.Current, other_iterator.Current);
if (cmp > 0)
{
// advance the other list iterator:
other_iterator.MoveNext();
}
else if (cmp < 0 ^ op == SetOperations.Difference)
{
var next = iterator.CurrentEntryListNext;
// marks and skips the current element in the instance list, advances iterator:
if (iterator_prev_entry < 0) this.listHead = next;
else _entries[iterator_prev_entry].listNext = next;
iterator.CurrentEntryListNext = deleted_dummy_next;
iterator.CurrentEntryIndex = next;
}
else
{
// advance this instance list iterator:
iterator_prev_entry = iterator.CurrentEntryIndex;
iterator.MoveNext();
}
}
// marks the remaining elements:
if (op == SetOperations.Intersection)
{
while (iterator.IsValid)
{
var next = _entries[iterator.CurrentEntryIndex].listNext;
// marks and skips the current element in the instance list, advances iterator:
if (iterator_prev_entry < 0) this.listHead = next;
else _entries[iterator_prev_entry].listNext = next;
iterator.CurrentEntryListNext = deleted_dummy_next;
iterator.CurrentEntryIndex = next;
}
}
//// dispose enumerators:
//iterator.Dispose();
//other_iterator.Dispose();
}
/// <summary>
/// Retrieves the difference of this instance elemens and elements of the specified lists.
/// </summary>
/// <param name="op">The operation.</param>
/// <param name="arrays">Array of arrays take away from this instance.</param>
/// <param name="comparer">The comparer of entries.</param>
/// <param name="result">The <see cref="IDictionary"/> where to add remaining items.</param>
internal void _set_operation(SetOperations op, PhpHashtable[]/*!*/ arrays,
IComparer<KeyValuePair<IntStringKey, PhpValue>>/*!*/ comparer, PhpHashtable/*!*/ result)
{
Debug.Assert(arrays != null && comparer != null && result != null);
int next;
int count = this.Count;
// nothing to do:
if (count == 0) return;
var _entries = this.entries;
const int deleted_dummy_next = -3;
// sorts this instance list (doesn't modify Prevs and keeps list cyclic):
this.listHead = _merge_sort(comparer, _entries, this.listHead, count, out next);
Debug.Assert(next < 0);
OrderedDictionary other_table;
foreach (var other_array in arrays)
{
// total number of elements in diff list:
if (other_array != null)
{
count = other_array.Count;
other_table = other_array.table;
}
else
{
count = 0;
other_table = null;
}
// result is empty - either the list is differentiated with itself or intersected with an empty set:
if (other_table == this && op == SetOperations.Difference || count == 0 && op == SetOperations.Intersection)
{
// reconstructs double linked list skipping elements marked as deleted:
_link_nexts_by_prevs();
// the result is empty:
return;
}
// skip operation (nothing new can be added):
if (other_table == this && op == SetOperations.Intersection || count == 0 && op == SetOperations.Difference)
continue;
Debug.Assert(other_table != null);
// perform the sort on the copied instance since it can be shared or used on another thread
other_table = new OrderedDictionary(other_table.owner, other_table);
// sorts other_head's list (doesn't modify Prevs and keeps list cyclic):
other_table.listHead = _merge_sort(comparer, other_table.entries, other_table.listHead, count, out next);
Debug.Assert(next < 0);
// applies operation on the instance list and the other list:
_set_operation(op, other_table, comparer, deleted_dummy_next);
//// rolls mergesort back:
//other_table._link_nexts_by_prevs(); // other_table is disposed
// instance list is empty:
if (this.listHead < 0) break;
}
_reverse_prev_links();
// adds remaining elements to a dictionary:
for (var iterator = this.listTail; iterator >= 0; iterator = _entries[iterator].listLast)
{
if (_entries[iterator].listNext != deleted_dummy_next)
result.Add(_entries[iterator]._key, _entries[iterator]._value);
}
_reverse_prev_links();
// reconstructs double linked list skipping elements marked as deleted:
_link_nexts_by_prevs();
//
_debug_check_consistency();
}
#endregion
#endregion
#region Public: IsShared, Share, Unshare, ThrowIfShared, InplaceCopyOnReturn
/// <summary>
/// True iff the data structure is shared by more PhpHashtable instances and must not be modified.
/// </summary>
//[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsShared { get { return this.copiesCount != 0; } }
/// <summary>
/// Remember whether this instance and its owner (<see cref="PhpArray"/>) can be recycled upon returning by value from a function.
/// </summary>
internal bool InplaceCopyOnReturn { get { return this.copiesCount < 0; } set { this.copiesCount = value ? -1 : 0; } }
/// <summary>
/// Marks this instance as shared (<see cref="IsShared"/>) and returns itself.
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public OrderedDictionary/*!*/Share()
{
Interlocked.Increment(ref copiesCount);
return this;
}
/// <summary>
/// Release shared instance of internal data.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Unshare()
{
Debug.Assert(copiesCount >= 0, "Too many Unshare() calls!"); // 0 is allowed, so noone needs this table anymore
Interlocked.Decrement(ref copiesCount);
}
/// <summary>
/// Helper method that throws if current instance is marked as shared.
/// </summary>
/// <exception cref="InvalidOperationException">If this instance is marked as shared.</exception>
[Conditional("DEBUG")]
private void ThrowIfShared()
{
if (this.IsShared)
throw new InvalidOperationException("The instance is not modifiable.");
}
#endregion
#region IDictionary<IntStringKey, PhpValue>
public void Add(IntStringKey key, PhpValue value)
{
_add_or_update(ref key, value/*, false*/);
}
public bool ContainsKey(IntStringKey key)
{
return _contains(ref key);
}
public ICollection<IntStringKey> Keys
{
get
{
if (_keys == null)
_keys = new KeyCollection(this);
return _keys;
}
}
private KeyCollection _keys;
public bool Remove(IntStringKey key)
{
return _del_key_or_index(ref key, null);
}
public bool TryGetValue(IntStringKey key, out PhpValue value)
{
return _tryGetValue(key, out value);
}
public bool TryGetValue(int ikey, out PhpValue value)
{
return _tryGetValue(ikey, out value);
}
/// <summary>
/// Gets a collection of values.
/// </summary>
public ICollection<PhpValue>/*!*/ Values
{
get
{
if (_values == null)
_values = new ValueCollection(this);
return _values;
}
}
private ValueCollection _values;
#region Inner class: ValueCollection
/// <summary>
/// Auxiliary collection used for manipulating keys or values of PhpHashtable.
/// </summary>
public sealed class ValueCollection : ICollection<PhpValue>, ICollection
{
private readonly OrderedDictionary/*!*/ hashtable;
internal ValueCollection(OrderedDictionary/*!*/ hashtable)
{
this.hashtable = hashtable;
}
#region ICollection<PhpValue> Members
public bool Contains(PhpValue item)
{
using (var enumerator = hashtable.GetFastEnumerator())
while (enumerator.MoveNext())
if (item.Equals(enumerator.CurrentValue))
return true;
return false;
}
public void CopyTo(PhpValue[]/*!*/ array, int index)
{
using (var enumerator = hashtable.GetFastEnumerator())
while (enumerator.MoveNext())
array[index++] = enumerator.CurrentValue;
}
public bool IsReadOnly { get { return true; } }
public void Add(PhpValue item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Remove(PhpValue item)
{
throw new NotSupportedException();
}
#endregion
#region ICollection Members
public int Count { get { return hashtable.Count; } }
public bool IsSynchronized { get { return false; } }
public object SyncRoot { get { return this; } }
public void CopyTo(Array/*!*/ array, int index)
{
CopyTo((object[])array, index);
}
#endregion
#region IEnumerable<PhpValue> Members
public IEnumerator<PhpValue> GetEnumerator()
{
var enumerator = hashtable.GetFastEnumerator();
while (enumerator.MoveNext())
yield return enumerator.CurrentValue;
enumerator.Dispose();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
#endregion
#region Inner class: KeyCollection
/// <summary>
/// Auxiliary collection used for manipulating keys or values of PhpHashtable.
/// </summary>
public sealed class KeyCollection : ICollection<IntStringKey>, ICollection
{
private readonly OrderedDictionary/*!*/ hashtable;
internal KeyCollection(OrderedDictionary/*!*/ hashtable)
{
this.hashtable = hashtable;
}
#region ICollection<object> Members
public bool Contains(IntStringKey item)
{
using (var enumerator = hashtable.GetFastEnumerator())
while (enumerator.MoveNext())
if (enumerator.CurrentKey.Equals(ref item))
return true;
return false;
}
public void CopyTo(IntStringKey[]/*!*/ array, int index)
{
using (var enumerator = hashtable.GetFastEnumerator())
while (enumerator.MoveNext())
array[index++] = enumerator.CurrentKey;
}
public bool IsReadOnly { get { return true; } }
public void Add(IntStringKey item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Remove(IntStringKey item)
{
throw new NotSupportedException();
}
#endregion
#region ICollection Members
public int Count { get { return hashtable.Count; } }
public bool IsSynchronized { get { return false; } }
public object SyncRoot { get { return this; } }
public void CopyTo(Array/*!*/ array, int index)
{
CopyTo((IntStringKey[])array, index);
}
#endregion
#region IEnumerable<object> Members
public IEnumerator<IntStringKey> GetEnumerator()
{
var enumerator = hashtable.GetFastEnumerator();
while (enumerator.MoveNext())
yield return enumerator.CurrentKey;
enumerator.Dispose();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
#endregion
public PhpValue this[IntStringKey key]
{
get
{
return _get(ref key);
}
set
{
_add_or_update(ref key, value/*, false*/);
}
}
public void Add(KeyValuePair<IntStringKey, PhpValue> item)
{
var key = item.Key;
_add_or_update(ref key, item.Value/*, true*/);
}
public void Clear()
{
_clear();
}
public bool Contains(KeyValuePair<IntStringKey, PhpValue> item)
{
PhpValue value;
return _tryGetValue(item.Key, out value) && value.Equals(item.Value);
}
public void CopyTo(KeyValuePair<IntStringKey, PhpValue>[] array, int arrayIndex)
{
if (array == null || arrayIndex < 0 || (arrayIndex + this.Count) > array.Length)
throw new ArgumentException();
using (var enumerator = GetFastEnumerator())
while (enumerator.MoveNext())
array[arrayIndex++] = enumerator.Current;
}
public void CopyTo(PhpValue[] array, int arrayIndex)
{
if (array == null || arrayIndex < 0 || (arrayIndex + this.Count) > array.Length)
throw new ArgumentException();
var enumerator = GetFastEnumerator();
while (enumerator.MoveNext())
array[arrayIndex++] = enumerator.CurrentValue;
// FastEnumerator does not have to be disposed
}
public int Count
{
get { return this.count - this.freeCount; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(KeyValuePair<IntStringKey, PhpValue> item)
{
var key = item.Key;
return _del_key_or_index(ref key, null);
}
public IEnumerator<KeyValuePair<IntStringKey, PhpValue>>/*!*/GetEnumerator() => new Enumerator(this);
IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this);
#endregion
//#region ISerializable (CLR only)
///// <summary>
///// Handles serialization and deserialization of <see cref="OrderedDictionary"/>.
///// </summary>
//private class SerializationHelper : ISerializable, IDeserializationCallback, IObjectReference
//{
// /// <summary>
// /// An instance of <see cref="OrderedDictionary"/> lazily created.
// /// </summary>
// private OrderedDictionary instance;
// /// <summary>
// /// Internal data from <see cref="SerializationInfo"/>.
// /// </summary>
// private readonly KeyValuePair<IntStringKey, object>[]/*!!*/array;
// /// <summary>
// /// Name of value field within <see cref="SerializationInfo"/> containing serialized array of keys and objects.
// /// </summary>
// private const string InfoValueName = "KeyValuePairs";
// /// <summary>
// /// Beginning of the deserialization.
// /// </summary>
// /// <param name="info"></param>
// /// <param name="context"></param>
// private SerializationHelper(SerializationInfo/*!*/info, StreamingContext context)
// {
// // careful - the array received here may not be fully deserialized yet
// // wait until until OnDeserialization to use it
// this.array = (KeyValuePair<IntStringKey, object>[])info.GetValue(InfoValueName, typeof(KeyValuePair<IntStringKey, object>[]));
// }
// [System.Security.SecurityCritical]
// internal static void GetObjectData(OrderedDictionary/*!*/instance, SerializationInfo info, StreamingContext context)
// {
// Debug.Assert(instance != null);
// Debug.Assert(info != null);
// info.SetType(typeof(SerializationHelper));
// var array = new KeyValuePair<IntStringKey, object>[instance.Count];
// instance.CopyTo(array, 0);
// info.AddValue(InfoValueName, array);
// }
// public void GetObjectData(SerializationInfo info, StreamingContext context)
// {
// // should never be called
// throw new InvalidOperationException();
// }
// public object GetRealObject(StreamingContext context)
// {
// return this.instance ?? (this.instance = new OrderedDictionary(null, (this.array != null) ? this.array.Length : 0));
// }
// public virtual void OnDeserialization(object sender)
// {
// Debug.Assert(this.instance != null);
// var data = this.array;
// if (data != null)
// {
// for (int i = 0; i < data.Length; i++)
// this.instance.Add(data[i]);
// }
// }
//}
//[System.Security.SecurityCritical]
//public void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// SerializationHelper.GetObjectData(this, info, context);
//}
//#endregion
#region ICloneable
/// <summary>
/// Perform fast clone.
/// </summary>
/// <returns>Clone of <c>this</c>.</returns>
public object Clone()
{
return new OrderedDictionary(this.owner, this);
}
#endregion
#region IDictionary
public void Add(object key, object value) { this.Add((IntStringKey)key, PhpValue.FromClr(value)); }
public bool Contains(object key) { return this.ContainsKey((IntStringKey)key); }
IDictionaryEnumerator IDictionary.GetEnumerator() => new DictionaryEnumerator(this);
public bool IsFixedSize { get { return false; } }
ICollection IDictionary.Keys { get { return (ICollection)this.Keys; } }
public void Remove(object key) { this.Remove((IntStringKey)key); }
ICollection IDictionary.Values { get { return (ICollection)this.Values; } }
public object this[object key]
{
get { return this[(IntStringKey)key]; }
set { this[(IntStringKey)key] = PhpValue.FromClr(value); }
}
public void CopyTo(Array array, int index)
{
// KeyValuePair<IntStringKey, object>[]
var pairs = array as KeyValuePair<IntStringKey, object>[];
if (pairs != null)
{
CopyTo(pairs, index);
return;
}
// DictionaryEntry[];
var entries = array as DictionaryEntry[];
if (entries != null)
{
using (var enumerator = GetFastEnumerator())
while (enumerator.MoveNext())
entries[index++] = new DictionaryEntry(enumerator.CurrentKey, enumerator.CurrentValue);
return;
}
// object[]
var objects = array as object[];
if (objects != null)
{
using (var enumerator = GetFastEnumerator())
while (enumerator.MoveNext())
objects[index++] = enumerator.Current;
return;
}
// otherwise
throw new ArgumentException("array");
}
public bool IsSynchronized { get { return false; } }
public object SyncRoot { get { return this; } }
#endregion
}
}
| 35.171988 | 218 | 0.512942 | [
"Apache-2.0"
] | jondmcelroy/peachpie | src/Peachpie.Runtime/OrderedDictionary.cs | 102,458 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadNextScene : MonoBehaviour
{
public void Load()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
| 21.230769 | 77 | 0.75 | [
"MIT"
] | iuyhcdfs/departedstore | Assets/LoadNextScene.cs | 278 | C# |
using YamlDotNet.RepresentationModel;
namespace Logicality.GitHub.Actions.Workflow;
public class JobDefaults : JobKeyValueMap<JobDefaults>
{
private string? _shell;
private string? _workingDirectory;
public JobDefaults(Job job) : base(job, "defaults")
{
}
public JobDefaults(Job job, IDictionary<string, string> map)
: base(job, "defaults", map)
{
}
/// <summary>
/// Set default shell and working-directory to all run steps in the job.
/// https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_iddefaultsrun
/// </summary>
/// <param name="shell"></param>
/// <param name="workingDirectory"></param>
/// <returns></returns>
public JobDefaults Run(string shell, string workingDirectory)
{
_shell = shell;
_workingDirectory = workingDirectory;
return this;
}
internal override void Build(YamlMappingNode yamlMappingNode)
{
if (Map.Any() || !string.IsNullOrWhiteSpace(_shell))
{
var defaultsMappingNode = new YamlMappingNode();
foreach (var property in Map)
{
defaultsMappingNode.Add(property.Key, new YamlScalarNode(property.Value));
}
// Defaults Run
if (!string.IsNullOrWhiteSpace(_shell) && !string.IsNullOrWhiteSpace(_workingDirectory))
{
var defaultsRunMappingNode = new YamlMappingNode
{
{ "shell", _shell },
{ "working-directory", _workingDirectory }
};
defaultsMappingNode.Add("run", defaultsRunMappingNode);
}
yamlMappingNode.Add("defaults", defaultsMappingNode);
}
}
} | 32.709091 | 115 | 0.60478 | [
"MIT"
] | logicality-io/extensions-hosted-services | libs/github/src/Actions.Workflow/JobDefaults.cs | 1,799 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Ipfs
{
[TestClass]
public class PeerTest
{
private const string marsId = "QmSoLMeWqB7YGVLJN3pNLQpmmEk35v6wYtsMGLzSr5QBU3";
private const string plutoId = "QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM";
private const string marsPublicKey = "CAASogEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKGUtbRQf+a9SBHFEruNAUatS/tsGUnHuCtifGrlbYPELD3UyyhWf/FYczBCavx3i8hIPEW2jQv4ehxQxi/cg9SHswZCQblSi0ucwTBFr8d40JEiyB9CcapiMdFQxdMgGvXEOQdLz1pz+UPUDojkdKZq8qkkeiBn7KlAoGEocnmpAgMBAAE=";
private static string marsAddress = "/ip4/10.1.10.10/tcp/29087/ipfs/QmSoLMeWqB7YGVLJN3pNLQpmmEk35v6wYtsMGLzSr5QBU3";
[TestMethod]
public new void ToString()
{
Assert.AreEqual("", new Peer().ToString());
Assert.AreEqual(marsId, new Peer { Id = marsId }.ToString());
}
[TestMethod]
public void DefaultValues()
{
var peer = new Peer();
Assert.AreEqual(null, peer.Id);
Assert.AreEqual(0, peer.Addresses.Count());
Assert.AreEqual("unknown/0.0", peer.ProtocolVersion);
Assert.AreEqual("unknown/0.0", peer.AgentVersion);
Assert.AreEqual(null, peer.PublicKey);
Assert.AreEqual(false, peer.IsValid()); // missing peer ID
Assert.AreEqual(null, peer.ConnectedAddress);
Assert.IsFalse(peer.Latency.HasValue);
}
[TestMethod]
public void ConnectedPeer()
{
var peer = new Peer
{
ConnectedAddress = new MultiAddress(marsAddress),
Latency = TimeSpan.FromHours(3.03 * 2)
};
Assert.AreEqual(marsAddress, peer.ConnectedAddress.ToString());
Assert.AreEqual(3.03 * 2, peer.Latency.Value.TotalHours);
}
[TestMethod]
public void Validation_No_Id()
{
var peer = new Peer();
Assert.AreEqual(false, peer.IsValid());
}
[TestMethod]
public void Validation_With_Id()
{
Peer peer = marsId;
Assert.AreEqual(true, peer.IsValid());
}
[TestMethod]
public void Validation_With_Id_Pubkey()
{
var peer = new Peer
{
Id = marsId,
PublicKey = marsPublicKey
};
Assert.AreEqual(true, peer.IsValid());
}
[TestMethod]
public void Validation_With_Id_Invalid_Pubkey()
{
var peer = new Peer
{
Id = plutoId,
PublicKey = marsPublicKey
};
Assert.AreEqual(false, peer.IsValid());
}
[TestMethod]
public void Value_Equality()
{
var a0 = new Peer { Id = marsId };
var a1 = new Peer { Id = marsId };
var b = new Peer { Id = plutoId };
Peer c = null;
Peer d = null;
Assert.IsTrue(c == d);
Assert.IsFalse(c == b);
Assert.IsFalse(b == c);
Assert.IsFalse(c != d);
Assert.IsTrue(c != b);
Assert.IsTrue(b != c);
#pragma warning disable 1718
Assert.IsTrue(a0 == a0);
Assert.IsTrue(a0 == a1);
Assert.IsFalse(a0 == b);
#pragma warning disable 1718
Assert.IsFalse(a0 != a0);
Assert.IsFalse(a0 != a1);
Assert.IsTrue(a0 != b);
Assert.IsTrue(a0.Equals(a0));
Assert.IsTrue(a0.Equals(a1));
Assert.IsFalse(a0.Equals(b));
Assert.AreEqual(a0, a0);
Assert.AreEqual(a0, a1);
Assert.AreNotEqual(a0, b);
Assert.AreEqual<Peer>(a0, a0);
Assert.AreEqual<Peer>(a0, a1);
Assert.AreNotEqual<Peer>(a0, b);
Assert.AreEqual(a0.GetHashCode(), a0.GetHashCode());
Assert.AreEqual(a0.GetHashCode(), a1.GetHashCode());
Assert.AreNotEqual(a0.GetHashCode(), b.GetHashCode());
}
[TestMethod]
public void Implicit_Conversion_From_String()
{
Peer a = marsId;
Assert.IsInstanceOfType(a, typeof(Peer));
}
}
}
| 32.181159 | 273 | 0.53569 | [
"MIT"
] | wforney/net-ipfs-core | test/PeerTest.cs | 4,443 | C# |
namespace ProjectSnowshoes
{
partial class TheScreenIsBlue
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.errRep = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Anchor = System.Windows.Forms.AnchorStyles.None;
this.pictureBox1.BackgroundImage = global::ProjectSnowshoes.Properties.Resources.SegoeUIEmoji_Tongue;
this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.pictureBox1.Location = new System.Drawing.Point(429, 39);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(478, 376);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// label1
//
this.label1.Anchor = System.Windows.Forms.AnchorStyles.None;
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Roboto Light", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.Color.White;
this.label1.Location = new System.Drawing.Point(419, 339);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(498, 38);
this.label1.TabIndex = 1;
this.label1.Text = "That...wasn\'t supposed to happen.";
//
// label2
//
this.label2.Anchor = System.Windows.Forms.AnchorStyles.None;
this.label2.Font = new System.Drawing.Font("Roboto Light", 16F);
this.label2.ForeColor = System.Drawing.Color.White;
this.label2.Location = new System.Drawing.Point(334, 398);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(668, 89);
this.label2.TabIndex = 2;
this.label2.Text = "So, we stopped Snowshoes to prevent any harm to your machine, avoiding any headac" +
"hes in a system-wide crash.";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// button1
//
this.button1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.button1.FlatAppearance.BorderColor = System.Drawing.Color.White;
this.button1.FlatAppearance.BorderSize = 2;
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Font = new System.Drawing.Font("Roboto", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button1.ForeColor = System.Drawing.Color.White;
this.button1.Location = new System.Drawing.Point(0, 734);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(1336, 34);
this.button1.TabIndex = 3;
this.button1.Text = "Exit to Windows";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// errRep
//
this.errRep.Anchor = System.Windows.Forms.AnchorStyles.None;
this.errRep.Font = new System.Drawing.Font("Roboto Light", 12F);
this.errRep.ForeColor = System.Drawing.Color.White;
this.errRep.Location = new System.Drawing.Point(335, 487);
this.errRep.Name = "errRep";
this.errRep.Size = new System.Drawing.Size(668, 107);
this.errRep.TabIndex = 4;
this.errRep.Text = "If you want to report this error, say this:";
this.errRep.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// TheScreenIsBlue
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.RoyalBlue;
this.ClientSize = new System.Drawing.Size(1336, 768);
this.Controls.Add(this.errRep);
this.Controls.Add(this.button1);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.pictureBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "TheScreenIsBlue";
this.Text = "TheScreenIsBlue";
this.TopMost = true;
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.TheScreenIsBlue_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label errRep;
}
} | 47.589552 | 158 | 0.603889 | [
"Apache-2.0"
] | IndigoBox/ProjectSnowshoes | ProjectSnowshoes/TheScreenIsBlue.Designer.cs | 6,379 | C# |
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using CommonSerializer;
using Kts.ObjectSync.Common;
using Microsoft.IO;
using NetMQ;
using NetMQ.Sockets;
using System.Threading.Tasks;
namespace Kts.ObjectSync.Transport.NetMQ
{
public class NetMQTransport: ITransport, IDisposable
{
private readonly ICommonSerializer _serializer;
private readonly RouterSocket _socket;
private static readonly RecyclableMemoryStreamManager _mgr = new RecyclableMemoryStreamManager();
private const string _prefix = "ObjectSyncProperty.";
private readonly ConcurrentDictionary<string, Tuple<Type, Action<string, object>>> _receiverCache = new ConcurrentDictionary<string, Tuple<Type, Action<string, object>>>();
private readonly ConcurrentDictionary<string, Action> _getOnConnectCache = new ConcurrentDictionary<string, Action>();
private readonly NetMQPoller _poller;
public NetMQTransport(ICommonSerializer serializer, bool isServer, Uri serverAddress = null, int maxMessageBufferCount = 1000)
{
_serializer = serializer;
_socket = new RouterSocket();
_socket.Options.ReceiveHighWatermark = maxMessageBufferCount;
// _subscription.Options.Linger // keep messages after disconnect
var timer = new NetMQTimer(5);
_poller = new NetMQPoller { _socket, timer };
_socket.ReceiveReady += OnMessageHandler;
var address = serverAddress == null ? "tcp://localhost:12345" : serverAddress.ToString();
if (isServer)
_socket.Bind(address);
else
_socket.Connect(address);
_poller.RunAsync("NetMQPoller for " + address);
}
public void Flush() // TODO: add timeout to flush
{
//var task = new Task(() => {
// while (_socket.HasOut) // doesn't work as it's "always true for the publisher" -- some bug
// Thread.Sleep(1);
//});
//task.Start(_poller);
//task.Wait();
}
private void OnMessageHandler(object sender, NetMQSocketEventArgs e)
{
var msg = new NetMQMessage(3);
var received = -1;
while (e.Socket.TryReceiveMultipartMessage(ref msg) && ++received < 1000)
{
var subject = msg[1].ConvertToString().Replace(_prefix, ""); // three frames: connection, subject, data
if (!_receiverCache.TryGetValue(subject, out var tuple))
continue;
using (var ms = new MemoryStream(msg[2].Buffer, 0, msg[2].BufferSize, false))
{
var data = ms.Length <= 0 ? null : _serializer.Deserialize(ms, tuple.Item1);
tuple.Item2.Invoke(subject, data);
}
}
}
public void Dispose()
{
_socket.ReceiveReady -= OnMessageHandler;
_poller.Dispose();
_socket.Dispose();
}
public void Send(string fullKey, Type type, object value) // TODO: add timeout to send
{
using (var stream = (RecyclableMemoryStream)_mgr.GetStream(fullKey))
{
_serializer.Serialize(stream, value, type);
var connectionFrame = new NetMQFrame(0); // all connections
var subjectFrame = new NetMQFrame(_prefix + fullKey);
var dataFrame = new NetMQFrame(stream.GetBuffer(), (int)stream.Length);
var msg = new NetMQMessage(new[]{connectionFrame, subjectFrame, dataFrame});
_socket.SendMultipartMessage(msg); // does memcpy, will block if buffer is full
}
}
public void RegisterReceiver(string parentKey, Type type, Action<string, object> action)
{
_receiverCache[parentKey] = Tuple.Create(type, action);
}
public void UnregisterReceiver(string parentKey)
{
_receiverCache.TryRemove(parentKey, out var _);
}
public void RegisterWantsAllOnConnected(string fullKey)
{
throw new NotImplementedException();
//_getOnConnectCache[fullKey] = action;
//if (IsConnected)
// action.Invoke();
}
public void UnregisterWantsAllOnConnected(string fullKey)
{
_getOnConnectCache.TryRemove(fullKey, out var _);
}
}
} | 38.736842 | 178 | 0.622056 | [
"MIT"
] | BrannonKing/Kts.ObjectSync | Kts.ObjectSync.Transport.NetMQ/NetMQTransport.cs | 4,418 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("ImageClassifierTrainer")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("ImageClassifierTrainer")]
[assembly: System.Reflection.AssemblyTitleAttribute("ImageClassifierTrainer")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 42.416667 | 80 | 0.660118 | [
"MIT"
] | elrod68/Hands-On-Machine-Learning-for-.NET-Developers-V | Section_6_ImageClassifier/Src_6_1/ImageClassifierTrainer/obj/Release/netcoreapp3.1/ImageClassifierTrainer.AssemblyInfo.cs | 1,018 | C# |
// Copyright (C) 2012 Winterleaf Entertainment L,L,C.
//
// THE SOFTW ARE IS PROVIDED ON AN “ AS IS” BASIS, WITHOUT W ARRANTY OF ANY KIND,
// INCLUDING WITHOUT LIMIT ATION THE W ARRANTIES OF MERCHANT ABILITY, FITNESS
// FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT . THE ENTIRE RISK AS TO THE
// QUALITY AND PERFORMANCE OF THE SOFTW ARE IS THE RESPONSIBILITY OF LICENSEE.
// SHOULD THE SOFTW ARE PROVE DEFECTIVE IN ANY RESPECT , LICENSEE AND NOT LICEN -
// SOR OR ITS SUPPLIERS OR RESELLERS ASSUMES THE ENTIRE COST OF AN Y SERVICE AND
// REPAIR. THIS DISCLAIMER OF W ARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
// AGREEMENT. NO USE OF THE SOFTW ARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// The use of the WinterLeaf Entertainment LLC DotNetT orque (“DNT ”) and DotNetT orque
// Customizer (“DNTC”)is governed by this license agreement (“ Agreement”).
//
// R E S T R I C T I O N S
//
// (a) Licensee may not: (i) create any derivative works of DNTC, including but not
// limited to translations, localizations, technology add-ons, or game making software
// other than Games; (ii) reverse engineer , or otherwise attempt to derive the algorithms
// for DNT or DNTC (iii) redistribute, encumber , sell, rent, lease, sublicense, or otherwise
// transfer rights to DNTC; or (iv) remove or alter any tra demark, logo, copyright
// or other proprietary notices, legends, symbols or labels in DNT or DNTC; or (iiv) use
// the Software to develop or distribute any software that compete s with the Software
// without WinterLeaf Entertainment’s prior written consent; or (i iiv) use the Software for
// any illegal purpose.
// (b) Licensee may not distribute the DNTC in any manner.
//
// LI C E N S E G R A N T .
// This license allows companies of any size, government entities or individuals to cre -
// ate, sell, rent, lease, or otherwise profit commercially from, games using executables
// created from the source code of DNT
//
// **********************************************************************************
// **********************************************************************************
// **********************************************************************************
// THE SOURCE CODE GENERATED BY DNTC CAN BE DISTRIBUTED PUBLICLY PROVIDED THAT THE
// DISTRIBUTOR PROVIDES THE GENERATE SOURCE CODE FREE OF CHARGE.
//
// THIS SOURCE CODE (DNT) CAN BE DISTRIBUTED PUBLICLY PROVIDED THAT THE DISTRIBUTOR
// PROVIDES THE SOURCE CODE (DNT) FREE OF CHARGE.
// **********************************************************************************
// **********************************************************************************
// **********************************************************************************
//
// Please visit http://www.winterleafentertainment.com for more information about the project and latest updates.
#region
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinterLeaf.Classes;
using WinterLeaf.Containers;
using WinterLeaf.Enums;
using System.ComponentModel;
using System.Threading;
#endregion
namespace WinterLeaf.tsObjects
{
/// <summary>
///
/// </summary>
internal class tsObjectConvertercoGuiInspector : TypeConverter
{
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="sourceType"></param>
/// <returns></returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return (typeof(string) == sourceType);
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="culture"></param>
/// <param name="value"></param>
/// <returns></returns>
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
return new coGuiInspector(value as string);
}
return null;
}
}
/// <summary>
///
/// </summary>
[TypeConverter(typeof(tsObjectConvertercoGuiInspector))]
public class coGuiInspector: coGuiStackControl
{
/// <summary>
///
/// </summary>
/// <param name="simobjectid"></param>
internal coGuiInspector(string simobjectid) : base(simobjectid){ }
/// <summary>
///
/// </summary>
/// <param name="simobjectid"></param>
internal coGuiInspector(uint simobjectid): base(simobjectid){ }
/// <summary>
///
/// </summary>
/// <param name="simobjectid"></param>
internal coGuiInspector(int simobjectid): base(simobjectid){ }
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator ==(coGuiInspector ts, string simobjectid)
{
if (object.ReferenceEquals(ts, null))
return object.ReferenceEquals(simobjectid, null);
return ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
throw new NotImplementedException();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (this._mSimObjectId ==(string)myReflections.ChangeType( obj,typeof(string)));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator !=(coGuiInspector ts, string simobjectid)
{
if (object.ReferenceEquals(ts, null))
return !object.ReferenceEquals(simobjectid, null);
return !ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator string( coGuiInspector ts)
{
if (object.ReferenceEquals(ts, null))
return "0";
return ts._mSimObjectId;
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator coGuiInspector(string ts)
{
return new coGuiInspector(ts);
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator int( coGuiInspector ts)
{
if (object.ReferenceEquals(ts, null))
return 0;
int i;
return int.TryParse(ts._mSimObjectId, out i) ? i : 0;
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator coGuiInspector(int ts)
{
return new coGuiInspector(ts);
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator uint( coGuiInspector ts)
{
if (object.ReferenceEquals(ts, null))
return 0;
uint i;
return uint.TryParse(ts._mSimObjectId, out i) ? i : 0;
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator coGuiInspector(uint ts)
{
return new coGuiInspector(ts);
}
/// <summary>
///
/// </summary>
public int dividerMargin
{
get
{
return dnTorque.self.GetVar(_mSimObjectId + ".dividerMargin").AsInt();
}
set
{
dnTorque.self.SetVar(_mSimObjectId + ".dividerMargin", value.AsString());
}
}
/// <summary>
/// Specify groups that should be shown or not. Specifying 'shown' implicitly does 'not show' all other groups. Example string: +name -otherName
/// </summary>
public String groupFilters
{
get
{
return dnTorque.self.GetVar(_mSimObjectId + ".groupFilters").AsString();
}
set
{
dnTorque.self.SetVar(_mSimObjectId + ".groupFilters", value.AsString());
}
}
/// <summary>
/// If false the custom fields Name, Id, and Source Class will not be shown.
/// </summary>
public bool showCustomFields
{
get
{
return dnTorque.self.GetVar(_mSimObjectId + ".showCustomFields").AsBool();
}
set
{
dnTorque.self.SetVar(_mSimObjectId + ".showCustomFields", value.AsString());
}
}
/// <summary>
/// ( GuiInspector, addInspect, void, 3, 4, ( id object, (bool autoSync = true) ) - Add the object to the list of objects being inspected. )
///
/// </summary>
public void addInspect(string a2, string a3= ""){
TorqueScriptTemplate.m_ts.fnGuiInspector_addInspect(_mSimObjectId, a2, a3);
}
/// <summary>
/// ( GuiInspector, apply, void, 2, 2, apply() - Force application of inspected object's attributes )
///
/// </summary>
public void apply(){
TorqueScriptTemplate.m_ts.fnGuiInspector_apply(_mSimObjectId);
}
/// <summary>
/// ( GuiInspector, getInspectObject, const char*, 2, 3, getInspectObject( int index=0 ) - Returns currently inspected object )
///
/// </summary>
public string getInspectObject(string a2= ""){
return TorqueScriptTemplate.m_ts.fnGuiInspector_getInspectObject(_mSimObjectId, a2);
}
/// <summary>
/// ( GuiInspector, getNumInspectObjects, S32, 2, 2, () - Return the number of objects currently being inspected. )
///
/// </summary>
public int getNumInspectObjects(){
return TorqueScriptTemplate.m_ts.fnGuiInspector_getNumInspectObjects(_mSimObjectId);
}
/// <summary>
/// ( GuiInspector, inspect, void, 3, 3, Inspect(Object))
///
/// </summary>
public void inspect(string a2){
TorqueScriptTemplate.m_ts.fnGuiInspector_inspect(_mSimObjectId, a2);
}
/// <summary>
/// ( GuiInspector, refresh, void, 2, 2, Reinspect the currently selected object. )
///
/// </summary>
public void refresh(){
TorqueScriptTemplate.m_ts.fnGuiInspector_refresh(_mSimObjectId);
}
/// <summary>
/// ( GuiInspector, removeInspect, void, 3, 3, ( id object ) - Remove the object from the list of objects being inspected. )
///
/// </summary>
public void removeInspect(string a2){
TorqueScriptTemplate.m_ts.fnGuiInspector_removeInspect(_mSimObjectId, a2);
}
/// <summary>
/// ( GuiInspector, setName, void, 3, 3, setName(NewObjectName))
///
/// </summary>
public new void setName(string a2){
TorqueScriptTemplate.m_ts.fnGuiInspector_setName(_mSimObjectId, a2);
}
/// <summary>
/// ( GuiInspector, setObjectField, void, 4, 4,
/// setObjectField( fieldname, data ) - Set a named fields value on the inspected object if it exists. This triggers all the usual callbacks that would occur if the field had been changed through the gui. )
///
/// </summary>
public void setObjectField(string a2, string a3){
TorqueScriptTemplate.m_ts.fnGuiInspector_setObjectField(_mSimObjectId, a2, a3);
}
}}
| 35.321637 | 210 | 0.5625 | [
"Unlicense"
] | Winterleaf/DNT-Torque3D-V1.1-MIT-3.0 | Engine/lib/DNT/tsObjects/coGuiInspector.cs | 11,757 | C# |
using System;
using NUnit.Framework;
namespace generatortests
{
[TestFixture]
public class Core_Jar2Xml : BaseGeneratorTest
{
protected override bool TryJavaInterop1 => false;
[Test]
public void GeneratedOK ()
{
AllowWarnings = true;
RunAllTargets (
outputRelativePath: "Core_Jar2Xml",
apiDescriptionFile: "expected/Core_Jar2Xml/api.xml",
expectedRelativePath: "Core_Jar2Xml",
enumFieldsMapFile: "expected/Core_Jar2Xml/fields.xml",
enumMethodMapFile: "expected/Core_Jar2Xml/methods.xml"
);
}
}
}
| 20.37037 | 59 | 0.725455 | [
"MIT"
] | Wivra/java.interop | tests/generator-Tests/Integration-Tests/Core_Jar2Xml.cs | 550 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace MultipleArduinoCom
{
class ArduinoSerialPort
{
private string comPort;
private Int32 baudRate;
private SerialPort ArduinoSerial = new SerialPort();
public ArduinoSerialPort(string COMport, Int32 BaudRate)
{
comPort = COMport;
baudRate = BaudRate;
}
public bool Connect()
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
if (port.Contains(comPort))
{
ArduinoSerial.PortName = comPort;
ArduinoSerial.BaudRate = 9600;
ArduinoSerial.Open();
return true;
}
}
return false;
}
public bool hasData()
{
if (ArduinoSerial.IsOpen && ArduinoSerial.BytesToRead > 0)
{
return true;
}
else
{
return false;
}
}
public string readData()
{
if (!ArduinoSerial.IsOpen) return null;
return ArduinoSerial.ReadLine();
}
public bool writeData(string data)
{
if (!ArduinoSerial.IsOpen) return false;
ArduinoSerial.Write(data + '\n');
return true;
}
public void close()
{
ArduinoSerial.Close();
}
}
}
| 23.955882 | 70 | 0.49294 | [
"Unlicense"
] | T41A/CanToUart | MultipleArduinoCom/ArduinoSerialPort.cs | 1,631 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
using ICSharpCode.NRefactory.Editor;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Highlighting;
namespace ICSharpCode.AvalonEdit.Utils
{
/// <summary>
/// Helps printing documents.
/// </summary>
public static class DocumentPrinter
{
#if NREFACTORY
/// <summary>
/// Converts a readonly TextDocument to a Block and applies the provided highlighting definition.
/// </summary>
public static Block ConvertTextDocumentToBlock(ReadOnlyDocument document, IHighlightingDefinition highlightingDefinition)
{
IHighlighter highlighter;
if (highlightingDefinition != null)
highlighter = new DocumentHighlighter(document, highlightingDefinition);
else
highlighter = null;
return ConvertTextDocumentToBlock(document, highlighter);
}
#endif
/// <summary>
/// Converts an IDocument to a Block and applies the provided highlighter.
/// </summary>
public static Block ConvertTextDocumentToBlock(IDocument document, IHighlighter highlighter)
{
if (document == null)
throw new ArgumentNullException("document");
Paragraph p = new Paragraph();
p.TextAlignment = TextAlignment.Left;
for (int lineNumber = 1; lineNumber <= document.LineCount; lineNumber++) {
if (lineNumber > 1)
p.Inlines.Add(new LineBreak());
var line = document.GetLineByNumber(lineNumber);
if (highlighter != null) {
HighlightedLine highlightedLine = highlighter.HighlightLine(lineNumber);
p.Inlines.AddRange(highlightedLine.ToRichText().CreateRuns());
} else {
p.Inlines.Add(document.GetText(line));
}
}
return p;
}
#if NREFACTORY
/// <summary>
/// Converts a readonly TextDocument to a RichText and applies the provided highlighting definition.
/// </summary>
public static RichText ConvertTextDocumentToRichText(ReadOnlyDocument document, IHighlightingDefinition highlightingDefinition)
{
IHighlighter highlighter;
if (highlightingDefinition != null)
highlighter = new DocumentHighlighter(document, highlightingDefinition);
else
highlighter = null;
return ConvertTextDocumentToRichText(document, highlighter);
}
#endif
/// <summary>
/// Converts an IDocument to a RichText and applies the provided highlighter.
/// </summary>
public static RichText ConvertTextDocumentToRichText(IDocument document, IHighlighter highlighter)
{
if (document == null)
throw new ArgumentNullException("document");
var texts = new List<RichText>();
for (int lineNumber = 1; lineNumber <= document.LineCount; lineNumber++) {
var line = document.GetLineByNumber(lineNumber);
if (lineNumber > 1)
texts.Add(line.PreviousLine.DelimiterLength == 2 ? "\r\n" : "\n");
if (highlighter != null) {
HighlightedLine highlightedLine = highlighter.HighlightLine(lineNumber);
texts.Add(highlightedLine.ToRichText());
} else {
texts.Add(document.GetText(line));
}
}
return RichText.Concat(texts.ToArray());
}
/// <summary>
/// Creates a flow document from the editor's contents.
/// </summary>
public static FlowDocument CreateFlowDocumentForEditor(TextEditor editor)
{
IHighlighter highlighter = editor.TextArea.GetService(typeof(IHighlighter)) as IHighlighter;
FlowDocument doc = new FlowDocument(ConvertTextDocumentToBlock(editor.Document, highlighter));
doc.FontFamily = editor.FontFamily;
doc.FontSize = editor.FontSize;
return doc;
}
}
}
| 38.081301 | 129 | 0.74082 | [
"MIT"
] | 376730969/ILSpy | AvalonEdit/ICSharpCode.AvalonEdit/Utils/DocumentPrinter.cs | 4,686 | C# |
namespace Grabacr07.KanColleWrapper.Models.Raw
{
// ReSharper disable InconsistentNaming
public class kcsapi_ndock
{
public int api_member_id { get; set; }
public int api_id { get; set; }
public int api_state { get; set; }
public int api_ship_id { get; set; }
public long api_complete_time { get; set; }
public string api_complete_time_str { get; set; }
public int api_item1 { get; set; }
public int api_item2 { get; set; }
public int api_item3 { get; set; }
public int api_item4 { get; set; }
}
// ReSharper restore InconsistentNaming
}
| 29.2 | 52 | 0.684932 | [
"MIT"
] | kyoryo/test | Grabacr07.KanColleWrapper/Models/Raw/kcsapi_ndock.cs | 586 | C# |
using System;
namespace ProxyPattern
{
class Program
{
static void Main(string[] args)
{
MathProxy proxy = new MathProxy();
Console.WriteLine($"4 + 2 = {proxy.Add(4, 2)}");
Console.WriteLine($"4 - 2 = {proxy.Sub(4, 2)}");
Console.WriteLine($"4 * 2 = {proxy.Multiply(4, 2)}");
Console.WriteLine($"4 / 2 = {proxy.Divide(4, 2)}");
try
{
Console.WriteLine($"4 / 0 = {proxy.Divide(4, 0)}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
| 25.576923 | 67 | 0.452632 | [
"MIT"
] | PhilShishov/Design-Patterns | StructuralPatterns/ProxyPattern/Program.cs | 667 | C# |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Xsl;
using Common.Logging;
using NakedObjects.Architecture.Adapter;
using NakedObjects.Architecture.Component;
using NakedObjects.Architecture.Facet;
using NakedObjects.Architecture.Spec;
using NakedObjects.Architecture.SpecImmutable;
using NakedObjects.Core;
using NakedObjects.Core.Util;
namespace NakedObjects.Snapshot.Xml.Utility {
public class XmlSnapshot : IXmlSnapshot {
private static readonly ILog Log = LogManager.GetLogger(typeof (XmlSnapshot));
private readonly IMetamodelManager metamodelManager;
private readonly INakedObjectManager nakedObjectManager;
private readonly Place rootPlace;
private bool topLevelElementWritten;
// Start a snapshot at the root object, using own namespace manager.
public XmlSnapshot(object obj, INakedObjectManager nakedObjectManager, IMetamodelManager metamodelManager) : this(obj, new XmlSchema(), nakedObjectManager, metamodelManager) {}
// Start a snapshot at the root object, using supplied namespace manager.
public XmlSnapshot(object obj, XmlSchema schema, INakedObjectManager nakedObjectManager, IMetamodelManager metamodelManager) {
this.nakedObjectManager = nakedObjectManager;
this.metamodelManager = metamodelManager;
INakedObjectAdapter rootObjectAdapter = nakedObjectManager.CreateAdapter(obj, null, null);
Schema = schema;
try {
XmlDocument = new XDocument();
XsdDocument = new XDocument();
XsdElement = XsMetaModel.CreateXsSchemaElement(XsdDocument);
rootPlace = AppendXml(rootObjectAdapter);
}
catch (ArgumentException e) {
throw new NakedObjectSystemException(Log.LogAndReturn("Unable to build snapshot"), e);
}
}
public XDocument XmlDocument { get; }
// The root element of GetXmlDocument(). Returns <code>null</code>
// until the snapshot has actually been built.
public XElement XmlElement { get; private set; }
public XDocument XsdDocument { get; }
// The root element of GetXsdDocument(). Returns <code>null</code>
// until the snapshot has actually been built.
public XElement XsdElement { get; }
public XmlSchema Schema { get; }
#region IXmlSnapshot Members
public string Xml {
get {
XElement element = XmlElement;
var sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb)) {
element.WriteTo(writer);
}
return sb.ToString();
}
}
public string Xsd {
get {
XElement element = XsdElement;
var sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb)) {
element.WriteTo(writer);
}
return sb.ToString();
}
}
// The name of the <code>xsi:schemaLocation</code> in the XML document.
//
// Taken from the <code>fullyQualifiedClassName</code> (which also is used
// as the basis for the <code>targetNamespace</code>.
//
// Populated in AppendXml(nakedObjectAdapter).
public string SchemaLocationFileName { get; private set; }
public string TransformedXml(string transform) {
return TransformXml(transform);
}
public string TransformedXsd(string transform) {
return TransformXsd(transform);
}
public void Include(string path) {
Include(path, null);
}
public void Include(string path, string annotation) {
// tokenize into successive fields
List<string> fieldNames = path.Split('/').Select(tok => tok.ToLower()).ToList();
IncludeField(rootPlace, fieldNames, annotation);
}
#endregion
// Start a snapshot at the root object, using own namespace manager.
// Creates an XElement representing this object, and appends it as the root
// element of the Document.
//
// The Document must not yet have a root element Additionally, the supplied
// schemaManager must be populated with any application-level namespaces
// referenced in the document that the parentElement resides within.
// (Normally this is achieved simply by using AppendXml passing in a new
// schemaManager - see ToXml() or XmlSnapshot).
private Place AppendXml(INakedObjectAdapter nakedObjectAdapter) {
string fullyQualifiedClassName = nakedObjectAdapter.Spec.FullName;
Schema.SetUri(fullyQualifiedClassName); // derive URI from fully qualified name
Place place = ObjectToElement(nakedObjectAdapter);
XElement element = place.XmlElement;
var xsElementElement = element.Annotation<XElement>();
XmlDocument.Add(element);
XsdElement.Add(xsElementElement);
Schema.SetTargetNamespace(XsdDocument, fullyQualifiedClassName);
string schemaLocationFileName = fullyQualifiedClassName + ".xsd";
Schema.AssignSchema(XmlDocument, fullyQualifiedClassName, schemaLocationFileName);
XmlElement = element;
SchemaLocationFileName = schemaLocationFileName;
return place;
}
// Creates an XElement representing this object, and appends it to the
// supplied parentElement, provided that an element for the object is not
// already appended.
//
// The method uses the OID to determine if an object's element is already
// present. If the object is not yet persistent, then the hashCode is used
// instead.
//
// The parentElement must have an owner document, and should define the nof
// namespace. Additionally, the supplied schemaManager must be populated
// with any application-level namespaces referenced in the document that the
// parentElement resides within. (Normally this is achieved simply by using
// appendXml passing in a rootElement and a new schemaManager - see
// ToXml() or XmlSnapshot).
private XElement AppendXml(Place parentPlace, INakedObjectAdapter childObjectAdapter) {
XElement parentElement = parentPlace.XmlElement;
var parentXsElement = parentElement.Annotation<XElement>();
if (parentElement.Document != XmlDocument) {
throw new ArgumentException(Log.LogAndReturn("parent XML XElement must have snapshot's XML document as its owner"));
}
Place childPlace = ObjectToElement(childObjectAdapter);
XElement childElement = childPlace.XmlElement;
var childXsElement = childElement.Annotation<XElement>();
childElement = MergeTree(parentElement, childElement);
Schema.AddXsElementIfNotPresent(parentXsElement, childXsElement);
return childElement;
}
private bool AppendXmlThenIncludeRemaining(Place parentPlace, INakedObjectAdapter referencedObjectAdapter, IList<string> fieldNames,
string annotation) {
XElement referencedElement = AppendXml(parentPlace, referencedObjectAdapter);
var referencedPlace = new Place(referencedObjectAdapter, referencedElement);
bool includedField = IncludeField(referencedPlace, fieldNames, annotation);
return includedField;
}
private static IEnumerable<XElement> ElementsUnder(XElement parentElement, string localName) {
return parentElement.Descendants().Where(element => localName.Equals("*") || element.Name.LocalName.Equals(localName));
}
public INakedObjectAdapter GetObject() {
return rootPlace.NakedObjectAdapter;
}
// return true if able to navigate the complete vector of field names
// successfully; false if a field could not be located or it turned
// out to be a value.
private bool IncludeField(Place place, IList<string> fieldNames, string annotation) {
INakedObjectAdapter nakedObjectAdapter = place.NakedObjectAdapter;
XElement xmlElement = place.XmlElement;
// we use a copy of the path so that we can safely traverse collections
// without side-effects
fieldNames = fieldNames.ToList();
// see if we have any fields to process
if (!fieldNames.Any()) {
return true;
}
// take the first field name from the list, and remove
string fieldName = fieldNames.First();
fieldNames.Remove(fieldName);
// locate the field in the object's class
var nos = (IObjectSpec) nakedObjectAdapter.Spec;
IAssociationSpec field = nos.Properties.SingleOrDefault(p => p.Id.ToLower() == fieldName);
if (field == null) {
return false;
}
// locate the corresponding XML element
// (the corresponding XSD element will later be attached to xmlElement
// as its userData)
XElement[] xmlFieldElements = ElementsUnder(xmlElement, field.Id).ToArray();
int fieldCount = xmlFieldElements.Length;
if (fieldCount != 1) {
return false;
}
XElement xmlFieldElement = xmlFieldElements.First();
if (!fieldNames.Any() && annotation != null) {
// nothing left in the path, so we will apply the annotation now
NofMetaModel.SetAnnotationAttribute(xmlFieldElement, annotation);
}
var fieldPlace = new Place(nakedObjectAdapter, xmlFieldElement);
if (field.ReturnSpec.IsParseable) {
return false;
}
var oneToOneAssociation = field as IOneToOneAssociationSpec;
if (oneToOneAssociation != null) {
INakedObjectAdapter referencedObjectAdapter = oneToOneAssociation.GetNakedObject(fieldPlace.NakedObjectAdapter);
if (referencedObjectAdapter == null) {
return true; // not a failure if the reference was null
}
bool appendedXml = AppendXmlThenIncludeRemaining(fieldPlace, referencedObjectAdapter, fieldNames, annotation);
return appendedXml;
}
var oneToManyAssociation = field as IOneToManyAssociationSpec;
if (oneToManyAssociation != null) {
INakedObjectAdapter collection = oneToManyAssociation.GetNakedObject(fieldPlace.NakedObjectAdapter);
INakedObjectAdapter[] collectionAsEnumerable = collection.GetAsEnumerable(nakedObjectManager).ToArray();
bool allFieldsNavigated = true;
foreach (INakedObjectAdapter referencedObject in collectionAsEnumerable) {
bool appendedXml = AppendXmlThenIncludeRemaining(fieldPlace, referencedObject, fieldNames, annotation);
allFieldsNavigated = allFieldsNavigated && appendedXml;
}
return allFieldsNavigated;
}
return false; // fall through, shouldn't get here but just in case.
}
private static string DoLog(string label, object obj) {
return (label ?? "?") + "='" + (obj == null ? "(null)" : obj.ToString()) + "'";
}
// Merges the tree of Elements whose root is <code>childElement</code>
// underneath the <code>parentElement</code>.
//
// If the <code>parentElement</code> already has an element that matches
// the <code>childElement</code>, then recursively attaches the
// grandchildren instead.
//
// The element returned will be either the supplied
// <code>childElement</code>, or an existing child element if one already
// existed under <code>parentElement</code>.
private static XElement MergeTree(XElement parentElement, XElement childElement) {
string childElementOid = NofMetaModel.GetAttribute(childElement, "oid");
if (childElementOid != null) {
// before we add the child element, check to see if it is already
// there
IEnumerable<XElement> existingChildElements = ElementsUnder(parentElement, childElement.Name.LocalName);
foreach (XElement possibleMatchingElement in existingChildElements) {
string possibleMatchOid = NofMetaModel.GetAttribute(possibleMatchingElement, "oid");
if (possibleMatchOid == null || !possibleMatchOid.Equals(childElementOid)) {
continue;
}
// match: transfer the children of the child (grandchildren) to the
// already existing matching child
XElement existingChildElement = possibleMatchingElement;
IEnumerable<XElement> grandchildrenElements = ElementsUnder(childElement, "*");
foreach (XElement grandchildElement in grandchildrenElements) {
grandchildElement.Remove();
MergeTree(existingChildElement, grandchildElement);
}
return existingChildElement;
}
}
parentElement.Add(childElement);
return childElement;
}
public Place ObjectToElement(INakedObjectAdapter nakedObjectAdapter) {
var nos = (IObjectSpec) nakedObjectAdapter.Spec;
XElement element = Schema.CreateElement(XmlDocument, nos.ShortName, nos.FullName, nos.SingularName, nos.PluralName);
NofMetaModel.AppendNofTitle(element, nakedObjectAdapter.TitleString());
XElement xsElement = Schema.CreateXsElementForNofClass(XsdDocument, element, topLevelElementWritten);
// hack: every element in the XSD schema apart from first needs minimum cardinality setting.
topLevelElementWritten = true;
var place = new Place(nakedObjectAdapter, element);
NofMetaModel.SetAttributesForClass(element, OidOrHashCode(nakedObjectAdapter));
IAssociationSpec[] fields = nos.Properties;
var seenFields = new List<string>();
foreach (IAssociationSpec field in fields) {
string fieldName = field.Id;
// Skip field if we have seen the name already
// This is a workaround for getLastActivity(). This method exists
// in AbstractNakedObject, but is not (at some level) being picked up
// by the dot-net reflector as a property. On the other hand it does
// exist as a field in the meta model (NakedObjectSpecification).
//
// Now, to re-expose the lastactivity field for .Net, a deriveLastActivity()
// has been added to BusinessObject. This caused another field ofthe
// same name, ultimately breaking the XSD.
if (seenFields.Contains(fieldName)) {
continue;
}
seenFields.Add(fieldName);
XNamespace ns = Schema.GetUri();
var xmlFieldElement = new XElement(ns + fieldName);
XElement xsdFieldElement;
var oneToOneAssociation = field as IOneToOneAssociationSpec;
var oneToManyAssociation = field as IOneToManyAssociationSpec;
if (field.ReturnSpec.IsParseable && oneToOneAssociation != null) {
IObjectSpec fieldNos = field.ReturnSpec;
// skip fields of type XmlValue
if (fieldNos?.FullName != null && fieldNos.FullName.EndsWith("XmlValue")) {
continue;
}
XElement xmlValueElement = xmlFieldElement; // more meaningful locally scoped name
try {
INakedObjectAdapter value = oneToOneAssociation.GetNakedObject(nakedObjectAdapter);
// a null value would be a programming error, but we protect
// against it anyway
if (value == null) {
continue;
}
ITypeSpec valueNos = value.Spec;
// XML
NofMetaModel.SetAttributesForValue(xmlValueElement, valueNos.ShortName);
bool notEmpty = value.TitleString().Length > 0;
if (notEmpty) {
string valueStr = value.TitleString();
xmlValueElement.Add(new XText(valueStr));
}
else {
NofMetaModel.SetIsEmptyAttribute(xmlValueElement, true);
}
}
catch (Exception) {
Log.Warn("objectToElement(NO): " + DoLog("field", fieldName) + ": getField() threw exception - skipping XML generation");
}
// XSD
xsdFieldElement = Schema.CreateXsElementForNofValue(xsElement, xmlValueElement);
}
else if (oneToOneAssociation != null) {
XElement xmlReferenceElement = xmlFieldElement; // more meaningful locally scoped name
try {
INakedObjectAdapter referencedNakedObjectAdapter = oneToOneAssociation.GetNakedObject(nakedObjectAdapter);
string fullyQualifiedClassName = field.ReturnSpec.FullName;
// XML
NofMetaModel.SetAttributesForReference(xmlReferenceElement, Schema.Prefix, fullyQualifiedClassName);
if (referencedNakedObjectAdapter != null) {
NofMetaModel.AppendNofTitle(xmlReferenceElement, referencedNakedObjectAdapter.TitleString());
}
else {
NofMetaModel.SetIsEmptyAttribute(xmlReferenceElement, true);
}
}
catch (Exception) {
Log.Warn("objectToElement(NO): " + DoLog("field", fieldName) + ": getAssociation() threw exception - skipping XML generation");
}
// XSD
xsdFieldElement = Schema.CreateXsElementForNofReference(xsElement, xmlReferenceElement, oneToOneAssociation.ReturnSpec.FullName);
}
else if (oneToManyAssociation != null) {
XElement xmlCollectionElement = xmlFieldElement; // more meaningful locally scoped name
try {
INakedObjectAdapter collection = oneToManyAssociation.GetNakedObject(nakedObjectAdapter);
ITypeOfFacet facet = collection.GetTypeOfFacetFromSpec();
IObjectSpecImmutable referencedTypeNos = facet.GetValueSpec(collection, metamodelManager.Metamodel);
string fullyQualifiedClassName = referencedTypeNos.FullName;
// XML
NofMetaModel.SetNofCollection(xmlCollectionElement, Schema.Prefix, fullyQualifiedClassName, collection, nakedObjectManager);
}
catch (Exception) {
Log.Warn("objectToElement(NO): " + DoLog("field", fieldName) + ": get(obj) threw exception - skipping XML generation");
}
// XSD
xsdFieldElement = Schema.CreateXsElementForNofCollection(xsElement, xmlCollectionElement, oneToManyAssociation.ReturnSpec.FullName);
}
else {
continue;
}
if (xsdFieldElement != null) {
xmlFieldElement.AddAnnotation(xsdFieldElement);
}
// XML
MergeTree(element, xmlFieldElement);
// XSD
if (xsdFieldElement != null) {
Schema.AddFieldXsElement(xsElement, xsdFieldElement);
}
}
return place;
}
private static string OidOrHashCode(INakedObjectAdapter nakedObjectAdapter) {
IOid oid = nakedObjectAdapter.Oid;
if (oid == null) {
return "" + nakedObjectAdapter.GetHashCode();
}
return oid.ToString();
}
private static string Transform(XDocument xDoc, string transform) {
var sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb)) {
var compiledTransform = new XslCompiledTransform();
compiledTransform.Load(XmlReader.Create(new StringReader(transform)));
compiledTransform.Transform(xDoc.CreateReader(), writer);
}
return sb.ToString();
}
public string TransformXml(string transform) {
return Transform(XmlDocument, transform);
}
public string TransformXsd(string transform) {
return Transform(XsdDocument, transform);
}
}
} | 42.701887 | 184 | 0.604145 | [
"Apache-2.0"
] | Giovanni-Russo-Boscoli/NakedObjectsFramework | Core/NakedObjects.Snapshot.Xml/utility/XmlSnapshot.cs | 22,634 | C# |
/*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Copyright (C) 2009-2010 Michael Möller <mmoeller@openhardwaremonitor.org>
*/
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using OpenHardwareMonitor.GUI;
namespace OpenHardwareMonitor {
public static class Program {
[STAThread]
public static void Main() {
#if !DEBUG
Application.ThreadException +=
new ThreadExceptionEventHandler(Application_ThreadException);
Application.SetUnhandledExceptionMode(
UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
if (!AllRequiredFilesAvailable())
Environment.Exit(0);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (GUI.MainForm form = new GUI.MainForm()) {
form.FormClosed += delegate(Object sender, FormClosedEventArgs e) {
Application.Exit();
};
Application.Run();
}
}
private static bool IsFileAvailable(string fileName) {
string path = Path.GetDirectoryName(Application.ExecutablePath) +
Path.DirectorySeparatorChar;
if (!File.Exists(path + fileName)) {
MessageBox.Show("The following file could not be found: " + fileName +
"\nPlease extract all files from the archive.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true;
}
private static bool AllRequiredFilesAvailable() {
if (!IsFileAvailable("Aga.Controls.dll"))
return false;
if (!IsFileAvailable("OpenHardwareMonitorLib.dll"))
return false;
return true;
}
private static void ReportException(Exception e) {
CrashForm form = new CrashForm();
form.Exception = e;
form.ShowDialog();
}
public static void Application_ThreadException(object sender,
ThreadExceptionEventArgs e)
{
try {
ReportException(e.Exception);
} catch {
} finally {
Application.Exit();
}
}
public static void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs args)
{
try {
Exception e = args.ExceptionObject as Exception;
if (e != null)
ReportException(e);
} catch {
} finally {
Environment.Exit(0);
}
}
}
}
| 28.535354 | 80 | 0.627257 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | paooer/open-hardware-monitor | Program.cs | 2,828 | C# |
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
//------------------------------------------------------------------------------
// <copyright company="DMV">
// Copyright 2014 Ded Medved
//
// 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>
//------------------------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.SqlServer.TransactSql.ScriptDom;
using System.Linq;
namespace Cheburashka
{
internal class EnforceUniqueTableAliasVisitor : TSqlConcreteFragmentVisitor, ICheburashkaTSqlConcreteFragmentVisitor
{
public EnforceUniqueTableAliasVisitor()
{
TableAliases = new List<Identifier>();
}
public List<Identifier> TableAliases { get; }
public IList<TSqlFragment> SqlFragments() { return TableAliases.ToList().Cast<TSqlFragment>().ToList(); }
public override void ExplicitVisit(AdHocTableReference node) { HandleNode(node); }
public override void ExplicitVisit(BuiltInFunctionTableReference node) { HandleNode(node); }
public override void ExplicitVisit(FullTextTableReference node) { HandleNode(node); }
public override void ExplicitVisit(InternalOpenRowset node) { HandleNode(node); }
// I can't believe I need to do this to prevent it picking up the TableReferences which doesn't carry an alias
public override void ExplicitVisit(MergeSpecification node)
{
if (node.TableAlias is not null)
{
TableAliases.Add(node.TableAlias);
}
node.TableReference.Accept(this);
node.SearchCondition.Accept(this);
foreach (var clause in node.ActionClauses)
{
clause.Accept(this);
}
}
// this clause is broken for merge statement target nodes
public override void ExplicitVisit(NamedTableReference node) { HandleNode(node); }
public override void ExplicitVisit(OpenJsonTableReference node) { HandleNode(node); }
public override void ExplicitVisit(OpenQueryTableReference node) { HandleNode(node); }
public override void ExplicitVisit(OpenRowsetTableReference node) { HandleNode(node); }
public override void ExplicitVisit(OpenXmlTableReference node) { HandleNode(node); }
public override void ExplicitVisit(PivotedTableReference node) { HandleNode(node); }
public override void ExplicitVisit(SemanticTableReference node) { HandleNode(node); }
public override void ExplicitVisit(UnpivotedTableReference node) { HandleNode(node); }
public override void ExplicitVisit(VariableTableReference node) { HandleNode(node); }
public override void ExplicitVisit(BulkOpenRowset node) { HandleNode(node); }
public override void ExplicitVisit(ChangeTableChangesTableReference node) { HandleNode(node); }
public override void ExplicitVisit(ChangeTableVersionTableReference node) { HandleNode(node); }
public override void ExplicitVisit(DataModificationTableReference node) { HandleNode(node); }
public override void ExplicitVisit(InlineDerivedTable node) { HandleNode(node); }
public override void ExplicitVisit(QueryDerivedTable node) { HandleNode(node); }
public override void ExplicitVisit(SchemaObjectFunctionTableReference node) { HandleNode(node); }
public override void ExplicitVisit(VariableMethodCallTableReference node) { HandleNode(node); }
private void HandleNode(TableReferenceWithAliasAndColumns node)
{
if (node.Alias is not null)
{
TableAliases.Add(node.Alias);
}
node.AcceptChildren(this);
}
private void HandleNode(TableReferenceWithAlias node)
{
if (node.Alias is not null)
{
TableAliases.Add(node.Alias);
}
node.AcceptChildren(this);
}
}
} | 50.912088 | 120 | 0.668681 | [
"Apache-2.0"
] | dedmedved/cheburashka | Cheburashka/Rules/CategoryLaxCode/EnforceUniqueTableAliasRule/EnforceUniqueTableAliasVisitor.cs | 4,635 | C# |
using System;
using System.Threading;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("My super program!!!!!");
Console.WriteLine("What's your name?");
new QuestionsForPicture();
//Readline and exit
Console.ReadLine();
}
}
}
| 14.423077 | 55 | 0.512 | [
"MIT"
] | FirstsSecond/myfirstconsoleapp | Program.cs | 377 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/wingdi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="EMREXTCREATEFONTINDIRECTW" /> struct.</summary>
public static unsafe class EMREXTCREATEFONTINDIRECTWTests
{
/// <summary>Validates that the <see cref="EMREXTCREATEFONTINDIRECTW" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<EMREXTCREATEFONTINDIRECTW>(), Is.EqualTo(sizeof(EMREXTCREATEFONTINDIRECTW)));
}
/// <summary>Validates that the <see cref="EMREXTCREATEFONTINDIRECTW" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(EMREXTCREATEFONTINDIRECTW).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="EMREXTCREATEFONTINDIRECTW" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(EMREXTCREATEFONTINDIRECTW), Is.EqualTo(332));
}
}
}
| 40.583333 | 145 | 0.687201 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/um/wingdi/EMREXTCREATEFONTINDIRECTWTests.cs | 1,463 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.Storage.Outputs
{
[OutputType]
public sealed class BlobInventoryPolicyRuleFilter
{
/// <summary>
/// A set of blob types. Possible values are `blockBlob`, `appendBlob`, and `pageBlob`. The storage account with `is_hns_enabled` is `true` doesn't support `pageBlob`.
/// </summary>
public readonly ImmutableArray<string> BlobTypes;
/// <summary>
/// Includes blob versions in blob inventory or not? Defaults to `false`.
/// </summary>
public readonly bool? IncludeBlobVersions;
/// <summary>
/// Includes blob snapshots in blob inventory or not? Defaults to `false`.
/// </summary>
public readonly bool? IncludeSnapshots;
/// <summary>
/// A set of strings for blob prefixes to be matched.
/// </summary>
public readonly ImmutableArray<string> PrefixMatches;
[OutputConstructor]
private BlobInventoryPolicyRuleFilter(
ImmutableArray<string> blobTypes,
bool? includeBlobVersions,
bool? includeSnapshots,
ImmutableArray<string> prefixMatches)
{
BlobTypes = blobTypes;
IncludeBlobVersions = includeBlobVersions;
IncludeSnapshots = includeSnapshots;
PrefixMatches = prefixMatches;
}
}
}
| 33.92 | 175 | 0.642689 | [
"ECL-2.0",
"Apache-2.0"
] | ScriptBox99/pulumi-azure | sdk/dotnet/Storage/Outputs/BlobInventoryPolicyRuleFilter.cs | 1,696 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace AscheLib.UniMonad {
public static partial class State {
private class PutGetCore<TState> : IStateMonad<TState, TState> {
TState _state;
public PutGetCore(TState state) {
_state = state;
}
public StateResult<TState, TState> RunState(TState state) {
return StateResult.Create(_state, _state);
}
}
public static IStateMonad<TState, TState> PutGet<TState>(TState state) {
return new PutGetCore<TState>(state);
}
}
} | 26.3 | 74 | 0.724335 | [
"MIT"
] | AscheLab/AscheLib.UniMonad | Assets/AscheLib/UniMonad/Monad/State/State.PutGet.cs | 528 | C# |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: search.proto
#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;
/// <summary>Holder for reflection information generated from search.proto</summary>
public static partial class SearchReflection {
#region Descriptor
/// <summary>File descriptor for search.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static SearchReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgxzZWFyY2gucHJvdG8iGAoHUmVxdWVzdBINCgVxdWVyeRgBIAEoCSJCCgZS",
"ZXN1bHQSDQoFdGl0bGUYASABKAkSCwoDdXJsGAIgASgJEg8KB3NuaXBwZXQY",
"AyABKAkSCwoDbG9nGAQgASgJMicKBkdvb2dsZRIdCgZTZWFyY2gSCC5SZXF1",
"ZXN0GgcuUmVzdWx0IgBiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Request), global::Request.Parser, new[]{ "Query" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Result), global::Result.Parser, new[]{ "Title", "Url", "Snippet", "Log" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class Request : pb::IMessage<Request> {
private static readonly pb::MessageParser<Request> _parser = new pb::MessageParser<Request>(() => new Request());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Request> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::SearchReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Request() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Request(Request other) : this() {
query_ = other.query_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Request Clone() {
return new Request(this);
}
/// <summary>Field number for the "query" field.</summary>
public const int QueryFieldNumber = 1;
private string query_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Query {
get { return query_; }
set {
query_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Request);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Request other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Query != other.Query) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Query.Length != 0) hash ^= Query.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 (Query.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Query);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Query.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Query);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Request other) {
if (other == null) {
return;
}
if (other.Query.Length != 0) {
Query = other.Query;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Query = input.ReadString();
break;
}
}
}
}
}
public sealed partial class Result : pb::IMessage<Result> {
private static readonly pb::MessageParser<Result> _parser = new pb::MessageParser<Result>(() => new Result());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Result> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::SearchReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Result() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Result(Result other) : this() {
title_ = other.title_;
url_ = other.url_;
snippet_ = other.snippet_;
log_ = other.log_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Result Clone() {
return new Result(this);
}
/// <summary>Field number for the "title" field.</summary>
public const int TitleFieldNumber = 1;
private string title_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Title {
get { return title_; }
set {
title_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "url" field.</summary>
public const int UrlFieldNumber = 2;
private string url_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Url {
get { return url_; }
set {
url_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "snippet" field.</summary>
public const int SnippetFieldNumber = 3;
private string snippet_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Snippet {
get { return snippet_; }
set {
snippet_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "log" field.</summary>
public const int LogFieldNumber = 4;
private string log_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Log {
get { return log_; }
set {
log_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Result);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Result other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Title != other.Title) return false;
if (Url != other.Url) return false;
if (Snippet != other.Snippet) return false;
if (Log != other.Log) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Title.Length != 0) hash ^= Title.GetHashCode();
if (Url.Length != 0) hash ^= Url.GetHashCode();
if (Snippet.Length != 0) hash ^= Snippet.GetHashCode();
if (Log.Length != 0) hash ^= Log.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 (Title.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Title);
}
if (Url.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Url);
}
if (Snippet.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Snippet);
}
if (Log.Length != 0) {
output.WriteRawTag(34);
output.WriteString(Log);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Title.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Title);
}
if (Url.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Url);
}
if (Snippet.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Snippet);
}
if (Log.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Log);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Result other) {
if (other == null) {
return;
}
if (other.Title.Length != 0) {
Title = other.Title;
}
if (other.Url.Length != 0) {
Url = other.Url;
}
if (other.Snippet.Length != 0) {
Snippet = other.Snippet;
}
if (other.Log.Length != 0) {
Log = other.Log;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Title = input.ReadString();
break;
}
case 18: {
Url = input.ReadString();
break;
}
case 26: {
Snippet = input.ReadString();
break;
}
case 34: {
Log = input.ReadString();
break;
}
}
}
}
}
#endregion
#endregion Designer generated code
| 28.986111 | 147 | 0.668424 | [
"MIT"
] | iljoong/msa-goapp | src/fedotnet/Search.cs | 10,435 | C# |
using DN.WebApi.Application.Common.Events;
using DN.WebApi.Application.Common.Notifications;
using DN.WebApi.Domain.Catalog.Brands;
using DN.WebApi.Domain.Catalog.Products;
using DN.WebApi.Domain.Common.Contracts;
using DN.WebApi.Shared.Notifications;
using MediatR;
using Microsoft.Extensions.Logging;
namespace DN.WebApi.Application.Dashboard;
// TODO: handle registerd users and registered roles create/delete
public class SendStatsChangedNotificationHandler :
INotificationHandler<EventNotification<BrandCreatedEvent>>,
INotificationHandler<EventNotification<BrandDeletedEvent>>,
INotificationHandler<EventNotification<ProductCreatedEvent>>,
INotificationHandler<EventNotification<ProductDeletedEvent>>
{
private readonly ILogger<SendStatsChangedNotificationHandler> _logger;
private readonly INotificationService _notificationService;
public SendStatsChangedNotificationHandler(ILogger<SendStatsChangedNotificationHandler> logger, INotificationService notificationService) =>
(_logger, _notificationService) = (logger, notificationService);
public Task Handle(EventNotification<BrandCreatedEvent> notification, CancellationToken cancellationToken) =>
SendStatsChangedNotification(notification.DomainEvent, cancellationToken);
public Task Handle(EventNotification<BrandDeletedEvent> notification, CancellationToken cancellationToken) =>
SendStatsChangedNotification(notification.DomainEvent, cancellationToken);
public Task Handle(EventNotification<ProductCreatedEvent> notification, CancellationToken cancellationToken) =>
SendStatsChangedNotification(notification.DomainEvent, cancellationToken);
public Task Handle(EventNotification<ProductDeletedEvent> notification, CancellationToken cancellationToken) =>
SendStatsChangedNotification(notification.DomainEvent, cancellationToken);
private Task SendStatsChangedNotification(DomainEvent domainEvent, CancellationToken cancellationToken)
{
_logger.LogInformation("{event} Triggered", domainEvent.GetType().Name);
return _notificationService.SendMessageAsync(new StatsChangedNotification(), cancellationToken);
}
} | 50.930233 | 144 | 0.825571 | [
"MIT"
] | AppSlope/dotnet-webapi-boilerplate | src/Core/Application/Dashboard/SendStatsChangedNotificationHandler.cs | 2,190 | 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 kinesisanalyticsv2-2018-05-23.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.KinesisAnalyticsV2.Model
{
///<summary>
/// KinesisAnalyticsV2 exception
/// </summary>
#if !PCL && !CORECLR
[Serializable]
#endif
public class InvalidRequestException : AmazonKinesisAnalyticsV2Exception
{
/// <summary>
/// Constructs a new InvalidRequestException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InvalidRequestException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InvalidRequestException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InvalidRequestException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InvalidRequestException
/// </summary>
/// <param name="innerException"></param>
public InvalidRequestException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InvalidRequestException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidRequestException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InvalidRequestException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidRequestException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !CORECLR
/// <summary>
/// Constructs a new instance of the InvalidRequestException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected InvalidRequestException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 43.175258 | 178 | 0.65043 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/KinesisAnalyticsV2/Generated/Model/InvalidRequestException.cs | 4,188 | C# |
using System;
using SolrNet;
using System.Collections.Generic;
using System.Linq;
namespace HealthKitServer.Server
{
public class HealthKidDataSolrConnection : IHealthKitDataStorage
{
private readonly ISolrOperations<HealthKitData> m_solrServer;
public HealthKidDataSolrConnection (string connectionString)
{
Startup.Init<HealthKitData>(connectionString);
}
public IEnumerable<HealthKitData> GetAllHealthKitData ()
{
return m_solrServer.Query (new SolrQuery ("*:*")).ToArray();
}
public IEnumerable<HealthKitData> GetSpesificHealthKitData (int id)
{
throw new NotImplementedException ();
}
public HealthKitData GetSpesificHealthKitDataRecord(int personId, int recordId)
{
throw new NotImplementedException ();
}
public void AddOrUpdateHealthKitDataToStorage (HealthKitData person)
{
m_solrServer.Add (person);
}
}
}
| 21.365854 | 81 | 0.767123 | [
"MIT"
] | andmos/HealthKitServer | HealthKitServer.Server/Services/HealthKidDataSolrConnection.cs | 878 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.JsonV4.Linq;
namespace Newtonsoft.JsonV4.Tests.Documentation.Samples.Linq
{
public class Clone
{
public void Example()
{
#region Usage
JObject o1 = new JObject
{
{ "String", "A string!" },
{ "Items", new JArray(1, 2) }
};
Console.WriteLine(o1.ToString());
// {
// "String": "A string!",
// "Items": [
// 1,
// 2
// ]
// }
JObject o2 = (JObject)o1.DeepClone();
Console.WriteLine(o2.ToString());
// {
// "String": "A string!",
// "Items": [
// 1,
// 2
// ]
// }
Console.WriteLine(JToken.DeepEquals(o1, o2));
// true
Console.WriteLine(Object.ReferenceEquals(o1, o2));
// false
#endregion
}
}
} | 23.083333 | 62 | 0.41065 | [
"MIT"
] | woodp/Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/Clone.cs | 1,110 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.TestFramework;
using Azure.ResourceManager.Resources.Models;
using NUnit.Framework;
namespace Azure.ResourceManager.Resources.Tests
{
public class TemplateSpecVersionCollectionTests : ResourcesTestBase
{
public TemplateSpecVersionCollectionTests(bool isAsync)
: base(isAsync)//, RecordedTestMode.Record)
{
}
[TestCase]
[RecordedTest]
public async Task CreateOrUpdate()
{
Subscription subscription = await Client.GetDefaultSubscriptionAsync();
string rgName = Recording.GenerateAssetName("testRg-1-");
ResourceGroupData rgData = new ResourceGroupData(AzureLocation.WestUS2);
var lro = await subscription.GetResourceGroups().CreateOrUpdateAsync(WaitUntil.Completed, rgName, rgData);
ResourceGroup rg = lro.Value;
string templateSpecName = Recording.GenerateAssetName("templateSpec-C-");
TemplateSpecData templateSpecData = CreateTemplateSpecData(templateSpecName);
TemplateSpec templateSpec = (await rg.GetTemplateSpecs().CreateOrUpdateAsync(WaitUntil.Completed, templateSpecName, templateSpecData)).Value;
const string version = "v1";
TemplateSpecVersionData templateSpecVersionData = CreateTemplateSpecVersionData();
TemplateSpecVersion templateSpecVersion = (await templateSpec.GetTemplateSpecVersions().CreateOrUpdateAsync(WaitUntil.Completed, version, templateSpecVersionData)).Value;
Assert.AreEqual(version, templateSpecVersion.Data.Name);
Assert.ThrowsAsync<ArgumentNullException>(async () => _ = await rg.GetTemplateSpecs().CreateOrUpdateAsync(WaitUntil.Completed, null, templateSpecData));
Assert.ThrowsAsync<ArgumentNullException>(async () => _ = await rg.GetTemplateSpecs().CreateOrUpdateAsync(WaitUntil.Completed, templateSpecName, null));
}
[TestCase]
[RecordedTest]
public async Task List()
{
Subscription subscription = await Client.GetDefaultSubscriptionAsync();
string rgName = Recording.GenerateAssetName("testRg-2-");
ResourceGroupData rgData = new ResourceGroupData(AzureLocation.WestUS2);
var lro = await subscription.GetResourceGroups().CreateOrUpdateAsync(WaitUntil.Completed, rgName, rgData);
ResourceGroup rg = lro.Value;
string templateSpecName = Recording.GenerateAssetName("templateSpec-L-");
TemplateSpecData templateSpecData = CreateTemplateSpecData(templateSpecName);
TemplateSpec templateSpec = (await rg.GetTemplateSpecs().CreateOrUpdateAsync(WaitUntil.Completed, templateSpecName, templateSpecData)).Value;
const string version = "v1";
TemplateSpecVersionData templateSpecVersionData = CreateTemplateSpecVersionData();
_ = (await templateSpec.GetTemplateSpecVersions().CreateOrUpdateAsync(WaitUntil.Completed, version, templateSpecVersionData)).Value;
int count = 0;
await foreach (var tempTemplateSpecVersion in templateSpec.GetTemplateSpecVersions().GetAllAsync())
{
count++;
}
Assert.AreEqual(count, 1);
}
[TestCase]
[RecordedTest]
public async Task Get()
{
Subscription subscription = await Client.GetDefaultSubscriptionAsync();
string rgName = Recording.GenerateAssetName("testRg-3-");
ResourceGroupData rgData = new ResourceGroupData(AzureLocation.WestUS2);
var lro = await subscription.GetResourceGroups().CreateOrUpdateAsync(WaitUntil.Completed, rgName, rgData);
ResourceGroup rg = lro.Value;
string templateSpecName = Recording.GenerateAssetName("templateSpec-G-");
TemplateSpecData templateSpecData = CreateTemplateSpecData(templateSpecName);
TemplateSpec templateSpec = (await rg.GetTemplateSpecs().CreateOrUpdateAsync(WaitUntil.Completed, templateSpecName, templateSpecData)).Value;
const string version = "v1";
TemplateSpecVersionData templateSpecVersionData = CreateTemplateSpecVersionData();
TemplateSpecVersion templateSpecVersion = (await templateSpec.GetTemplateSpecVersions().CreateOrUpdateAsync(WaitUntil.Completed, version, templateSpecVersionData)).Value;
TemplateSpecVersion getTemplateSpecVersion = await templateSpec.GetTemplateSpecVersions().GetAsync(version);
AssertValidTemplateSpecVersion(templateSpecVersion, getTemplateSpecVersion);
Assert.ThrowsAsync<ArgumentNullException>(async () => _ = await templateSpec.GetTemplateSpecVersions().GetAsync(null));
}
private static void AssertValidTemplateSpecVersion(TemplateSpecVersion model, TemplateSpecVersion getResult)
{
Assert.AreEqual(model.Data.Name, getResult.Data.Name);
Assert.AreEqual(model.Data.Id, getResult.Data.Id);
Assert.AreEqual(model.Data.ResourceType, getResult.Data.ResourceType);
Assert.AreEqual(model.Data.Location, getResult.Data.Location);
Assert.AreEqual(model.Data.Tags, getResult.Data.Tags);
Assert.AreEqual(model.Data.Description, getResult.Data.Description);
Assert.AreEqual(model.Data.LinkedTemplates.Count, getResult.Data.LinkedTemplates.Count);
for (int i = 0; i < model.Data.LinkedTemplates.Count; ++i)
{
Assert.AreEqual(model.Data.LinkedTemplates[i].Path, getResult.Data.LinkedTemplates[i].Path);
Assert.AreEqual(model.Data.LinkedTemplates[i].Template, getResult.Data.LinkedTemplates[i].Template);
}
Assert.AreEqual(model.Data.Metadata, getResult.Data.Metadata);
Assert.AreEqual(model.Data.MainTemplate.ToArray(), getResult.Data.MainTemplate.ToArray());
Assert.AreEqual(model.Data.UiFormDefinition, getResult.Data.UiFormDefinition);
}
}
}
| 60.048544 | 182 | 0.706386 | [
"MIT"
] | Ramananaidu/dotnet-sonarqube | sdk/resources/Azure.ResourceManager.Resources/tests/Scenario/TemplateSpecVersionCollectionTests.cs | 6,187 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace Microsoft.AspNetCore.Razor.Language;
public class DefaultRazorCodeDocumentTest
{
[Fact]
public void Ctor()
{
// Arrange
var source = TestRazorSourceDocument.Create();
var imports = new RazorSourceDocument[]
{
TestRazorSourceDocument.Create(),
};
// Act
var code = new DefaultRazorCodeDocument(source, imports);
// Assert
Assert.Same(source, code.Source);
Assert.NotNull(code.Items);
Assert.NotSame(imports, code.Imports);
Assert.Collection(imports, d => Assert.Same(imports[0], d));
}
[Fact]
public void Ctor_AllowsNullForImports()
{
// Arrange
var source = TestRazorSourceDocument.Create();
// Act
var code = new DefaultRazorCodeDocument(source, imports: null);
// Assert
Assert.Same(source, code.Source);
Assert.NotNull(code.Items);
Assert.Empty(code.Imports);
}
}
| 24.382979 | 71 | 0.620419 | [
"MIT"
] | MitrichDot/aspnetcore | src/Razor/Microsoft.AspNetCore.Razor.Language/test/DefaultRazorCodeDocumentTest.cs | 1,148 | C# |
using System;
using System.Collections.Generic;
using Android.Runtime;
using Java.Interop;
namespace Com.Payment.Paymentsdk.Integrationmodels {
// Metadata.xml XPath class reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']"
[global::Android.Runtime.Register ("com/payment/paymentsdk/integrationmodels/PaymentSdkTransactionDetails", DoNotGenerateAcw=true)]
public sealed partial class PaymentSdkTransactionDetails : global::Java.Lang.Object {
static readonly JniPeerMembers _members = new XAPeerMembers ("com/payment/paymentsdk/integrationmodels/PaymentSdkTransactionDetails", typeof (PaymentSdkTransactionDetails));
internal static IntPtr class_ref {
get { return _members.JniPeerType.PeerReference.Handle; }
}
[global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)]
[global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)]
public override global::Java.Interop.JniPeerMembers JniPeerMembers {
get { return _members; }
}
[global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)]
[global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)]
protected override IntPtr ThresholdClass {
get { return _members.JniPeerType.PeerReference.Handle; }
}
[global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)]
[global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)]
protected override global::System.Type ThresholdType {
get { return _members.ManagedPeerType; }
}
internal PaymentSdkTransactionDetails (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer)
{
}
// Metadata.xml XPath constructor reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/constructor[@name='PaymentSdkTransactionDetails' and count(parameter)=0]"
[Register (".ctor", "()V", "")]
public unsafe PaymentSdkTransactionDetails () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
const string __id = "()V";
if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero)
return;
try {
var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), null);
SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef);
_members.InstanceMethods.FinishCreateInstance (__id, this, null);
} finally {
}
}
// Metadata.xml XPath constructor reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/constructor[@name='PaymentSdkTransactionDetails' and count(parameter)=15 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='java.lang.String'] and parameter[5][@type='java.lang.String'] and parameter[6][@type='java.lang.String'] and parameter[7][@type='java.lang.String'] and parameter[8][@type='com.payment.paymentsdk.integrationmodels.PaymentSdkPaymentResult'] and parameter[9][@type='com.payment.paymentsdk.integrationmodels.PaymentSdkPaymentInfo'] and parameter[10][@type='java.lang.String'] and parameter[11][@type='java.lang.String'] and parameter[12][@type='java.lang.String'] and parameter[13][@type='java.lang.String'] and parameter[14][@type='com.payment.paymentsdk.integrationmodels.PaymentSdkBillingDetails'] and parameter[15][@type='com.payment.paymentsdk.integrationmodels.PaymentSdkShippingDetails']]"
[Register (".ctor", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentResult;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentInfo;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkBillingDetails;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkShippingDetails;)V", "")]
public unsafe PaymentSdkTransactionDetails (string transactionReference, string transactionType, string cartID, string cartDescription, string cartCurrency, string cartAmount, string payResponseReturn, global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentResult paymentResult, global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentInfo paymentInfo, string redirectUrl, string errorCode, string errorMsg, string token, global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkBillingDetails billingDetails, global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkShippingDetails shippingDetails) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
const string __id = "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentResult;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentInfo;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkBillingDetails;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkShippingDetails;)V";
if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero)
return;
IntPtr native_transactionReference = JNIEnv.NewString (transactionReference);
IntPtr native_transactionType = JNIEnv.NewString (transactionType);
IntPtr native_cartID = JNIEnv.NewString (cartID);
IntPtr native_cartDescription = JNIEnv.NewString (cartDescription);
IntPtr native_cartCurrency = JNIEnv.NewString (cartCurrency);
IntPtr native_cartAmount = JNIEnv.NewString (cartAmount);
IntPtr native_payResponseReturn = JNIEnv.NewString (payResponseReturn);
IntPtr native_redirectUrl = JNIEnv.NewString (redirectUrl);
IntPtr native_errorCode = JNIEnv.NewString (errorCode);
IntPtr native_errorMsg = JNIEnv.NewString (errorMsg);
IntPtr native_token = JNIEnv.NewString (token);
try {
JniArgumentValue* __args = stackalloc JniArgumentValue [15];
__args [0] = new JniArgumentValue (native_transactionReference);
__args [1] = new JniArgumentValue (native_transactionType);
__args [2] = new JniArgumentValue (native_cartID);
__args [3] = new JniArgumentValue (native_cartDescription);
__args [4] = new JniArgumentValue (native_cartCurrency);
__args [5] = new JniArgumentValue (native_cartAmount);
__args [6] = new JniArgumentValue (native_payResponseReturn);
__args [7] = new JniArgumentValue ((paymentResult == null) ? IntPtr.Zero : ((global::Java.Lang.Object) paymentResult).Handle);
__args [8] = new JniArgumentValue ((paymentInfo == null) ? IntPtr.Zero : ((global::Java.Lang.Object) paymentInfo).Handle);
__args [9] = new JniArgumentValue (native_redirectUrl);
__args [10] = new JniArgumentValue (native_errorCode);
__args [11] = new JniArgumentValue (native_errorMsg);
__args [12] = new JniArgumentValue (native_token);
__args [13] = new JniArgumentValue ((billingDetails == null) ? IntPtr.Zero : ((global::Java.Lang.Object) billingDetails).Handle);
__args [14] = new JniArgumentValue ((shippingDetails == null) ? IntPtr.Zero : ((global::Java.Lang.Object) shippingDetails).Handle);
var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args);
SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef);
_members.InstanceMethods.FinishCreateInstance (__id, this, __args);
} finally {
JNIEnv.DeleteLocalRef (native_transactionReference);
JNIEnv.DeleteLocalRef (native_transactionType);
JNIEnv.DeleteLocalRef (native_cartID);
JNIEnv.DeleteLocalRef (native_cartDescription);
JNIEnv.DeleteLocalRef (native_cartCurrency);
JNIEnv.DeleteLocalRef (native_cartAmount);
JNIEnv.DeleteLocalRef (native_payResponseReturn);
JNIEnv.DeleteLocalRef (native_redirectUrl);
JNIEnv.DeleteLocalRef (native_errorCode);
JNIEnv.DeleteLocalRef (native_errorMsg);
JNIEnv.DeleteLocalRef (native_token);
global::System.GC.KeepAlive (paymentResult);
global::System.GC.KeepAlive (paymentInfo);
global::System.GC.KeepAlive (billingDetails);
global::System.GC.KeepAlive (shippingDetails);
}
}
public unsafe global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkBillingDetails BillingDetails {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getBillingDetails' and count(parameter)=0]"
[Register ("getBillingDetails", "()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkBillingDetails;", "")]
get {
const string __id = "getBillingDetails.()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkBillingDetails;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkBillingDetails> (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string CartAmount {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getCartAmount' and count(parameter)=0]"
[Register ("getCartAmount", "()Ljava/lang/String;", "")]
get {
const string __id = "getCartAmount.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string CartCurrency {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getCartCurrency' and count(parameter)=0]"
[Register ("getCartCurrency", "()Ljava/lang/String;", "")]
get {
const string __id = "getCartCurrency.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string CartDescription {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getCartDescription' and count(parameter)=0]"
[Register ("getCartDescription", "()Ljava/lang/String;", "")]
get {
const string __id = "getCartDescription.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string CartID {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getCartID' and count(parameter)=0]"
[Register ("getCartID", "()Ljava/lang/String;", "")]
get {
const string __id = "getCartID.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string ErrorCode {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getErrorCode' and count(parameter)=0]"
[Register ("getErrorCode", "()Ljava/lang/String;", "")]
get {
const string __id = "getErrorCode.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string ErrorMsg {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getErrorMsg' and count(parameter)=0]"
[Register ("getErrorMsg", "()Ljava/lang/String;", "")]
get {
const string __id = "getErrorMsg.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string PayResponseReturn {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getPayResponseReturn' and count(parameter)=0]"
[Register ("getPayResponseReturn", "()Ljava/lang/String;", "")]
get {
const string __id = "getPayResponseReturn.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentInfo PaymentInfo {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getPaymentInfo' and count(parameter)=0]"
[Register ("getPaymentInfo", "()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentInfo;", "")]
get {
const string __id = "getPaymentInfo.()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentInfo;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentInfo> (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentResult PaymentResult {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getPaymentResult' and count(parameter)=0]"
[Register ("getPaymentResult", "()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentResult;", "")]
get {
const string __id = "getPaymentResult.()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentResult;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentResult> (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string RedirectUrl {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getRedirectUrl' and count(parameter)=0]"
[Register ("getRedirectUrl", "()Ljava/lang/String;", "")]
get {
const string __id = "getRedirectUrl.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkShippingDetails ShippingDetails {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getShippingDetails' and count(parameter)=0]"
[Register ("getShippingDetails", "()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkShippingDetails;", "")]
get {
const string __id = "getShippingDetails.()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkShippingDetails;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkShippingDetails> (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string Token {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getToken' and count(parameter)=0]"
[Register ("getToken", "()Ljava/lang/String;", "")]
get {
const string __id = "getToken.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string TransactionReference {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getTransactionReference' and count(parameter)=0]"
[Register ("getTransactionReference", "()Ljava/lang/String;", "")]
get {
const string __id = "getTransactionReference.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
public unsafe string TransactionType {
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='getTransactionType' and count(parameter)=0]"
[Register ("getTransactionType", "()Ljava/lang/String;", "")]
get {
const string __id = "getTransactionType.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component1' and count(parameter)=0]"
[Register ("component1", "()Ljava/lang/String;", "")]
public unsafe string Component1 ()
{
const string __id = "component1.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component10' and count(parameter)=0]"
[Register ("component10", "()Ljava/lang/String;", "")]
public unsafe string Component10 ()
{
const string __id = "component10.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component11' and count(parameter)=0]"
[Register ("component11", "()Ljava/lang/String;", "")]
public unsafe string Component11 ()
{
const string __id = "component11.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component12' and count(parameter)=0]"
[Register ("component12", "()Ljava/lang/String;", "")]
public unsafe string Component12 ()
{
const string __id = "component12.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component13' and count(parameter)=0]"
[Register ("component13", "()Ljava/lang/String;", "")]
public unsafe string Component13 ()
{
const string __id = "component13.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component14' and count(parameter)=0]"
[Register ("component14", "()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkBillingDetails;", "")]
public unsafe global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkBillingDetails Component14 ()
{
const string __id = "component14.()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkBillingDetails;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkBillingDetails> (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component15' and count(parameter)=0]"
[Register ("component15", "()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkShippingDetails;", "")]
public unsafe global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkShippingDetails Component15 ()
{
const string __id = "component15.()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkShippingDetails;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkShippingDetails> (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component2' and count(parameter)=0]"
[Register ("component2", "()Ljava/lang/String;", "")]
public unsafe string Component2 ()
{
const string __id = "component2.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component3' and count(parameter)=0]"
[Register ("component3", "()Ljava/lang/String;", "")]
public unsafe string Component3 ()
{
const string __id = "component3.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component4' and count(parameter)=0]"
[Register ("component4", "()Ljava/lang/String;", "")]
public unsafe string Component4 ()
{
const string __id = "component4.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component5' and count(parameter)=0]"
[Register ("component5", "()Ljava/lang/String;", "")]
public unsafe string Component5 ()
{
const string __id = "component5.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component6' and count(parameter)=0]"
[Register ("component6", "()Ljava/lang/String;", "")]
public unsafe string Component6 ()
{
const string __id = "component6.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component7' and count(parameter)=0]"
[Register ("component7", "()Ljava/lang/String;", "")]
public unsafe string Component7 ()
{
const string __id = "component7.()Ljava/lang/String;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component8' and count(parameter)=0]"
[Register ("component8", "()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentResult;", "")]
public unsafe global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentResult Component8 ()
{
const string __id = "component8.()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentResult;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentResult> (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='component9' and count(parameter)=0]"
[Register ("component9", "()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentInfo;", "")]
public unsafe global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentInfo Component9 ()
{
const string __id = "component9.()Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentInfo;";
try {
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentInfo> (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.integrationmodels']/class[@name='PaymentSdkTransactionDetails']/method[@name='copy' and count(parameter)=15 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='java.lang.String'] and parameter[5][@type='java.lang.String'] and parameter[6][@type='java.lang.String'] and parameter[7][@type='java.lang.String'] and parameter[8][@type='com.payment.paymentsdk.integrationmodels.PaymentSdkPaymentResult'] and parameter[9][@type='com.payment.paymentsdk.integrationmodels.PaymentSdkPaymentInfo'] and parameter[10][@type='java.lang.String'] and parameter[11][@type='java.lang.String'] and parameter[12][@type='java.lang.String'] and parameter[13][@type='java.lang.String'] and parameter[14][@type='com.payment.paymentsdk.integrationmodels.PaymentSdkBillingDetails'] and parameter[15][@type='com.payment.paymentsdk.integrationmodels.PaymentSdkShippingDetails']]"
[Register ("copy", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentResult;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentInfo;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkBillingDetails;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkShippingDetails;)Lcom/payment/paymentsdk/integrationmodels/PaymentSdkTransactionDetails;", "")]
public unsafe global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkTransactionDetails Copy (string transactionReference, string transactionType, string cartID, string cartDescription, string cartCurrency, string cartAmount, string payResponseReturn, global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentResult paymentResult, global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkPaymentInfo paymentInfo, string redirectUrl, string errorCode, string errorMsg, string token, global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkBillingDetails billingDetails, global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkShippingDetails shippingDetails)
{
const string __id = "copy.(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentResult;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkPaymentInfo;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkBillingDetails;Lcom/payment/paymentsdk/integrationmodels/PaymentSdkShippingDetails;)Lcom/payment/paymentsdk/integrationmodels/PaymentSdkTransactionDetails;";
IntPtr native_transactionReference = JNIEnv.NewString (transactionReference);
IntPtr native_transactionType = JNIEnv.NewString (transactionType);
IntPtr native_cartID = JNIEnv.NewString (cartID);
IntPtr native_cartDescription = JNIEnv.NewString (cartDescription);
IntPtr native_cartCurrency = JNIEnv.NewString (cartCurrency);
IntPtr native_cartAmount = JNIEnv.NewString (cartAmount);
IntPtr native_payResponseReturn = JNIEnv.NewString (payResponseReturn);
IntPtr native_redirectUrl = JNIEnv.NewString (redirectUrl);
IntPtr native_errorCode = JNIEnv.NewString (errorCode);
IntPtr native_errorMsg = JNIEnv.NewString (errorMsg);
IntPtr native_token = JNIEnv.NewString (token);
try {
JniArgumentValue* __args = stackalloc JniArgumentValue [15];
__args [0] = new JniArgumentValue (native_transactionReference);
__args [1] = new JniArgumentValue (native_transactionType);
__args [2] = new JniArgumentValue (native_cartID);
__args [3] = new JniArgumentValue (native_cartDescription);
__args [4] = new JniArgumentValue (native_cartCurrency);
__args [5] = new JniArgumentValue (native_cartAmount);
__args [6] = new JniArgumentValue (native_payResponseReturn);
__args [7] = new JniArgumentValue ((paymentResult == null) ? IntPtr.Zero : ((global::Java.Lang.Object) paymentResult).Handle);
__args [8] = new JniArgumentValue ((paymentInfo == null) ? IntPtr.Zero : ((global::Java.Lang.Object) paymentInfo).Handle);
__args [9] = new JniArgumentValue (native_redirectUrl);
__args [10] = new JniArgumentValue (native_errorCode);
__args [11] = new JniArgumentValue (native_errorMsg);
__args [12] = new JniArgumentValue (native_token);
__args [13] = new JniArgumentValue ((billingDetails == null) ? IntPtr.Zero : ((global::Java.Lang.Object) billingDetails).Handle);
__args [14] = new JniArgumentValue ((shippingDetails == null) ? IntPtr.Zero : ((global::Java.Lang.Object) shippingDetails).Handle);
var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, __args);
return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkTransactionDetails> (__rm.Handle, JniHandleOwnership.TransferLocalRef);
} finally {
JNIEnv.DeleteLocalRef (native_transactionReference);
JNIEnv.DeleteLocalRef (native_transactionType);
JNIEnv.DeleteLocalRef (native_cartID);
JNIEnv.DeleteLocalRef (native_cartDescription);
JNIEnv.DeleteLocalRef (native_cartCurrency);
JNIEnv.DeleteLocalRef (native_cartAmount);
JNIEnv.DeleteLocalRef (native_payResponseReturn);
JNIEnv.DeleteLocalRef (native_redirectUrl);
JNIEnv.DeleteLocalRef (native_errorCode);
JNIEnv.DeleteLocalRef (native_errorMsg);
JNIEnv.DeleteLocalRef (native_token);
global::System.GC.KeepAlive (paymentResult);
global::System.GC.KeepAlive (paymentInfo);
global::System.GC.KeepAlive (billingDetails);
global::System.GC.KeepAlive (shippingDetails);
}
}
}
}
| 61.970696 | 1,078 | 0.760965 | [
"MIT"
] | amr-Magdy-PT/xamarin-paytabs-binding | android/PaymentSDK.Binding/obj/Debug/generated/src/Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkTransactionDetails.cs | 33,836 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Ron.DistributedCacheDemo
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Ron.DistributedCacheDemo.Startups.CSRedis.Startup>();
}
}
| 26.48 | 81 | 0.71148 | [
"MIT"
] | kongxiangxun/EasyAspNetCoreDemo | Ron.DistributedCacheDemo/Ron.DistributedCacheDemo/Program.cs | 664 | C# |
namespace Presentacion
{
partial class PrincipalGUI
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PrincipalGUI));
this.panel1 = new System.Windows.Forms.Panel();
this.btnCuentas = new System.Windows.Forms.Button();
this.btnPedido = new System.Windows.Forms.Button();
this.panel2 = new System.Windows.Forms.Panel();
this.brnCerrarSesion = new System.Windows.Forms.Button();
this.shapeContainer3 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.lineShape3 = new Microsoft.VisualBasic.PowerPacks.LineShape();
this.btnDetalles = new System.Windows.Forms.Button();
this.Marcas = new System.Windows.Forms.Button();
this.pictureBox6 = new System.Windows.Forms.PictureBox();
this.pictureBox5 = new System.Windows.Forms.PictureBox();
this.pictureBox4 = new System.Windows.Forms.PictureBox();
this.pictureBox3 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.panel3 = new System.Windows.Forms.Panel();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.fecha = new System.Windows.Forms.Label();
this.hora = new System.Windows.Forms.Label();
this.EstadoCivil = new System.Windows.Forms.Label();
this.Nombre = new System.Windows.Forms.Label();
this.Cargo = new System.Windows.Forms.Label();
this.shapeContainer2 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.lineShape2 = new Microsoft.VisualBasic.PowerPacks.LineShape();
this.Colores = new System.Windows.Forms.Button();
this.Productos = new System.Windows.Forms.Button();
this.Estilos = new System.Windows.Forms.Button();
this.Categorias = new System.Windows.Forms.Button();
this.Pedidos = new System.Windows.Forms.Button();
this.shapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.lineShape1 = new Microsoft.VisualBasic.PowerPacks.LineShape();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.btnPagos = new System.Windows.Forms.Button();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.panel3.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(122)))), ((int)(((byte)(204)))));
this.panel1.Controls.Add(this.btnPagos);
this.panel1.Controls.Add(this.btnCuentas);
this.panel1.Controls.Add(this.btnPedido);
this.panel1.Controls.Add(this.panel2);
this.panel1.Controls.Add(this.btnDetalles);
this.panel1.Controls.Add(this.Marcas);
this.panel1.Controls.Add(this.pictureBox6);
this.panel1.Controls.Add(this.pictureBox5);
this.panel1.Controls.Add(this.pictureBox4);
this.panel1.Controls.Add(this.pictureBox3);
this.panel1.Controls.Add(this.pictureBox2);
this.panel1.Controls.Add(this.pictureBox1);
this.panel1.Controls.Add(this.panel3);
this.panel1.Controls.Add(this.Colores);
this.panel1.Controls.Add(this.Productos);
this.panel1.Controls.Add(this.Estilos);
this.panel1.Controls.Add(this.Categorias);
this.panel1.Controls.Add(this.Pedidos);
this.panel1.Controls.Add(this.shapeContainer1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(877, 554);
this.panel1.TabIndex = 15;
//
// btnCuentas
//
this.btnCuentas.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.btnCuentas.FlatAppearance.BorderSize = 0;
this.btnCuentas.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.btnCuentas.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.btnCuentas.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnCuentas.ForeColor = System.Drawing.Color.LightGray;
this.btnCuentas.Location = new System.Drawing.Point(24, 425);
this.btnCuentas.Name = "btnCuentas";
this.btnCuentas.Size = new System.Drawing.Size(110, 38);
this.btnCuentas.TabIndex = 27;
this.btnCuentas.Text = "Cuentas";
this.btnCuentas.UseVisualStyleBackColor = false;
this.btnCuentas.Click += new System.EventHandler(this.btnCuentas_Click);
//
// btnPedido
//
this.btnPedido.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.btnPedido.FlatAppearance.BorderSize = 0;
this.btnPedido.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.btnPedido.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.btnPedido.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnPedido.ForeColor = System.Drawing.Color.LightGray;
this.btnPedido.Location = new System.Drawing.Point(24, 381);
this.btnPedido.Name = "btnPedido";
this.btnPedido.Size = new System.Drawing.Size(110, 38);
this.btnPedido.TabIndex = 26;
this.btnPedido.Text = "Pedidos";
this.btnPedido.UseVisualStyleBackColor = false;
this.btnPedido.Click += new System.EventHandler(this.btnPedido_Click);
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(122)))), ((int)(((byte)(204)))));
this.panel2.Controls.Add(this.brnCerrarSesion);
this.panel2.Controls.Add(this.shapeContainer3);
this.panel2.Location = new System.Drawing.Point(3, 494);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(594, 48);
this.panel2.TabIndex = 17;
//
// brnCerrarSesion
//
this.brnCerrarSesion.BackColor = System.Drawing.Color.Crimson;
this.brnCerrarSesion.FlatAppearance.BorderSize = 0;
this.brnCerrarSesion.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.brnCerrarSesion.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.brnCerrarSesion.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.brnCerrarSesion.Font = new System.Drawing.Font("Javanese Text", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.brnCerrarSesion.ForeColor = System.Drawing.Color.LightGray;
this.brnCerrarSesion.Location = new System.Drawing.Point(3, 5);
this.brnCerrarSesion.Name = "brnCerrarSesion";
this.brnCerrarSesion.Size = new System.Drawing.Size(110, 40);
this.brnCerrarSesion.TabIndex = 17;
this.brnCerrarSesion.Text = "Cerrar Sesion";
this.brnCerrarSesion.UseVisualStyleBackColor = false;
this.brnCerrarSesion.Click += new System.EventHandler(this.brnCerrarSesion_Click);
//
// shapeContainer3
//
this.shapeContainer3.Location = new System.Drawing.Point(0, 0);
this.shapeContainer3.Margin = new System.Windows.Forms.Padding(0);
this.shapeContainer3.Name = "shapeContainer3";
this.shapeContainer3.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] {
this.lineShape3});
this.shapeContainer3.Size = new System.Drawing.Size(594, 48);
this.shapeContainer3.TabIndex = 18;
this.shapeContainer3.TabStop = false;
//
// lineShape3
//
this.lineShape3.Name = "lineShape3";
this.lineShape3.X1 = 2;
this.lineShape3.X2 = 592;
this.lineShape3.Y1 = 0;
this.lineShape3.Y2 = -1;
//
// btnDetalles
//
this.btnDetalles.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.btnDetalles.FlatAppearance.BorderSize = 0;
this.btnDetalles.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.btnDetalles.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.btnDetalles.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnDetalles.ForeColor = System.Drawing.Color.LightGray;
this.btnDetalles.Location = new System.Drawing.Point(24, 150);
this.btnDetalles.Name = "btnDetalles";
this.btnDetalles.Size = new System.Drawing.Size(110, 49);
this.btnDetalles.TabIndex = 25;
this.btnDetalles.Text = "Detalles";
this.btnDetalles.UseVisualStyleBackColor = false;
this.btnDetalles.Click += new System.EventHandler(this.button1_Click);
//
// Marcas
//
this.Marcas.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.Marcas.FlatAppearance.BorderSize = 0;
this.Marcas.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.Marcas.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.Marcas.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Marcas.ForeColor = System.Drawing.Color.LightGray;
this.Marcas.Location = new System.Drawing.Point(256, 95);
this.Marcas.Name = "Marcas";
this.Marcas.Size = new System.Drawing.Size(110, 47);
this.Marcas.TabIndex = 23;
this.Marcas.Text = "Marcas";
this.Marcas.UseVisualStyleBackColor = false;
this.Marcas.Click += new System.EventHandler(this.Marcas_Click);
//
// pictureBox6
//
this.pictureBox6.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox6.Image")));
this.pictureBox6.Location = new System.Drawing.Point(256, 3);
this.pictureBox6.Name = "pictureBox6";
this.pictureBox6.Size = new System.Drawing.Size(110, 95);
this.pictureBox6.TabIndex = 22;
this.pictureBox6.TabStop = false;
//
// pictureBox5
//
this.pictureBox5.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox5.Image")));
this.pictureBox5.Location = new System.Drawing.Point(473, 0);
this.pictureBox5.Name = "pictureBox5";
this.pictureBox5.Size = new System.Drawing.Size(110, 98);
this.pictureBox5.TabIndex = 21;
this.pictureBox5.TabStop = false;
//
// pictureBox4
//
this.pictureBox4.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox4.Image")));
this.pictureBox4.Location = new System.Drawing.Point(256, 232);
this.pictureBox4.Name = "pictureBox4";
this.pictureBox4.Size = new System.Drawing.Size(110, 105);
this.pictureBox4.TabIndex = 20;
this.pictureBox4.TabStop = false;
//
// pictureBox3
//
this.pictureBox3.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox3.Image")));
this.pictureBox3.Location = new System.Drawing.Point(473, 232);
this.pictureBox3.Name = "pictureBox3";
this.pictureBox3.Size = new System.Drawing.Size(110, 105);
this.pictureBox3.TabIndex = 19;
this.pictureBox3.TabStop = false;
//
// pictureBox2
//
this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image")));
this.pictureBox2.Location = new System.Drawing.Point(24, 232);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(110, 105);
this.pictureBox2.TabIndex = 18;
this.pictureBox2.TabStop = false;
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(24, 3);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(110, 95);
this.pictureBox1.TabIndex = 17;
this.pictureBox1.TabStop = false;
//
// panel3
//
this.panel3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(130)))), ((int)(((byte)(203)))));
this.panel3.Controls.Add(this.label5);
this.panel3.Controls.Add(this.label4);
this.panel3.Controls.Add(this.label3);
this.panel3.Controls.Add(this.label2);
this.panel3.Controls.Add(this.label1);
this.panel3.Controls.Add(this.fecha);
this.panel3.Controls.Add(this.hora);
this.panel3.Controls.Add(this.EstadoCivil);
this.panel3.Controls.Add(this.Nombre);
this.panel3.Controls.Add(this.Cargo);
this.panel3.Controls.Add(this.shapeContainer2);
this.panel3.Dock = System.Windows.Forms.DockStyle.Right;
this.panel3.Location = new System.Drawing.Point(606, 0);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(271, 554);
this.panel3.TabIndex = 16;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(12, 165);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(61, 18);
this.label5.TabIndex = 10;
this.label5.Text = "Nombre:";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(12, 139);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(46, 18);
this.label4.TabIndex = 9;
this.label4.Text = "Cargo:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(12, 49);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(46, 18);
this.label3.TabIndex = 8;
this.label3.Text = "Fecha:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(12, 18);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(41, 18);
this.label2.TabIndex = 7;
this.label2.Text = "Hora:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Arial", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.Color.White;
this.label1.Location = new System.Drawing.Point(73, 106);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(136, 18);
this.label1.TabIndex = 6;
this.label1.Text = "Datos del usuario:";
//
// fecha
//
this.fecha.AutoSize = true;
this.fecha.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.fecha.Location = new System.Drawing.Point(57, 49);
this.fecha.Name = "fecha";
this.fecha.Size = new System.Drawing.Size(39, 17);
this.fecha.TabIndex = 4;
this.fecha.Text = "fecha";
//
// hora
//
this.hora.AutoSize = true;
this.hora.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.hora.Location = new System.Drawing.Point(57, 18);
this.hora.Name = "hora";
this.hora.Size = new System.Drawing.Size(35, 17);
this.hora.TabIndex = 3;
this.hora.Text = "hora";
//
// EstadoCivil
//
this.EstadoCivil.AutoSize = true;
this.EstadoCivil.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.EstadoCivil.Location = new System.Drawing.Point(70, 190);
this.EstadoCivil.Name = "EstadoCivil";
this.EstadoCivil.Size = new System.Drawing.Size(76, 17);
this.EstadoCivil.TabIndex = 2;
this.EstadoCivil.Text = "EstadoCivil";
//
// Nombre
//
this.Nombre.AutoSize = true;
this.Nombre.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Nombre.Location = new System.Drawing.Point(73, 166);
this.Nombre.Name = "Nombre";
this.Nombre.Size = new System.Drawing.Size(55, 17);
this.Nombre.TabIndex = 1;
this.Nombre.Text = "Nombre";
//
// Cargo
//
this.Cargo.AutoSize = true;
this.Cargo.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Cargo.Location = new System.Drawing.Point(70, 140);
this.Cargo.Name = "Cargo";
this.Cargo.Size = new System.Drawing.Size(43, 17);
this.Cargo.TabIndex = 0;
this.Cargo.Text = "Cargo";
//
// shapeContainer2
//
this.shapeContainer2.Location = new System.Drawing.Point(0, 0);
this.shapeContainer2.Margin = new System.Windows.Forms.Padding(0);
this.shapeContainer2.Name = "shapeContainer2";
this.shapeContainer2.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] {
this.lineShape2});
this.shapeContainer2.Size = new System.Drawing.Size(271, 554);
this.shapeContainer2.TabIndex = 5;
this.shapeContainer2.TabStop = false;
//
// lineShape2
//
this.lineShape2.Name = "lineShape2";
this.lineShape2.X1 = 2;
this.lineShape2.X2 = 198;
this.lineShape2.Y1 = 94;
this.lineShape2.Y2 = 94;
//
// Colores
//
this.Colores.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.Colores.FlatAppearance.BorderSize = 0;
this.Colores.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.Colores.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.Colores.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Colores.ForeColor = System.Drawing.Color.LightGray;
this.Colores.Location = new System.Drawing.Point(473, 331);
this.Colores.Name = "Colores";
this.Colores.Size = new System.Drawing.Size(110, 47);
this.Colores.TabIndex = 15;
this.Colores.Text = "Colores";
this.Colores.UseVisualStyleBackColor = false;
this.Colores.Click += new System.EventHandler(this.Colores_Click_1);
//
// Productos
//
this.Productos.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.Productos.FlatAppearance.BorderSize = 0;
this.Productos.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.Productos.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.Productos.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Productos.ForeColor = System.Drawing.Color.LightGray;
this.Productos.Location = new System.Drawing.Point(24, 93);
this.Productos.Name = "Productos";
this.Productos.Size = new System.Drawing.Size(110, 49);
this.Productos.TabIndex = 15;
this.Productos.Text = "Productos";
this.Productos.UseVisualStyleBackColor = false;
this.Productos.Click += new System.EventHandler(this.Productos_Click);
//
// Estilos
//
this.Estilos.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.Estilos.FlatAppearance.BorderSize = 0;
this.Estilos.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.Estilos.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.Estilos.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Estilos.ForeColor = System.Drawing.Color.LightGray;
this.Estilos.Location = new System.Drawing.Point(256, 331);
this.Estilos.Name = "Estilos";
this.Estilos.Size = new System.Drawing.Size(110, 47);
this.Estilos.TabIndex = 15;
this.Estilos.Text = "Estilos";
this.Estilos.UseVisualStyleBackColor = false;
this.Estilos.Click += new System.EventHandler(this.Estilos_Click_1);
//
// Categorias
//
this.Categorias.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.Categorias.FlatAppearance.BorderSize = 0;
this.Categorias.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.Categorias.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.Categorias.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Categorias.ForeColor = System.Drawing.Color.LightGray;
this.Categorias.Location = new System.Drawing.Point(473, 93);
this.Categorias.Name = "Categorias";
this.Categorias.Size = new System.Drawing.Size(110, 47);
this.Categorias.TabIndex = 15;
this.Categorias.Text = "Categorias";
this.Categorias.UseVisualStyleBackColor = false;
this.Categorias.Click += new System.EventHandler(this.Categorias_Click_1);
//
// Pedidos
//
this.Pedidos.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.Pedidos.FlatAppearance.BorderSize = 0;
this.Pedidos.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.Pedidos.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.Pedidos.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Pedidos.ForeColor = System.Drawing.Color.LightGray;
this.Pedidos.Location = new System.Drawing.Point(24, 331);
this.Pedidos.Name = "Pedidos";
this.Pedidos.Size = new System.Drawing.Size(110, 44);
this.Pedidos.TabIndex = 15;
this.Pedidos.Text = "Proveedores";
this.Pedidos.UseVisualStyleBackColor = false;
this.Pedidos.Click += new System.EventHandler(this.Pedidos_Click);
//
// shapeContainer1
//
this.shapeContainer1.Location = new System.Drawing.Point(0, 0);
this.shapeContainer1.Margin = new System.Windows.Forms.Padding(0);
this.shapeContainer1.Name = "shapeContainer1";
this.shapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] {
this.lineShape1});
this.shapeContainer1.Size = new System.Drawing.Size(877, 554);
this.shapeContainer1.TabIndex = 24;
this.shapeContainer1.TabStop = false;
//
// lineShape1
//
this.lineShape1.Name = "lineShape1";
this.lineShape1.X1 = 594;
this.lineShape1.X2 = 593;
this.lineShape1.Y1 = 3;
this.lineShape1.Y2 = 404;
//
// btnPagos
//
this.btnPagos.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
this.btnPagos.FlatAppearance.BorderSize = 0;
this.btnPagos.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28)))));
this.btnPagos.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.btnPagos.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnPagos.ForeColor = System.Drawing.Color.LightGray;
this.btnPagos.Location = new System.Drawing.Point(256, 425);
this.btnPagos.Name = "btnPagos";
this.btnPagos.Size = new System.Drawing.Size(110, 38);
this.btnPagos.TabIndex = 28;
this.btnPagos.Text = "Pagos";
this.btnPagos.UseVisualStyleBackColor = false;
this.btnPagos.Click += new System.EventHandler(this.btnPagos_Click);
//
// PrincipalGUI
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(15)))), ((int)(((byte)(15)))), ((int)(((byte)(15)))));
this.ClientSize = new System.Drawing.Size(877, 554);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "PrincipalGUI";
this.Opacity = 0.9D;
this.Text = "Principal";
this.TransparencyKey = System.Drawing.Color.FromArgb(((int)(((byte)(15)))), ((int)(((byte)(15)))), ((int)(((byte)(15)))));
this.Load += new System.EventHandler(this.Principal_Load);
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.panel3.ResumeLayout(false);
this.panel3.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button Colores;
private System.Windows.Forms.Button Productos;
private System.Windows.Forms.Button Estilos;
private System.Windows.Forms.Button Categorias;
private System.Windows.Forms.Button Pedidos;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Button brnCerrarSesion;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Label Cargo;
private System.Windows.Forms.Label EstadoCivil;
private System.Windows.Forms.Label Nombre;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox6;
private System.Windows.Forms.PictureBox pictureBox5;
private System.Windows.Forms.PictureBox pictureBox4;
private System.Windows.Forms.PictureBox pictureBox3;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.Button Marcas;
private Microsoft.VisualBasic.PowerPacks.ShapeContainer shapeContainer1;
private Microsoft.VisualBasic.PowerPacks.LineShape lineShape1;
private System.Windows.Forms.Label fecha;
private System.Windows.Forms.Label hora;
private System.Windows.Forms.Label label1;
private Microsoft.VisualBasic.PowerPacks.ShapeContainer shapeContainer2;
private Microsoft.VisualBasic.PowerPacks.LineShape lineShape2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private Microsoft.VisualBasic.PowerPacks.ShapeContainer shapeContainer3;
private Microsoft.VisualBasic.PowerPacks.LineShape lineShape3;
private System.Windows.Forms.Button btnDetalles;
private System.Windows.Forms.Button btnPedido;
private System.Windows.Forms.Button btnCuentas;
private System.Windows.Forms.Button btnPagos;
}
} | 58.481481 | 169 | 0.588923 | [
"Apache-2.0"
] | kike413/Desarrollo_de_un_ERP_Equipo5_8B | Presentacion/PrincipalGUI.Designer.cs | 34,740 | C# |
using System.Linq;
using NUnit.Framework;
using ShoppingBasket.Item;
using ShoppingBasket.Readers;
namespace ShoppingBasket.Tests
{
[TestFixture]
public class ItemsParserTests
{
private IParseItems _parser;
[SetUp]
public void Setup()
{
_parser = new ItemsParser();
}
[Test]
public void ReturnsNoItems()
{
Assert.IsEmpty(_parser.Parse(""));
}
[Test]
public void IgnoresWhitespace()
{
Assert.IsEmpty(_parser.Parse(" "));
}
[Test]
public void ReturnsOneItem()
{
Assert.AreEqual(1, _parser.Parse("item").Count());
Assert.AreEqual((ItemName)"namedItem", _parser.Parse("namedItem").Single());
}
[Test]
public void ReturnsMultipleItems()
{
var itemNames = _parser.Parse("first second").ToList();
Assert.AreEqual(2, itemNames.Count());
Assert.Contains((ItemName)"first", itemNames);
Assert.Contains((ItemName)"second", itemNames);
}
}
} | 25.021277 | 89 | 0.529762 | [
"Apache-2.0"
] | ofraski/ShoppingBasketPriceCalculator | Tests/ItemsParserTests.cs | 1,178 | C# |
using Microsoft.Extensions.Configuration;
using System;
namespace Proletarians.Utility
{
public class ProjectUtility
{
IConfiguration Configuration;
public IConfiguration GetConfiguration() => Configuration;
public static ProjectUtility Instance { get; } = new ProjectUtility();
private static readonly Lazy<ProjectUtility> lazy = new Lazy<ProjectUtility>();
public string GetDatabaseConnection() => Configuration.GetConnectionString("DefaultConnection");
public string GetRedisConnection() => Configuration.GetConnectionString("RedisConnectionString");
public string GetMongoConnection() => Configuration.GetConnectionString("MongoProductDb");
public string GetElasticConnection() => Configuration.GetConnectionString("ElasticDbConnection");
static ProjectUtility()
{
}
ProjectUtility()
{
}
public void Initialize(IConfiguration configuration)
{
Configuration = configuration;
}
}
}
| 33.15625 | 105 | 0.68426 | [
"MIT"
] | oguzhancagliyan/comics-for-geeks | Proletarians/Utility/ProjectUtility.cs | 1,063 | C# |
using MassiveKnob.Plugin.CoreAudio.Base;
namespace MassiveKnob.Plugin.CoreAudio.GetVolume
{
public class DeviceGetVolumeActionSettingsViewModel : BaseDeviceSettingsViewModel<DeviceGetVolumeActionSettings>
{
// ReSharper disable once SuggestBaseTypeForParameter - by design
public DeviceGetVolumeActionSettingsViewModel(DeviceGetVolumeActionSettings settings) : base(settings)
{
}
}
}
| 33.076923 | 116 | 0.772093 | [
"Unlicense"
] | MvRens/MassiveKnob | Windows/MassiveKnob.Plugin.CoreAudio/GetVolume/DeviceGetVolumeActionSettingsViewModel.cs | 432 | C# |
/**
* Autogenerated by Thrift Compiler (0.9.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
namespace Apache.Cassandra
{
public enum IndexType
{
KEYS = 0,
CUSTOM = 1,
COMPOSITES = 2,
}
}
| 15.764706 | 68 | 0.589552 | [
"Apache-2.0"
] | avezenkov/cassandra-sharp | Apache.Cassandra/gen-csharp/Apache/Cassandra/IndexType.cs | 268 | C# |
using NUnit.Framework;
namespace DotNetSdk.Test.Unit
{
[TestFixture]
public class Usage
{
[Test]
public void Example()
{
//ProductName.DefaultConfiguration.Interceptors.Add(/*something*/);
//ProductName.DefaultConfiguration.Serializer = // some custom serializer
//ProductName.DefaultConfiguration.Transport = // some other http abstraction
ProductName.DefaultConfiguration
.WithInterceptor<MyRandomInterceptor>();
var client = ProductName.CreateClient("123");
var typedResponse = client.Resource1.Get();
}
}
}
| 29.565217 | 90 | 0.598529 | [
"Apache-2.0"
] | davidwhitney/DotNetSdkExample | DotNetSdk.Test.Unit/Usage.cs | 682 | C# |
using System.Threading.Tasks;
namespace server.Services
{
public interface ICacheService
{
Task<string> GetCacheValueAsync(string key);
Task SetCacheValueAsync(string key, string value);
}
}
| 18.5 | 58 | 0.698198 | [
"MIT"
] | krazymirk/EUvsVirus | server/Services/ICacheService.cs | 224 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using DevSpace.Common;
namespace DevSpace.Database {
public class TimeSlotDataStore : IDataStore<ITimeSlot> {
public async Task<ITimeSlot> Add( ITimeSlot ItemToAdd ) {
throw new NotImplementedException();
}
public Task<bool> Delete( int Id ) {
throw new NotImplementedException();
}
public async Task<ITimeSlot> Get( int Id ) {
try {
using( SqlConnection connection = new SqlConnection( Settings.ConnectionString ) ) {
connection.Open();
using( SqlCommand command = new SqlCommand( "SELECT * FROM TimeSlots WHERE Id = @Id", connection ) ) {
command.Parameters.Add( "Id", SqlDbType.Int ).Value = Id;
using( SqlDataReader dataReader = await command.ExecuteReaderAsync().ConfigureAwait( false ) ) {
if( await dataReader.ReadAsync() ) {
return new Models.TimeSlotModel( dataReader );
}
}
}
}
} catch( Exception ex ) {
return null;
}
return null;
}
public async Task<IList<ITimeSlot>> Get( string Field, object Value ) {
throw new NotImplementedException();
}
public async Task<IList<ITimeSlot>> GetAll() {
List<ITimeSlot> returnList = new List<ITimeSlot>();
using( SqlConnection connection = new SqlConnection( Settings.ConnectionString ) ) {
connection.Open();
using( SqlCommand command = new SqlCommand( "SELECT * FROM TimeSlots", connection ) ) {
using( SqlDataReader dataReader = await command.ExecuteReaderAsync() ) {
while( await dataReader.ReadAsync() ) {
returnList.Add( new Models.TimeSlotModel( dataReader ) );
}
}
}
}
return returnList;
}
public async Task<ITimeSlot> Update( ITimeSlot ItemToUpdate ) {
throw new NotImplementedException();
}
}
}
| 28.615385 | 107 | 0.682796 | [
"MIT"
] | BrandenSchwartz/WebsiteAndApi | Database/TimeSlotDataStore.cs | 1,862 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IndustryTower.Models;
namespace IndustryTower.ViewModels
{
public class UserHomeFeedViewModel
{
public DateTime Date { get; set; }
public Post post { get; set; }
public Share share { get; set; }
//public Like like { get; set; }
//public Comment comment { get; set; }
public Question question { get; set; }
public Answer answer { get; set; }
public Experience experience { get; set; }
public Certificate certificate { get; set; }
public Product CoProduct { get; set; }
public Service CoService { get; set; }
}
public class HomeFeedWebinarsClassified
{
public IEnumerable<Seminar> attending { get; set; }
public IEnumerable<Seminar> Now { get; set; }
}
public class HomeFeedEvents
{
public Event Event { get; set; }
public int relevance { get; set; }
}
public class HomeFeedQuestionsClassified
{
public IEnumerable<HomeFeedQuestions> answered { get; set; }
public IEnumerable<HomeFeedQuestions> unAnswered { get; set; }
public IEnumerable<HomeFeedQuestions> old { get; set; }
}
public class HomeFeedQuestions
{
public Question Question { get; set; }
public int relevance { get; set; }
}
} | 27.076923 | 70 | 0.62642 | [
"Apache-2.0"
] | MehdiValinejad/industrytower | IndustryTower/ViewModels/UserHomeFeedViewModel.cs | 1,410 | C# |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Linq;
using Twilio.Types;
namespace Twilio.TwiML.Voice
{
/// <summary>
/// Stream TwiML Noun
/// </summary>
public class Stream : TwiML
{
public sealed class TrackEnum : StringEnum
{
private TrackEnum(string value) : base(value) {}
public TrackEnum() {}
public static implicit operator TrackEnum(string value)
{
return new TrackEnum(value);
}
public static readonly TrackEnum InboundTrack = new TrackEnum("inbound_track");
public static readonly TrackEnum OutboundTrack = new TrackEnum("outbound_track");
public static readonly TrackEnum BothTracks = new TrackEnum("both_tracks");
}
public sealed class StatusCallbackMethodEnum : StringEnum
{
private StatusCallbackMethodEnum(string value) : base(value) {}
public StatusCallbackMethodEnum() {}
public static implicit operator StatusCallbackMethodEnum(string value)
{
return new StatusCallbackMethodEnum(value);
}
public static readonly StatusCallbackMethodEnum Get = new StatusCallbackMethodEnum("GET");
public static readonly StatusCallbackMethodEnum Post = new StatusCallbackMethodEnum("POST");
}
/// <summary>
/// Friendly name given to the Stream
/// </summary>
public string Name { get; set; }
/// <summary>
/// Unique name for Stream Connector
/// </summary>
public string ConnectorName { get; set; }
/// <summary>
/// URL of the remote service where the Stream is routed
/// </summary>
public string Url { get; set; }
/// <summary>
/// Track to be streamed to remote service
/// </summary>
public Stream.TrackEnum Track { get; set; }
/// <summary>
/// Status Callback URL
/// </summary>
public string StatusCallback { get; set; }
/// <summary>
/// Status Callback URL method
/// </summary>
public Stream.StatusCallbackMethodEnum StatusCallbackMethod { get; set; }
/// <summary>
/// Create a new Stream
/// </summary>
/// <param name="name"> Friendly name given to the Stream </param>
/// <param name="connectorName"> Unique name for Stream Connector </param>
/// <param name="url"> URL of the remote service where the Stream is routed </param>
/// <param name="track"> Track to be streamed to remote service </param>
/// <param name="statusCallback"> Status Callback URL </param>
/// <param name="statusCallbackMethod"> Status Callback URL method </param>
public Stream(string name = null,
string connectorName = null,
string url = null,
Stream.TrackEnum track = null,
string statusCallback = null,
Stream.StatusCallbackMethodEnum statusCallbackMethod = null) : base("Stream")
{
this.Name = name;
this.ConnectorName = connectorName;
this.Url = url;
this.Track = track;
this.StatusCallback = statusCallback;
this.StatusCallbackMethod = statusCallbackMethod;
}
/// <summary>
/// Return the attributes of the TwiML tag
/// </summary>
protected override List<XAttribute> GetElementAttributes()
{
var attributes = new List<XAttribute>();
if (this.Name != null)
{
attributes.Add(new XAttribute("name", this.Name));
}
if (this.ConnectorName != null)
{
attributes.Add(new XAttribute("connectorName", this.ConnectorName));
}
if (this.Url != null)
{
attributes.Add(new XAttribute("url", this.Url));
}
if (this.Track != null)
{
attributes.Add(new XAttribute("track", this.Track.ToString()));
}
if (this.StatusCallback != null)
{
attributes.Add(new XAttribute("statusCallback", this.StatusCallback));
}
if (this.StatusCallbackMethod != null)
{
attributes.Add(new XAttribute("statusCallbackMethod", this.StatusCallbackMethod.ToString()));
}
return attributes;
}
/// <summary>
/// Create a new <Parameter/> element and append it as a child of this element.
/// </summary>
/// <param name="name"> The name of the custom parameter </param>
/// <param name="value"> The value of the custom parameter </param>
public Stream Parameter(string name = null, string value = null)
{
var newChild = new Parameter(name, value);
this.Append(newChild);
return this;
}
/// <summary>
/// Append a <Parameter/> element as a child of this element
/// </summary>
/// <param name="parameter"> A Parameter instance. </param>
[System.Obsolete("This method is deprecated, use .Append() instead.")]
public Stream Parameter(Parameter parameter)
{
this.Append(parameter);
return this;
}
/// <summary>
/// Append a child TwiML element to this element returning this element to allow chaining.
/// </summary>
/// <param name="childElem"> Child TwiML element to add </param>
public new Stream Append(TwiML childElem)
{
return (Stream) base.Append(childElem);
}
/// <summary>
/// Add freeform key-value attributes to the generated xml
/// </summary>
/// <param name="key"> Option key </param>
/// <param name="value"> Option value </param>
public new Stream SetOption(string key, object value)
{
return (Stream) base.SetOption(key, value);
}
}
} | 36.866279 | 109 | 0.55496 | [
"MIT"
] | BrimmingDev/twilio-csharp | src/Twilio/TwiML/Voice/Stream.cs | 6,341 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.