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 |
|---|---|---|---|---|---|---|---|---|
// <copyright file="GpBiCgTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// 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.
// </copyright>
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32.Solvers.Iterative
{
using System;
using LinearAlgebra.Complex32;
using LinearAlgebra.Complex32.Solvers;
using LinearAlgebra.Complex32.Solvers.Iterative;
using LinearAlgebra.Complex32.Solvers.StopCriterium;
using LinearAlgebra.Generic.Solvers.Status;
using NUnit.Framework;
/// <summary>
/// Tests for Generalized Product Bi-Conjugate Gradient iterative matrix solver.
/// </summary>
[TestFixture]
public class GpBiCgTest
{
/// <summary>
/// Convergence boundary.
/// </summary>
const float ConvergenceBoundary = 1e-5f;
/// <summary>
/// Maximum iterations.
/// </summary>
const int MaximumIterations = 1000;
/// <summary>
/// Solve wide matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveWideMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(2, 3);
Vector input = new DenseVector(2);
var solver = new GpBiCg();
Assert.Throws<ArgumentException>(() => solver.Solve(matrix, input));
}
/// <summary>
/// Solve long matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveLongMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(3, 2);
Vector input = new DenseVector(3);
var solver = new GpBiCg();
Assert.Throws<ArgumentException>(() => solver.Solve(matrix, input));
}
/// <summary>
/// Solve unit matrix and back multiply.
/// </summary>
[Test]
public void SolveUnitMatrixAndBackMultiply()
{
// Create the identity matrix
Matrix matrix = SparseMatrix.Identity(100);
// Create the y vector
Vector y = DenseVector.Create(matrix.RowCount, i => 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator(new IIterationStopCriterium[]
{
new IterationCountStopCriterium(MaximumIterations),
new ResidualStopCriterium(ConvergenceBoundary),
new DivergenceStopCriterium(),
new FailureStopCriterium()
});
var solver = new GpBiCg(monitor);
// Solve equation Ax = y
var x = solver.Solve(matrix, y);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status is CalculationConverged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.IsTrue((y[i] - z[i]).Magnitude.IsSmaller(ConvergenceBoundary, 1), "#05-" + i);
}
}
/// <summary>
/// Solve scaled unit matrix and back multiply.
/// </summary>
[Test]
public void SolveScaledUnitMatrixAndBackMultiply()
{
// Create the identity matrix
Matrix matrix = SparseMatrix.Identity(100);
// Scale it with a funny number
matrix.Multiply((float) Math.PI, matrix);
// Create the y vector
Vector y = DenseVector.Create(matrix.RowCount, i => 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator(new IIterationStopCriterium[]
{
new IterationCountStopCriterium(MaximumIterations),
new ResidualStopCriterium(ConvergenceBoundary),
new DivergenceStopCriterium(),
new FailureStopCriterium()
});
var solver = new GpBiCg(monitor);
// Solve equation Ax = y
var x = solver.Solve(matrix, y);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status is CalculationConverged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.IsTrue((y[i] - z[i]).Magnitude.IsSmaller(ConvergenceBoundary, 1), "#05-" + i);
}
}
/// <summary>
/// Solve poisson matrix and back multiply.
/// </summary>
[Test]
public void SolvePoissonMatrixAndBackMultiply()
{
// Create the matrix
var matrix = new SparseMatrix(25);
// Assemble the matrix. We assume we're solving the Poisson equation
// on a rectangular 5 x 5 grid
const int GridSize = 5;
// The pattern is:
// 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
for (var i = 0; i < matrix.RowCount; i++)
{
// Insert the first set of -1's
if (i > (GridSize - 1))
{
matrix[i, i - GridSize] = -1;
}
// Insert the second set of -1's
if (i > 0)
{
matrix[i, i - 1] = -1;
}
// Insert the centerline values
matrix[i, i] = 4;
// Insert the first trailing set of -1's
if (i < matrix.RowCount - 1)
{
matrix[i, i + 1] = -1;
}
// Insert the second trailing set of -1's
if (i < matrix.RowCount - GridSize)
{
matrix[i, i + GridSize] = -1;
}
}
// Create the y vector
Vector y = DenseVector.Create(matrix.RowCount, i => 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator(new IIterationStopCriterium[]
{
new IterationCountStopCriterium(MaximumIterations),
new ResidualStopCriterium(ConvergenceBoundary),
new DivergenceStopCriterium(),
new FailureStopCriterium()
});
var solver = new GpBiCg(monitor);
// Solve equation Ax = y
var x = solver.Solve(matrix, y);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status is CalculationConverged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.IsTrue((y[i] - z[i]).Magnitude.IsSmaller(ConvergenceBoundary, 1), "#05-" + i);
}
}
/// <summary>
/// Can solve for a random vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
public void CanSolveForRandomVector(int order)
{
for (var iteration = 5; iteration > 3; iteration--)
{
var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
var vectorb = MatrixLoader.GenerateRandomDenseVector(order);
var monitor = new Iterator(new IIterationStopCriterium[]
{
new IterationCountStopCriterium(1000),
new ResidualStopCriterium((float) Math.Pow(1.0/10.0, iteration)),
});
var solver = new GpBiCg(monitor);
var resultx = solver.Solve(matrixA, vectorb);
if (!(monitor.Status is CalculationConverged))
{
// Solution was not found, try again downgrading convergence boundary
continue;
}
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, (float) Math.Pow(1.0/10.0, iteration - 3));
Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, (float) Math.Pow(1.0/10.0, iteration - 3));
}
return;
}
Assert.Fail("Solution was not found in 3 tries");
}
}
}
| 35.639456 | 134 | 0.546287 | [
"MIT"
] | Plankankul/Framework-w-WebApp | Original/mathnet-numerics/src/UnitTests/LinearAlgebraTests/Complex32/Solvers/Iterative/GpBiCgTest.cs | 10,478 | 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 translate-2017-07-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Translate.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Translate.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for EncryptionKey Object
/// </summary>
public class EncryptionKeyUnmarshaller : IUnmarshaller<EncryptionKey, XmlUnmarshallerContext>, IUnmarshaller<EncryptionKey, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
EncryptionKey IUnmarshaller<EncryptionKey, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public EncryptionKey Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
EncryptionKey unmarshalledObject = new EncryptionKey();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Id", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Id = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Type", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Type = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static EncryptionKeyUnmarshaller _instance = new EncryptionKeyUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static EncryptionKeyUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 34.081633 | 152 | 0.625749 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/Translate/Generated/Model/Internal/MarshallTransformations/EncryptionKeyUnmarshaller.cs | 3,340 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using lm.Comol.Modules.Standard.ProjectManagement.Domain;
namespace lm.Comol.Modules.Standard.ProjectManagement.Presentation
{
public interface IViewSelectOwnerFromResources : lm.Comol.Core.DomainModel.Common.iDomainView
{
Boolean isInitialized { get; set; }
Boolean DisplayDescription { get; set; }
Boolean RaiseCommandEvents { get; set; }
void InitializeControl(List<dtoProjectResource> resources,String description = "");
long GetSelectedIdResource();
}
} | 35.235294 | 98 | 0.742905 | [
"MIT"
] | EdutechSRL/Adevico | 3-Business/3-Modules/lm.Comol.Modules.Standard/ProjectManagement/Presentation/0_IView/Settings/Controls/IViewSelectOwnerFromResources.cs | 601 | C# |
using DotNetNuke.Abstractions;
using DotNetNuke.Abstractions.Portals;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Services.Localization;
using Moq;
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
namespace DotNetNuke.Tests.Core.Common
{
[TestFixture]
public class NavigationManagerTests
{
private INavigationManager _navigationManager;
private const int TabID = 100;
private const int PortalID = 7;
private const string DefaultURLPattern = "/Default.aspx?tabid={0}";
private const string DefaultSuperTabPattern = "&portalid={0}";
private const string ControlKeyPattern = "&ctl={0}";
private const string LanguagePattern = "&language={0}";
[TestFixtureSetUp]
public void Setup()
{
_navigationManager = new NavigationManager(PortalControllerMock());
TabController.SetTestableInstance(TabControllerMock());
LocaleController.SetTestableInstance(LocaleControllerMock());
IPortalController PortalControllerMock()
{
var mockPortalController = new Mock<IPortalController>();
mockPortalController
.Setup(x => x.GetCurrentPortalSettings())
.Returns(PortalSettingsMock());
mockPortalController
.Setup(x => x.GetCurrentSettings())
.Returns(PortalSettingsMock());
return mockPortalController.Object;
PortalSettings PortalSettingsMock()
{
var portalSettings = new PortalSettings
{
PortalId = PortalID,
ActiveTab = new TabInfo
{
TabID = TabID
}
};
return portalSettings;
}
}
ITabController TabControllerMock()
{
var mockTabController = new Mock<ITabController>();
mockTabController
.Setup(x => x.GetTabsByPortal(Null.NullInteger))
.Returns(default(TabCollection));
mockTabController
.Setup(x => x.GetTab(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<bool>()))
.Returns(new TabInfo
{
CultureCode = "en-US"
});
return mockTabController.Object;
}
ILocaleController LocaleControllerMock()
{
var mockLocaleController = new Mock<ILocaleController>();
mockLocaleController
.Setup(x => x.GetLocales(It.IsAny<int>()))
.Returns(new Dictionary<string, Locale>
{
{ "en-US", new Locale() },
{ "TEST", new Locale() }
});
return mockLocaleController.Object;
}
}
[TestFixtureTearDown]
public void TearDown()
{
_navigationManager = null;
TabController.ClearInstance();
LocaleController.ClearInstance();
}
[Test]
public void NavigateUrlTest()
{
var expected = string.Format(DefaultURLPattern, TabID);
var actual = _navigationManager.NavigateURL();
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
[TestCase(4)]
[TestCase(5)]
[TestCase(6)]
[TestCase(7)]
[TestCase(8)]
[TestCase(9)]
[TestCase(10)]
[TestCase(11)]
public void NavigateUrl_CustomTabID(int tabId)
{
var expected = string.Format(DefaultURLPattern, tabId);
var actual = _navigationManager.NavigateURL(tabId);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[Test]
public void NavigateUrl_CustomTab_NotSuperTab()
{
var customTabId = 55;
var expected = string.Format(DefaultURLPattern, customTabId);
var actual = _navigationManager.NavigateURL(customTabId, false);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
[TestCase(4)]
[TestCase(5)]
[TestCase(6)]
[TestCase(7)]
[TestCase(8)]
[TestCase(9)]
[TestCase(10)]
[TestCase(11)]
public void NavigateUrl_CustomTab_IsSuperTab(int tabId)
{
var expected = string.Format(DefaultURLPattern, tabId) + string.Format(DefaultSuperTabPattern, PortalID);
var actual = _navigationManager.NavigateURL(tabId, true);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[Test]
[Ignore]
public void NavigateUrl_ControlKey_AccessDenied()
{
// TODO - We can't properly test this until we migrate
// Globals.AccessDeniedURL to an interface in the abstraction
// project. The dependencies go very deep and make it very
// difficult to properly test just the NavigationManager logic.
var actual = _navigationManager.NavigateURL("Access Denied");
}
[Test]
public void NavigateUrl_ControlKey()
{
var controlKey = "My-Control-Key";
var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey);
var actual = _navigationManager.NavigateURL(controlKey);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[Test]
public void NavigateUrl_ControlKey_EmptyAdditionalParameter()
{
var controlKey = "My-Control-Key";
var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey);
var actual = _navigationManager.NavigateURL(controlKey, new string[0]);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[Test]
public void NavigateUrl_ControlKey_SingleAdditionalParameter()
{
var controlKey = "My-Control-Key";
var parameters = new string[] { "My-Parameter" };
var expected = string.Format(DefaultURLPattern, TabID) +
string.Format(ControlKeyPattern, controlKey) +
$"&{parameters[0]}";
var actual = _navigationManager.NavigateURL(controlKey, parameters);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestCase(2)]
[TestCase(3)]
[TestCase(4)]
[TestCase(5)]
[TestCase(6)]
[TestCase(7)]
[TestCase(8)]
[TestCase(9)]
[TestCase(10)]
public void NavigateUrl_ControlKey_MultipleAdditionalParameter(int count)
{
string[] parameters = new string[count];
for (int index = 0; index < count; index++)
parameters[index] = $"My-Parameter{index}";
var controlKey = "My-Control-Key";
var expected = string.Format(DefaultURLPattern, TabID) +
string.Format(ControlKeyPattern, controlKey) +
parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}");
var actual = _navigationManager.NavigateURL(controlKey, parameters);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
[TestCase(4)]
[TestCase(5)]
[TestCase(6)]
[TestCase(7)]
[TestCase(8)]
[TestCase(9)]
[TestCase(10)]
[TestCase(11)]
public void NavigateUrl_TabID_ControlKey(int tabId)
{
var controlKey = "My-Control-Key";
var expected = string.Format(DefaultURLPattern, tabId) + string.Format(ControlKeyPattern, controlKey);
var actual = _navigationManager.NavigateURL(tabId, controlKey);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
[TestCase(4)]
[TestCase(5)]
[TestCase(6)]
[TestCase(7)]
[TestCase(8)]
[TestCase(9)]
[TestCase(10)]
[TestCase(11)]
public void NavigateUrl_TabID_EmptyControlKey(int tabId)
{
var expected = string.Format(DefaultURLPattern, tabId);
var actual = _navigationManager.NavigateURL(tabId, string.Empty);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
[TestCase(4)]
[TestCase(5)]
[TestCase(6)]
[TestCase(7)]
[TestCase(8)]
[TestCase(9)]
[TestCase(10)]
[TestCase(11)]
public void NavigateUrl_TabID_NullControlKey(int tabId)
{
var expected = string.Format(DefaultURLPattern, tabId);
var actual = _navigationManager.NavigateURL(tabId, string.Empty);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestCase(0, "My-Control-Key-0")]
[TestCase(1, "My-Control-Key-1")]
[TestCase(2, "My-Control-Key-2")]
[TestCase(3, "My-Control-Key-3")]
[TestCase(4, "My-Control-Key-4")]
[TestCase(5, "My-Control-Key-5")]
[TestCase(6, "My-Control-Key-6")]
[TestCase(7, "My-Control-Key-7")]
[TestCase(8, "My-Control-Key-8")]
[TestCase(9, "My-Control-Key-9")]
[TestCase(10, "My-Control-Key-10")]
public void NavigateUrl_TabID_ControlKey_Parameter(int count, string controlKey)
{
string[] parameters = new string[count];
for (int index = 0; index < count; index++)
parameters[index] = $"My-Parameter{index}";
var customTabId = 51;
var expected = string.Format(DefaultURLPattern, customTabId) +
string.Format(ControlKeyPattern, controlKey);
if (parameters.Length > 0)
expected += parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}");
var actual = _navigationManager.NavigateURL(customTabId, controlKey, parameters);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestCase(0, "My-Control-Key-0")]
[TestCase(1, "My-Control-Key-1")]
[TestCase(2, "My-Control-Key-2")]
[TestCase(3, "My-Control-Key-3")]
[TestCase(4, "My-Control-Key-4")]
[TestCase(5, "My-Control-Key-5")]
[TestCase(6, "My-Control-Key-6")]
[TestCase(7, "My-Control-Key-7")]
[TestCase(8, "My-Control-Key-8")]
[TestCase(9, "My-Control-Key-9")]
[TestCase(10, "My-Control-Key-10")]
public void NavigateUrl_TabID_ControlKey_NullParameter(int tabId, string controlKey)
{
var expected = string.Format(DefaultURLPattern, tabId) +
string.Format(ControlKeyPattern, controlKey);
var actual = _navigationManager.NavigateURL(tabId, controlKey, null);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestCase(0, "My-Control-Key-0")]
[TestCase(1, "My-Control-Key-1")]
[TestCase(2, "My-Control-Key-2")]
[TestCase(3, "My-Control-Key-3")]
[TestCase(4, "My-Control-Key-4")]
[TestCase(5, "My-Control-Key-5")]
[TestCase(6, "My-Control-Key-6")]
[TestCase(7, "My-Control-Key-7")]
[TestCase(8, "My-Control-Key-8")]
[TestCase(9, "My-Control-Key-9")]
[TestCase(10, "My-Control-Key-10")]
public void NavigateUrl_TabId_NullSettings_ControlKey(int tabId, string controlKey)
{
var expected = string.Format(DefaultURLPattern, tabId) +
string.Format(ControlKeyPattern, controlKey);
var actual = _navigationManager.NavigateURL(tabId, default(IPortalSettings), controlKey, null);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestCase(0, "My-Control-Key-0")]
[TestCase(1, "My-Control-Key-1")]
[TestCase(2, "My-Control-Key-2")]
[TestCase(3, "My-Control-Key-3")]
[TestCase(4, "My-Control-Key-4")]
[TestCase(5, "My-Control-Key-5")]
[TestCase(6, "My-Control-Key-6")]
[TestCase(7, "My-Control-Key-7")]
[TestCase(8, "My-Control-Key-8")]
[TestCase(9, "My-Control-Key-9")]
[TestCase(10, "My-Control-Key-10")]
public void NavigateUrl_TabId_Settings_ControlKey(int tabId, string controlKey)
{
var mockSettings = new Mock<IPortalSettings>();
mockSettings
.Setup(x => x.ContentLocalizationEnabled)
.Returns(true);
var expected = string.Format(DefaultURLPattern, tabId) +
string.Format(ControlKeyPattern, controlKey) +
string.Format(LanguagePattern, "en-US");
var actual = _navigationManager.NavigateURL(tabId, mockSettings.Object, controlKey, null);
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
}
}
| 35.111392 | 117 | 0.559665 | [
"MIT"
] | Mhtshum/Dnn.Platform | DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs | 13,871 | C# |
using Volo.Abp.Localization;
namespace CustomAngularAppWithIdentityServer.Localization
{
[LocalizationResourceName("CustomAngularAppWithIdentityServer")]
public class CustomAngularAppWithIdentityServerResource
{
}
} | 23.4 | 68 | 0.811966 | [
"MIT"
] | 271943794/abp-samples | CustomAngularAppWithIdentityServer/aspnet-core/src/CustomAngularAppWithIdentityServer.Domain.Shared/Localization/CustomAngularAppWithIdentityServerResource.cs | 236 | C# |
using System.IO;
namespace Oxide.Core.Plugins.Watchers
{
/// <summary>
/// Represents a file change
/// </summary>
public sealed class FileChange
{
/// <summary>
/// Gets the Name
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the ChangeType
/// </summary>
public WatcherChangeTypes ChangeType { get; private set; }
/// <summary>
/// Initializes a new instance of the FileChange class
/// </summary>
/// <param name="name"></param>
/// <param name="changeType"></param>
public FileChange(string name, WatcherChangeTypes changeType)
{
// Initialize
Name = name;
ChangeType = changeType;
}
}
}
| 24.727273 | 69 | 0.528186 | [
"MIT"
] | CryptoJones/Oxide | Oxide.Core/Plugins/Watchers/FileChange.cs | 818 | C# |
using Aggregates.Messages;
using NServiceBus;
using Demo.Library.Exceptions;
using Demo.Library.Reply;
using Demo.Presentation.ServiceStack.Infrastructure.Authentication;
using Demo.Presentation.ServiceStack.Infrastructure.Commands;
using Demo.Library.SSE;
using ServiceStack;
using ServiceStack.Caching;
using ServiceStack.Configuration;
using ServiceStack.Logging;
using ServiceStack.Web;
using System;
using System.Linq;
using System.Threading.Tasks;
using Q = Demo.Presentation.ServiceStack.Infrastructure.Queries;
using R = Demo.Presentation.ServiceStack.Infrastructure.Responses;
using Demo.Presentation.ServiceStack.Infrastructure.SSE;
namespace Demo.Presentation.ServiceStack.Infrastructure.Extensions
{
public static class RequestExtensions
{
private static readonly ILog Logger = LogManager.GetLogger("Requests");
public static Auth0Profile RetreiveUserProfile(this IRequest request)
{
var appSettings = new AppSettings();
var appSecret = appSettings.GetString("oauth.auth0.AppSecret").Replace('-', '+').Replace('_', '/');
var header = request.Headers["Authorization"];
if (header.IsNullOrEmpty())
return null;
try
{
var token = header.Split(' ');
if (token[0].ToUpper() != "PULSEAUTH")
return null;
var profile = JWT.JsonWebToken.Decode(token[1], Convert.FromBase64String(appSecret), verify: true);
if (profile.IsNullOrEmpty())
return null;
var auth0Profile = profile.FromJson<Auth0Profile>();
return auth0Profile;
}
catch
{
return null;
}
}
public static R.ResponsesQuery<TResponse> ToOptimizedCachedResult<TResponse>(this IRequest request, Q.QueriesQuery<TResponse> query, ICacheClient cache, Func<R.ResponsesQuery<TResponse>> factory)
{
var key = query.GetCacheKey();
var cached = cache.GetOrCreate(key, factory);
return cached;
}
public static async Task<R.ResponsesQuery<TResponse>> ToOptimizedCachedResult<TResponse>(this IRequest request, Q.QueriesQuery<TResponse> query, ICacheClient cache, Func<Task<R.ResponsesQuery<TResponse>>> factory)
{
var key = query.GetCacheKey();
var cached = cache.Get<R.ResponsesQuery<TResponse>>(key);
if (cached == null)
{
cached = await factory().ConfigureAwait(false);
cache.Add(key, cached);
}
return cached;
}
public static R.ResponsesQuery<TResponse> ToOptimizedCachedAndSubscribedResult<TResponse>(this IRequest request, Q.QueriesQuery<TResponse> query, ICacheClient cache, ISubscriptionManager manager, Func<R.ResponsesQuery<TResponse>> factory)
{
var result = request.ToOptimizedCachedResult(query, cache, () =>
{
var response = factory();
return response;
});
if (!query.SubscriptionId.IsNullOrEmpty())
manager.SubscribeWith(result, query, request.GetSessionId());
return result;
}
public static async Task<R.ResponsesQuery<TResponse>> ToOptimizedCachedAndSubscribedResult<TResponse>(this IRequest request, Q.QueriesQuery<TResponse> query, ICacheClient cache, ISubscriptionManager manager, Func<Task<R.ResponsesQuery<TResponse>>> factory)
{
var key = query.GetCacheKey();
var cached = cache.Get<R.ResponsesQuery<TResponse>>(key);
if (cached == null)
{
cached = await factory().ConfigureAwait(false);
cache.Add(key, cached);
}
if (!query.SubscriptionId.IsNullOrEmpty())
manager.SubscribeWith(cached, query, request.GetSessionId());
return cached;
}
public static R.ResponsesPaged<TResponse> ToOptimizedCachedResult<TResponse>(this IRequest request, Q.QueriesPaged<TResponse> query, ICacheClient cache, Func<R.ResponsesPaged<TResponse>> factory)
{
var key = query.GetCacheKey();
var cached = cache.GetOrCreate(key, () =>
{
var result = factory();
return result;
});
return cached;
}
public static async Task<R.ResponsesPaged<TResponse>> ToOptimizedCachedResult<TResponse>(this IRequest request, Q.QueriesPaged<TResponse> query, ICacheClient cache, Func<Task<R.ResponsesPaged<TResponse>>> factory)
{
var key = query.GetCacheKey();
var cached = cache.Get<R.ResponsesPaged<TResponse>>(key);
if (cached == null)
{
cached = await factory().ConfigureAwait(false);
cache.Add(key, cached);
}
return cached;
}
public static R.ResponsesPaged<TResponse> ToOptimizedCachedAndSubscribedPagedResult<TResponse>(this IRequest request, Q.QueriesPaged<TResponse> query, ICacheClient cache, ISubscriptionManager manager, Func<R.ResponsesPaged<TResponse>> factory)
{
var result = request.ToOptimizedCachedResult(query, cache, () =>
{
var response = factory();
return response;
});
if (!query.SubscriptionId.IsNullOrEmpty())
manager.SubscribeWith(result, query, request.GetSessionId());
return result;
}
public static async Task<R.ResponsesPaged<TResponse>> ToOptimizedCachedAndSubscribedPagedResult<TResponse>(this IRequest request, Q.QueriesPaged<TResponse> query, ICacheClient cache, ISubscriptionManager manager, Func<Task<R.ResponsesPaged<TResponse>>> factory)
{
var key = query.GetCacheKey();
var cached = cache.Get<R.ResponsesPaged<TResponse>>(key);
if (cached == null)
{
cached = await factory().ConfigureAwait(false);
cache.Add(key, cached);
}
if (!query.SubscriptionId.IsNullOrEmpty())
manager.SubscribeWith(cached, query, request.GetSessionId());
return cached;
}
public static R.ResponsesQuery<TResponse> RequestQuery<TResponse>(this IMessage message, Q.QueriesQuery<TResponse> query = null) where TResponse : class
{
if (message == null || message is Reject)
{
var reject = (Reject) message;
Logger.WarnFormat("Query was rejected - Message: {0}\n", reject.Message);
if (reject != null)
throw new QueryRejectedException(reject.Message);
throw new QueryRejectedException();
}
if (message is Error)
{
var error = (Error) message;
Logger.WarnFormat("Query raised an error - Message: {0}", error.Message);
throw new QueryRejectedException(error.Message);
}
var package = (IReply) message;
if (package == null)
throw new QueryRejectedException($"Unexpected response type: {message.GetType().FullName}");
var payload = package.Payload.ConvertTo<TResponse>();
return new R.ResponsesQuery<TResponse>
{
Payload = payload,
Etag = package.ETag,
SubscriptionId = query?.SubscriptionId,
SubscriptionTime = query?.SubscriptionTime,
};
}
public static R.ResponsesPaged<TResponse> RequestPaged<TResponse>(this IMessage message, Q.QueriesPaged<TResponse> query = null) where TResponse : class
{
if (message == null || message is Reject)
{
var reject = (Reject) message;
Logger.WarnFormat("Query was rejected - Message: {0}\n", reject.Message);
if (reject != null)
throw new QueryRejectedException(reject.Message);
throw new QueryRejectedException();
}
if (message is Error)
{
var error = (Error) message;
Logger.WarnFormat("Query raised an error - Message: {0}", error.Message);
throw new QueryRejectedException(error.Message);
}
var package = (IPagedReply) message;
if (package == null)
throw new QueryRejectedException($"Unexpected response type: {message.GetType().FullName}");
var records = package.Records.Select(x => x.ConvertTo<TResponse>());
return new R.ResponsesPaged<TResponse>
{
Records = records,
Total = package.Total,
ElapsedMs = package.ElapsedMs,
SubscriptionId = query?.SubscriptionId,
SubscriptionTime = query?.SubscriptionTime,
};
}
public static Task SubscribeCommand<TResponse>(this IRequest request, string documentId, ServiceCommand command, ISubscriptionManager manager)
{
if (!command.SubscriptionId.IsNullOrEmpty())
return manager.Manage<TResponse>(documentId, command.SubscriptionId, command.SubscriptionType ?? ChangeType.All, TimeSpan.FromSeconds(command.SubscriptionTime ?? 300), request.GetSessionId());
return Task.FromResult(0);
}
}
} | 43.071749 | 269 | 0.605518 | [
"MIT"
] | ImenRASSAA/DDD.Enterprise.Example | Presentation/ServiceStack/Infrastructure/Extensions/RequestExtensions.cs | 9,607 | C# |
using System.Threading.Tasks;
using Fluid;
using Fluid.Values;
using Newtonsoft.Json.Linq;
namespace OrchardCore.Liquid.Filters
{
public class JsonParseFilter : ILiquidFilter
{
public ValueTask<FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext context)
{
return new ValueTask<FluidValue>(new ObjectValue(JObject.Parse(input.ToStringValue())));
}
}
}
| 27.1875 | 119 | 0.726437 | [
"BSD-3-Clause"
] | Dryadepy/OrchardCore | src/OrchardCore.Modules/OrchardCore.Liquid/Filters/JsonParseFilter.cs | 435 | 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 sqs-2012-11-05.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.SQS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.SQS.Model.Internal.MarshallTransformations
{
/// <summary>
/// ReceiveMessage Request Marshaller
/// </summary>
public class ReceiveMessageRequestMarshaller : IMarshaller<IRequest, ReceiveMessageRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ReceiveMessageRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ReceiveMessageRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.SQS");
request.Parameters.Add("Action", "ReceiveMessage");
request.Parameters.Add("Version", "2012-11-05");
if(publicRequest != null)
{
if(publicRequest.IsSetAttributeNames())
{
int publicRequestlistValueIndex = 1;
foreach(var publicRequestlistValue in publicRequest.AttributeNames)
{
request.Parameters.Add("AttributeName" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue));
publicRequestlistValueIndex++;
}
}
if(publicRequest.IsSetMaxNumberOfMessages())
{
request.Parameters.Add("MaxNumberOfMessages", StringUtils.FromInt(publicRequest.MaxNumberOfMessages));
}
if(publicRequest.IsSetMessageAttributeNames())
{
int publicRequestlistValueIndex = 1;
foreach(var publicRequestlistValue in publicRequest.MessageAttributeNames)
{
request.Parameters.Add("MessageAttributeName" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue));
publicRequestlistValueIndex++;
}
}
if(publicRequest.IsSetQueueUrl())
{
request.Parameters.Add("QueueUrl", StringUtils.FromString(publicRequest.QueueUrl));
}
if(publicRequest.IsSetReceiveRequestAttemptId())
{
request.Parameters.Add("ReceiveRequestAttemptId", StringUtils.FromString(publicRequest.ReceiveRequestAttemptId));
}
if(publicRequest.IsSetVisibilityTimeout())
{
request.Parameters.Add("VisibilityTimeout", StringUtils.FromInt(publicRequest.VisibilityTimeout));
}
if(publicRequest.IsSetWaitTimeSeconds())
{
request.Parameters.Add("WaitTimeSeconds", StringUtils.FromInt(publicRequest.WaitTimeSeconds));
}
}
return request;
}
private static ReceiveMessageRequestMarshaller _instance = new ReceiveMessageRequestMarshaller();
internal static ReceiveMessageRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ReceiveMessageRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.305785 | 155 | 0.601976 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/SQS/Generated/Model/Internal/MarshallTransformations/ReceiveMessageRequestMarshaller.cs | 4,756 | C# |
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Scripting.Hosting;
namespace Edelstein.Core.Scripts.Python
{
public class PythonScript : IScript
{
private readonly CompiledCode _code;
private readonly ScriptScope _scope;
public PythonScript(CompiledCode code, ScriptScope scope)
{
_code = code;
_scope = scope;
}
public Task Register(string key, object value)
{
_scope.SetVariable(key, value);
return Task.CompletedTask;
}
public Task Start(CancellationToken token)
=> Task.Run(() => _code.Execute(), token);
}
} | 25.259259 | 65 | 0.617302 | [
"MIT"
] | Bia10/Edelstein | src/Edelstein.Core/Scripts/Python/PythonScript.cs | 682 | C# |
//-----------------------------------------------------------------------
// <copyright file="Rotate.cs" company="Tasty Codes">
// Copyright (c) 2010 Chad Burggraf.
// </copyright>
//-----------------------------------------------------------------------
namespace Zencoder
{
using System;
using Newtonsoft.Json;
/// <summary>
/// Defines the possible output video rotations.
/// </summary>
[JsonConverter(typeof(EnumIntJsonConverter))]
public enum Rotate
{
/// <summary>
/// Identifies that auto-rotation is diabled.
/// </summary>
None = 0,
/// <summary>
/// Identifies that the video is rotated 90 degrees.
/// </summary>
Ninety = 90,
/// <summary>
/// Identifies that the video is rotated 180 degrees.
/// </summary>
OneEighty = 180,
/// <summary>
/// Identifies that the video is rotated 270 degrees.
/// </summary>
TwoSeventy = 270
}
}
| 26.051282 | 74 | 0.470472 | [
"MIT"
] | ChadBurggraf/zencoder-cs | Source/Zencoder/Rotate.cs | 1,018 | C# |
using FIUAssist.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace FIUAssist.DatabaseManager
{
[JsonObject]
public class WoundSensors
{
[JsonProperty(PropertyName = "id")]
public string mId { get; set; }
//private string mId;
//public string getId() { return mId; }
//public void setId(string id) { mId = id; }
[JsonProperty(PropertyName = "CreatedAt")]
public DateTimeOffset mCreatedAt { get; set; }
//private DateTimeOffset mCreatedAt;
//public DateTimeOffset getCreatedAt() { return mCreatedAt; }
//protected void setCreatedAt(DateTimeOffset createdAt) { mCreatedAt = createdAt; }
[JsonProperty(PropertyName = "UpdatedAt")]
public DateTimeOffset mUpdatedAt { get; set; }
//private DateTimeOffset mUpdatedAt;
//public DateTimeOffset getUpdatedAt() { return mUpdatedAt; }
//protected void setUpdatedAt(DateTimeOffset updatedAt) { mUpdatedAt = updatedAt; }
[JsonProperty(PropertyName = "Version")]
public string mVersion { get; set; }
//private string mVersion;
//public string getVersion() { return mVersion; }
//public void setVersion(string version) { mVersion = version; }
[JsonProperty(PropertyName = "channel")]
public float mChannel { get; set; }
//private float mChannel;
//public float getChannel() { return mChannel; }
//public void setChannel(float channel) { mChannel = channel; }
[JsonProperty(PropertyName = "temperature")]
public float mTemperature { get; set; }
//private float mTemperature;
//public float getTemperature() { return mTemperature; }
//public void setTemperature(float temperature) { mTemperature = temperature; }
[JsonProperty(PropertyName = "battery_voltage")]
public float mBattery_voltage { get; set; }
//private float mBattery_voltage;
//public float getBattery_voltage() { return mBattery_voltage; }
//public void setBattery_voltage(float battery_voltage) { mBattery_voltage = battery_voltage; }
[JsonProperty(PropertyName = "bias")]
public float mBias { get; set; }
//private float mBias;
//public float getBias() { return mBias; }
//public void setBias(float bias) { mBias = bias; }
[JsonProperty(PropertyName = "timestamp")]
public string mTimeStamp { get; set; }
//public String TimeStamp;
//public String getTimeStamp() { return TimeStamp; }
//public void setTimeStamp(String TimeStamp) { this.TimeStamp = TimeStamp; }
[JsonProperty(PropertyName = "lmpoutput")]
public float mLmpoutput { get; set; }
//private float mLmpoutput;
//public float getLmpoutput() { return mLmpoutput; }
//public void setLmpoutput(float lmpoutput) { mLmpoutput = lmpoutput; }
[JsonProperty(PropertyName = "user_id")]
public string user_id { get; set; }
//private String user_id;
//public String getuser_id() { return user_id; }
//public void setuser_id(String user_id) { this.user_id = user_id; }
public double[] GetDoubleArray()
{
double[] data = new double[Constants.WOUND_LENGTH];
data[Constants.TEMPERATURE] = this.mTemperature;
data[Constants.CHANNEL] = this.mChannel;
data[Constants.BATTERY_VOLTAGE] = this.mBattery_voltage;
data[Constants.BIAS] = this.mBias;
data[Constants.LMPOUTPUT] = this.mLmpoutput;
return data;
}
}
}
| 38.030928 | 103 | 0.638927 | [
"MIT"
] | Guillebarq/IoT_Sensor_Collection_Xamarin | FIUAssist/FIUAssist/FIUAssist/DatabaseManager/WoundSensors.cs | 3,691 | C# |
// Copyright © Conatus Creative, Inc. All rights reserved.
// Licensed under the Apache 2.0 License. See LICENSE.md in the project root for license terms.
using System;
using System.Linq;
using System.Reflection;
namespace Pixel3D.Serialization.MethodProviders
{
internal class FallbackMethodProvider : MethodProvider
{
private readonly MethodProvider[] providers;
private FallbackMethodProvider(params MethodProvider[] providers)
{
this.providers = providers;
}
public static MethodProvider Combine(params MethodProvider[] providers)
{
var unwrappedProviders = providers.SelectMany(provider =>
{
var fallbackProvider = provider as FallbackMethodProvider;
if (fallbackProvider != null)
return fallbackProvider.providers;
if (provider is EmptyMethodProvider)
return new MethodProvider[] { };
return new[] {provider};
});
if (unwrappedProviders.Count() == 0)
return new EmptyMethodProvider();
if (unwrappedProviders.Count() == 1)
return unwrappedProviders.First();
return new FallbackMethodProvider(unwrappedProviders.ToArray());
}
public override MethodInfo GetMethodForType(Type type)
{
foreach (var provider in providers)
{
var methodInfo = provider.GetMethodForType(type);
if (methodInfo != null)
return methodInfo;
}
return null;
}
}
} | 25.980769 | 95 | 0.72983 | [
"Apache-2.0"
] | caogtaa/Pixel3D | src/Pixel3D.Serialization/MethodProviders/FallbackMethodProvider.cs | 1,354 | C# |
using System;
using System.IO;
using System.Net;
using System.Text;
using UIC.Util.Extensions;
using UIC.Util.Logging;
namespace UIC.Communication.M2mgo.ProjectAgent.WebApi
{
internal class WebApiRequestExecutor {
internal string ExecuteRequest(HttpWebRequest request, string payload, ILogger logger) {
request.Accept = "*/*";
request.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => {
logger.Information("accept server certificate");
return true;
};
if (request.Method != "GET") {
if (payload.IsNullOrEmpty()) {
request.ContentLength = 0;
}
else {
var data = Encoding.UTF8.GetBytes(payload);
var reqStr = request.GetRequestStream();
reqStr.Write(data, 0, data.Length);
request.ContentType = "application/json";
}
}
logger.Information(request.RequestUri.ToString());
using (HttpWebResponse resp = (HttpWebResponse) request.GetResponse()) {
return ReadDataFrom(resp);
}
}
internal static string ReadDataFrom(HttpWebResponse resp) {
string rawData = String.Empty;
if (resp.ContentLength > 0) {
using (var s = new StreamReader(resp.GetResponseStream())) {
rawData = s.ReadToEnd();
}
}
if (resp.StatusCode == HttpStatusCode.NotFound) {
return String.Empty;
}
if (resp.StatusCode != HttpStatusCode.OK) {
throw new Exception(resp.StatusCode + ": " + rawData);
}
return rawData;
}
}
} | 32.910714 | 99 | 0.537168 | [
"MIT"
] | CDE-GMA/UIC.net-mono.c-sharp | UIC/UIC.Communication.M2mgo.ProjectAgent/WebApi/WebApiRequestExecutor.cs | 1,845 | C# |
using Neu.IO;
using Neu.IO.Caching;
using System;
using System.Collections.Generic;
namespace Neu.Implementations.Blockchains.LevelDB
{
internal class DbCache<TKey, TValue> : DataCache<TKey, TValue>
where TKey : IEquatable<TKey>, ISerializable, new()
where TValue : class, ISerializable, new()
{
private DB db;
private DataEntryPrefix prefix;
public DbCache(DB db, DataEntryPrefix prefix)
{
this.db = db;
this.prefix = prefix;
}
public void Commit(WriteBatch batch)
{
foreach (Trackable trackable in GetChangeSet())
if (trackable.State != TrackState.Deleted)
batch.Put(prefix, trackable.Key, trackable.Item);
else
batch.Delete(prefix, trackable.Key);
}
protected override IEnumerable<KeyValuePair<TKey, TValue>> FindInternal(byte[] key_prefix)
{
return db.Find(ReadOptions.Default, SliceBuilder.Begin(prefix).Add(key_prefix), (k, v) => new KeyValuePair<TKey, TValue>(k.ToArray().AsSerializable<TKey>(), v.ToArray().AsSerializable<TValue>()));
}
protected override TValue GetInternal(TKey key)
{
return db.Get<TValue>(ReadOptions.Default, prefix, key);
}
protected override TValue TryGetInternal(TKey key)
{
return db.TryGet<TValue>(ReadOptions.Default, prefix, key);
}
}
}
| 32.347826 | 208 | 0.609543 | [
"MIT"
] | NeuBlockchain/NEU | neu/Implementations/Blockchains/LevelDB/DbCache.cs | 1,490 | C# |
using System;
using System.Collections.Generic;
namespace BettingTrivia.Shared
{
public class Room
{
public Guid ID { get; set; }
public List<User> Users { get; set; }
public Room()
{
ID = Guid.NewGuid();
}
}
} | 16.352941 | 45 | 0.535971 | [
"MIT"
] | torcher/BettingTrivia | Shared/Room.cs | 280 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace CshtmlComponentScopedCss.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 25.78125 | 88 | 0.687273 | [
"MIT"
] | Acmion/CshtmlComponentScopedCss | CshtmlComponentScopedCss/Pages/Error.cshtml.cs | 825 | C# |
// *****************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
// *****************************************************************
using System;
using System.Collections.Generic;
namespace MBF.IO.GenBank
{
/// <summary>
/// Region on a DNA molecule involved in RNA polymerase binding to initiate transcription.
/// </summary>
[Serializable]
public class Promoter : FeatureItem
{
#region Constructors
/// <summary>
/// Creates new Promoter feature item from the specified location.
/// </summary>
/// <param name="location">Location of the Promoter.</param>
public Promoter(ILocation location)
: base(StandardFeatureKeys.Promoter, location) { }
/// <summary>
/// Creates new Promoter feature item with the specified location.
/// Note that this constructor uses LocationBuilder to construct location object from the specified
/// location string.
/// </summary>
/// <param name="location">Location of the Promoter.</param>
public Promoter(string location)
: base(StandardFeatureKeys.Promoter, location) { }
/// <summary>
/// Private constructor for clone method.
/// </summary>
/// <param name="other">Other Promoter instance.</param>
private Promoter(Promoter other)
: base(other) { }
#endregion Constructors
#region Properties
/// <summary>
/// Name of the allele for the given gene.
/// All gene-related features (exon, CDS etc) for a given gene should share the same Allele qualifier value;
/// the Allele qualifier value must, by definition, be different from the Gene qualifier value; when used with
/// the variation feature key, the Allele qualifier value should be that of the variant.
/// </summary>
public string Allele
{
get
{
return GetSingleTextQualifier(StandardQualifierNames.Allele);
}
set
{
SetSingleTextQualifier(StandardQualifierNames.Allele, value);
}
}
/// <summary>
/// Name of the molecule/complex that may bind to the given feature.
/// </summary>
public List<string> BoundMoiety
{
get
{
return GetQualifier(StandardQualifierNames.BoundMoiety);
}
}
/// <summary>
/// Reference to a citation listed in the entry reference field.
/// </summary>
public List<string> Citation
{
get
{
return GetQualifier(StandardQualifierNames.Citation);
}
}
/// <summary>
/// Database cross-reference: pointer to related information in another database.
/// </summary>
public List<string> DatabaseCrossReference
{
get
{
return GetQualifier(StandardQualifierNames.DatabaseCrossReference);
}
}
/// <summary>
/// A brief description of the nature of the experimental evidence that supports the feature
/// identification or assignment.
/// </summary>
public List<string> Experiment
{
get
{
return GetQualifier(StandardQualifierNames.Experiment);
}
}
/// <summary>
/// Function attributed to a sequence.
/// </summary>
public List<string> Function
{
get
{
return GetQualifier(StandardQualifierNames.Function);
}
}
/// <summary>
/// Symbol of the gene corresponding to a sequence region.
/// </summary>
public string GeneSymbol
{
get
{
return GetSingleTextQualifier(StandardQualifierNames.GeneSymbol);
}
set
{
SetSingleTextQualifier(StandardQualifierNames.GeneSymbol, value);
}
}
/// <summary>
/// Synonymous, replaced, obsolete or former gene symbol.
/// </summary>
public List<string> GeneSynonym
{
get
{
return GetQualifier(StandardQualifierNames.GeneSynonym);
}
}
/// <summary>
/// Genomic map position of feature.
/// </summary>
public string GenomicMapPosition
{
get
{
return GetSingleTextQualifier(StandardQualifierNames.GenomicMapPosition);
}
set
{
SetSingleTextQualifier(StandardQualifierNames.GenomicMapPosition, value);
}
}
/// <summary>
/// A structured description of non-experimental evidence that supports the feature
/// identification or assignment.
/// </summary>
public List<string> Inference
{
get
{
return GetQualifier(StandardQualifierNames.Inference);
}
}
/// <summary>
/// A submitter-supplied, systematic, stable identifier for a gene and its associated
/// features, used for tracking purposes.
/// </summary>
public List<string> LocusTag
{
get
{
return GetQualifier(StandardQualifierNames.LocusTag);
}
}
/// <summary>
/// Any comment or additional information.
/// </summary>
public List<string> Note
{
get
{
return GetQualifier(StandardQualifierNames.Note);
}
}
/// <summary>
/// Feature tag assigned for tracking purposes.
/// </summary>
public List<string> OldLocusTag
{
get
{
return GetQualifier(StandardQualifierNames.OldLocusTag);
}
}
/// <summary>
/// Name of the group of contiguous genes transcribed into a single transcript to which that feature belongs.
/// </summary>
public string Operon
{
get
{
return GetSingleTextQualifier(StandardQualifierNames.Operon);
}
set
{
SetSingleTextQualifier(StandardQualifierNames.Operon, value);
}
}
/// <summary>
/// Phenotype conferred by the feature, where phenotype is defined as a physical, biochemical or behavioral
/// characteristic or set of characteristics.
/// </summary>
public List<string> Phenotype
{
get
{
return GetQualifier(StandardQualifierNames.Phenotype);
}
}
/// <summary>
/// Indicates that this feature is a non-functional version of the element named by the feature key.
/// </summary>
public bool Pseudo
{
get
{
return GetSingleBooleanQualifier(StandardQualifierNames.Pseudo);
}
set
{
SetSingleBooleanQualifier(StandardQualifierNames.Pseudo, value);
}
}
/// <summary>
/// Accepted standard name for this feature.
/// </summary>
public string StandardName
{
get
{
return GetSingleTextQualifier(StandardQualifierNames.StandardName);
}
set
{
SetSingleTextQualifier(StandardQualifierNames.StandardName, value);
}
}
#endregion Properties
#region Methods
/// <summary>
/// Creates a new Promoter that is a copy of the current Promoter.
/// </summary>
/// <returns>A new Promoter that is a copy of this Promoter.</returns>
public new Promoter Clone()
{
return new Promoter(this);
}
#endregion Methods
}
} | 30.123239 | 119 | 0.529632 | [
"Apache-2.0"
] | jdm7dv/Microsoft-Biology-Foundation | archive/Changesets/beta/Source/MBF/MBF/IO/GenBank/Promoter.cs | 8,555 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using System;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class ImportChain : Cci.IImportScope
{
public readonly Imports Imports;
public readonly ImportChain ParentOpt;
private ImmutableArray<Cci.UsedNamespaceOrType> _lazyTranslatedImports;
public ImportChain(Imports imports, ImportChain parentOpt)
{
Debug.Assert(imports != null);
Imports = imports;
ParentOpt = parentOpt;
}
ImmutableArray<Cci.UsedNamespaceOrType> Cci.IImportScope.GetUsedNamespaces()
{
// The imports should have been translated during code gen.
Debug.Assert(!_lazyTranslatedImports.IsDefault);
return _lazyTranslatedImports;
}
public Cci.IImportScope Translate(Emit.PEModuleBuilder moduleBuilder, DiagnosticBag diagnostics)
{
for (var scope = this; scope != null; scope = scope.ParentOpt)
{
if (!scope._lazyTranslatedImports.IsDefault)
{
break;
}
ImmutableInterlocked.InterlockedInitialize(ref scope._lazyTranslatedImports, scope.TranslateImports(moduleBuilder, diagnostics));
}
return this;
}
private ImmutableArray<Cci.UsedNamespaceOrType> TranslateImports(Emit.PEModuleBuilder moduleBuilder, DiagnosticBag diagnostics)
{
var usedNamespaces = ArrayBuilder<Cci.UsedNamespaceOrType>.GetInstance();
// NOTE: order based on dev12: extern aliases, then usings, then aliases namespaces and types
ImmutableArray<AliasAndExternAliasDirective> externAliases = Imports.ExternAliases;
if (!externAliases.IsDefault)
{
foreach (var alias in externAliases)
{
usedNamespaces.Add(Cci.UsedNamespaceOrType.CreateExternAlias(alias.Alias.Name));
}
}
ImmutableArray<NamespaceOrTypeAndUsingDirective> usings = Imports.Usings;
if (!usings.IsDefault)
{
foreach (var nsOrType in usings)
{
NamespaceOrTypeSymbol namespaceOrType = nsOrType.NamespaceOrType;
if (namespaceOrType.IsNamespace)
{
var ns = (NamespaceSymbol)namespaceOrType;
var assemblyRef = TryGetAssemblyScope(ns, moduleBuilder, diagnostics);
usedNamespaces.Add(Cci.UsedNamespaceOrType.CreateNamespace(ns, assemblyRef));
}
else if (!namespaceOrType.ContainingAssembly.IsLinked)
{
// We skip alias imports of embedded types to be consistent with imports of aliased embedded types and with VB.
var typeRef = GetTypeReference((TypeSymbol)namespaceOrType, nsOrType.UsingDirective, moduleBuilder, diagnostics);
usedNamespaces.Add(Cci.UsedNamespaceOrType.CreateType(typeRef));
}
}
}
ImmutableDictionary<string, AliasAndUsingDirective> aliasSymbols = Imports.UsingAliases;
if (!aliasSymbols.IsEmpty)
{
var aliases = ArrayBuilder<string>.GetInstance(aliasSymbols.Count);
aliases.AddRange(aliasSymbols.Keys);
aliases.Sort(StringComparer.Ordinal); // Actual order doesn't matter - just want to be deterministic.
foreach (var alias in aliases)
{
var aliasAndUsingDirective = aliasSymbols[alias];
var symbol = aliasAndUsingDirective.Alias;
var syntax = aliasAndUsingDirective.UsingDirective;
Debug.Assert(!symbol.IsExtern);
NamespaceOrTypeSymbol target = symbol.Target;
if (target.Kind == SymbolKind.Namespace)
{
var ns = (NamespaceSymbol)target;
var assemblyRef = TryGetAssemblyScope(ns, moduleBuilder, diagnostics);
usedNamespaces.Add(Cci.UsedNamespaceOrType.CreateNamespace(ns, assemblyRef, alias));
}
else if (!target.ContainingAssembly.IsLinked)
{
// We skip alias imports of embedded types to avoid breaking existing code that
// imports types that can't be embedded but doesn't use them anywhere else in the code.
var typeRef = GetTypeReference((TypeSymbol)target, syntax, moduleBuilder, diagnostics);
usedNamespaces.Add(Cci.UsedNamespaceOrType.CreateType(typeRef, alias));
}
}
aliases.Free();
}
return usedNamespaces.ToImmutableAndFree();
}
private static Cci.ITypeReference GetTypeReference(TypeSymbol type, SyntaxNode syntaxNode, Emit.PEModuleBuilder moduleBuilder, DiagnosticBag diagnostics)
{
return moduleBuilder.Translate(type, syntaxNode, diagnostics);
}
private Cci.IAssemblyReference TryGetAssemblyScope(NamespaceSymbol @namespace, Emit.PEModuleBuilder moduleBuilder, DiagnosticBag diagnostics)
{
AssemblySymbol containingAssembly = @namespace.ContainingAssembly;
if ((object)containingAssembly != null && (object)containingAssembly != moduleBuilder.CommonCompilation.Assembly)
{
var referenceManager = ((CSharpCompilation)moduleBuilder.CommonCompilation).GetBoundReferenceManager();
for (int i = 0; i < referenceManager.ReferencedAssemblies.Length; i++)
{
if ((object)referenceManager.ReferencedAssemblies[i] == containingAssembly)
{
if (!referenceManager.DeclarationsAccessibleWithoutAlias(i))
{
return moduleBuilder.Translate(containingAssembly, diagnostics);
}
}
}
}
return null;
}
Cci.IImportScope Cci.IImportScope.Parent => ParentOpt;
}
}
| 44.446667 | 161 | 0.59982 | [
"Apache-2.0"
] | davidfowl/roslyn | src/Compilers/CSharp/Portable/Binder/ImportChain.cs | 6,669 | C# |
using System;
namespace Christ3D.Domain.Interfaces
{
/// <summary>
/// 工作单元接口
/// </summary>
public interface IUnitOfWork : IDisposable
{
//是否提交成功
bool Commit();
}
}
| 14.857143 | 46 | 0.5625 | [
"MIT"
] | DotNetExample/ChristDDD | Christ3D.Domain/Interfaces/IUnitOfWork.cs | 234 | C# |
using System;
namespace Inflow.Services.Payments.Core.Deposits.DTO;
public class DepositAccountDto
{
public Guid AccountId { get; set; }
public Guid CustomerId { get; set; }
public string Currency { get; set; }
public string Iban { get; set; }
public DateTime CreatedAt { get; set; }
} | 25.666667 | 53 | 0.691558 | [
"MIT"
] | devmentors/Inflow-micro | src/Payments/Inflow.Services.Payments.Core/Deposits/DTO/DepositAccountDto.cs | 310 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class SystemGenerator : MonoBehaviour
{
private int m_rows;
private int m_columns;
public delegate void SystemGenerationComplete(int rowSize, int columnSize);
public static event SystemGenerationComplete OnSystemGenerationComplete;
private void OnEnable()
{
WorldGenerator.OnWorldGenerationComplete += GenerateSystem;
}
private void OnDisable()
{
WorldGenerator.OnWorldGenerationComplete -= GenerateSystem;
}
public void GenerateSystem(int rows, int columns)
{
m_rows = rows;
m_columns = columns;
AddComponentsToTileObjects();
InitializeSenderOnlyRiverTiles();
OnSystemGenerationComplete?.Invoke(m_rows, m_columns);
}
/// <summary>
/// Iterates through each tile object to add necessary script Components.
/// </summary>
/// <param name="rows"></param>
/// <param name="columns"></param>
private void AddComponentsToTileObjects()
{
for (int x = 0; x < m_rows; x++)
{
for (int y = 0; y < m_columns; y++)
{
Vector2 tileIndex = new Vector2(x, y);
if (TileManager.s_TilesDictonary.TryGetValue(tileIndex, out GameObject value))
{
DetermineTileComponents(value, value.GetComponent<Tile>().m_PhysicalType);
}
}
}
}
private void InitializeSenderOnlyRiverTiles()
{
// Find all water Tiles in row 0
for (int y = 0; y < m_columns; y++)
{
Vector2 tileIndex = new Vector2(0, y);
if (TileManager.s_TilesDictonary.TryGetValue(tileIndex, out GameObject value))
{
Tile tileScript = value.GetComponent<Tile>();
if (tileScript.m_Basetype == BaseType.Water)
{
tileScript.m_isStateSpawner = true;
}
}
}
for (int x = 0; x < m_rows; x++)
{
Vector2 tileIndexLeft = new Vector2(x, 0);
Vector2 tileIndexRight = new Vector2(x, m_columns - 1);
if (TileManager.s_TilesDictonary.TryGetValue(tileIndexLeft, out GameObject valueL))
{
Tile tileScript = valueL.GetComponent<Tile>();
if (tileScript.m_Basetype == BaseType.Water)
{
tileScript.m_isStateSpawner = true;
}
}
if (TileManager.s_TilesDictonary.TryGetValue(tileIndexRight, out GameObject valueR))
{
Tile tileScript = valueR.GetComponent<Tile>();
if (tileScript.m_Basetype == BaseType.Water)
{
tileScript.m_isStateSpawner = true;
}
}
}
}
//// Please search for a tile's implemented set of components using CTRL+I
//// then type in name of physical tile type.
//// This setup allows for individualization of component setup per tile type.
/// <summary>
/// Adds the appropriate script Components depending on the PhysicalType of the current tile.
/// </summary>
/// <param name="currentTile"></param>
/// <param name="physicalType"></param>
private void DetermineTileComponents(GameObject currentTile, PhysicalType physicalType)
{
Debug.Assert(physicalType != PhysicalType.None, $"There is no PhysicalType associated with tile at index {currentTile.GetComponent<Tile>().m_TileIndex}");
switch (physicalType)
{
case PhysicalType.None:
Debug.LogError($"There is no PhysicalType associated with tile at index {currentTile.GetComponent<Tile>().m_TileIndex}");
break;
case PhysicalType.Agriculture:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "Agriculture tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "Agriculture";
break;
case PhysicalType.Commercial:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "Commercial tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "Commercial";
break;
case PhysicalType.EngineeredReservoir:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Water, "EngineeredReservoir tiles are expected to be water type");
currentTile.AddComponent(typeof(BrownTroutPopulation));
currentTile.AddComponent(typeof(CreekChubPopulation));
currentTile.AddComponent(typeof(InsectPopulation));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(RateOfFlow));
currentTile.AddComponent(typeof(RedDacePopulation));
currentTile.AddComponent(typeof(RiparianLevel));
currentTile.AddComponent(typeof(RiverbedHealth));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(Sinuosity));
currentTile.AddComponent(typeof(ShadeCoverage));
currentTile.AddComponent(typeof(Turbidity));
currentTile.AddComponent(typeof(WaterDepth));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "EngineeredReservoir";
break;
case PhysicalType.EngineeredStream:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Water, "EngineeredStream tiles are expected to be water type");
currentTile.AddComponent(typeof(BrownTroutPopulation));
currentTile.AddComponent(typeof(CreekChubPopulation));
currentTile.AddComponent(typeof(InsectPopulation));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(RateOfFlow));
currentTile.AddComponent(typeof(RedDacePopulation));
currentTile.AddComponent(typeof(RiparianLevel));
currentTile.AddComponent(typeof(RiverbedHealth));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(Sinuosity));
currentTile.AddComponent(typeof(ShadeCoverage));
currentTile.AddComponent(typeof(Turbidity));
currentTile.AddComponent(typeof(WaterDepth));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "EngineeredStream";
break;
case PhysicalType.EstateResidential:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "EstateResidential tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "EstateResidential";
break;
case PhysicalType.Forest:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "Forest tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "Forest";
break;
case PhysicalType.GolfCourse:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "GolfCourse tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "GolfCourse";
break;
case PhysicalType.HighDensity:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "HighDensity tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "HighDensity";
break;
case PhysicalType.Highway:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "Highway tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
// These variables need to be able to flow through Highway because Highway crosses water.
currentTile.AddComponent(typeof(BrownTroutPopulation));
currentTile.AddComponent(typeof(CreekChubPopulation));
currentTile.AddComponent(typeof(InsectPopulation));
currentTile.AddComponent(typeof(RateOfFlow));
currentTile.AddComponent(typeof(RedDacePopulation));
currentTile.AddComponent(typeof(RiparianLevel));
currentTile.AddComponent(typeof(RiverbedHealth));
currentTile.AddComponent(typeof(Sinuosity));
currentTile.AddComponent(typeof(ShadeCoverage));
currentTile.AddComponent(typeof(Turbidity));
currentTile.AddComponent(typeof(WaterDepth));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "Highway";
break;
case PhysicalType.Industrial:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "Industrial tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "Industrial";
break;
case PhysicalType.Institutional:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "Institutional tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "Institutional";
break;
case PhysicalType.LowMidDensity:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "LowMidDensity tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "LowMidDensity";
break;
case PhysicalType.Meadow:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "Meadow tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "Meadow";
break;
case PhysicalType.NaturalReservoir:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Water, "NaturalReservoir tiles are expected to be water type");
currentTile.AddComponent(typeof(BrownTroutPopulation));
currentTile.AddComponent(typeof(CreekChubPopulation));
currentTile.AddComponent(typeof(InsectPopulation));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(RateOfFlow));
currentTile.AddComponent(typeof(RedDacePopulation));
currentTile.AddComponent(typeof(RiparianLevel));
currentTile.AddComponent(typeof(RiverbedHealth));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(Sinuosity));
currentTile.AddComponent(typeof(ShadeCoverage));
currentTile.AddComponent(typeof(Turbidity));
currentTile.AddComponent(typeof(WaterDepth));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "NaturalReservoir";
break;
case PhysicalType.NaturalStream:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Water, "NaturalStream tiles are expected to be water type");
currentTile.AddComponent(typeof(BrownTroutPopulation));
currentTile.AddComponent(typeof(CreekChubPopulation));
currentTile.AddComponent(typeof(InsectPopulation));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(RateOfFlow));
currentTile.AddComponent(typeof(RedDacePopulation));
currentTile.AddComponent(typeof(RiparianLevel));
currentTile.AddComponent(typeof(RiverbedHealth));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(Sinuosity));
currentTile.AddComponent(typeof(ShadeCoverage));
currentTile.AddComponent(typeof(Turbidity));
currentTile.AddComponent(typeof(WaterDepth));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "NaturalStream";
break;
case PhysicalType.RecreationCentreSpace:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "RecreationCentreSpace tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "RecreationCentreSpace";
break;
case PhysicalType.Successional:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "Successional tiles are suspected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "Successional";
break;
case PhysicalType.UrbanOpenSpace:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "UrbanOpenSpace tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "UrbanOpenSpace";
break;
case PhysicalType.Vacant:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Land, "Vacant tiles are expected to be land type");
currentTile.AddComponent(typeof(AsphaltDensity));
currentTile.AddComponent(typeof(ErosionRate));
currentTile.AddComponent(typeof(LandHeight));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "Vacant";
break;
case PhysicalType.Wetland:
Debug.Assert(currentTile.GetComponent<Tile>().m_Basetype == BaseType.Water, "Wetland tiles are expected to be water type");
currentTile.AddComponent(typeof(BrownTroutPopulation));
currentTile.AddComponent(typeof(CreekChubPopulation));
currentTile.AddComponent(typeof(InsectPopulation));
currentTile.AddComponent(typeof(PollutionLevel));
currentTile.AddComponent(typeof(RateOfFlow));
currentTile.AddComponent(typeof(RedDacePopulation));
currentTile.AddComponent(typeof(RiparianLevel));
currentTile.AddComponent(typeof(RiverbedHealth));
currentTile.AddComponent(typeof(SewageLevel));
currentTile.AddComponent(typeof(Sinuosity));
currentTile.AddComponent(typeof(ShadeCoverage));
currentTile.AddComponent(typeof(Turbidity));
currentTile.AddComponent(typeof(WaterDepth));
currentTile.AddComponent(typeof(WaterTemperature));
currentTile.tag = "Wetland";
break;
default:
Debug.LogError($"There is no PhysicalType associated with tile at index {currentTile.GetComponent<Tile>().m_TileIndex}");
break;
}
}
}
| 54.731383 | 162 | 0.624909 | [
"CC0-1.0"
] | Amelia-McLeavey/mywatershed-game | myWATERSHED/Assets/Scripts/PCG/SystemGenerator.cs | 20,579 | C# |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Collections.Generic;
using System.ComponentModel;
using FluentMigrator.Expressions;
using FluentMigrator.Model;
namespace FluentMigrator.Builders.Delete
{
public class DeleteDataExpressionBuilder : IDeleteDataOrInSchemaSyntax
{
private readonly DeleteDataExpression _expression;
public DeleteDataExpressionBuilder(DeleteDataExpression expression)
{
_expression = expression;
}
public void IsNull(string columnName)
{
_expression.Rows.Add(new DeletionDataDefinition
{
new KeyValuePair<string, object>(columnName, null)
});
}
public IDeleteDataSyntax Row(object dataAsAnonymousType)
{
_expression.Rows.Add(GetData(dataAsAnonymousType));
return this;
}
public IDeleteDataSyntax InSchema(string schemaName)
{
_expression.SchemaName = schemaName;
return this;
}
public void AllRows()
{
_expression.IsAllRows = true;
}
private static DeletionDataDefinition GetData(object dataAsAnonymousType)
{
var data = new DeletionDataDefinition();
var properties = TypeDescriptor.GetProperties(dataAsAnonymousType);
foreach (PropertyDescriptor property in properties)
data.Add(new KeyValuePair<string, object>(property.Name, property.GetValue(dataAsAnonymousType)));
return data;
}
}
} | 32.428571 | 114 | 0.648018 | [
"Apache-2.0"
] | BartDM/fluentmigrator | src/FluentMigrator/Builders/Delete/DeleteDataExpressionBuilder.cs | 2,270 | C# |
using System;
namespace Ao.ObjectDesign.Designing.Annotations
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
public sealed class UnfoldMappingAttribute : Attribute
{
public bool SkipSelft { get; set; } = true;
}
}
| 24.909091 | 73 | 0.693431 | [
"Apache-2.0"
] | Cricle/Ao.ObjectDesign | src/Ao.ObjectDesign.Designing/Annotations/UnfoldMappingAttribute.cs | 276 | C# |
using Bloom.Data.Interfaces;
namespace Bloom.Data.Tables
{
/// <summary>
/// Represents the filterset_element table.
/// </summary>
/// <seealso cref="Bloom.Data.Interfaces.ISqlTable" />
public class FiltersetElementTable : ISqlTable
{
/// <summary>
/// Gets the create filterset_element table SQL.
/// </summary>
public string CreateSql => "CREATE TABLE filterset_element (" +
"filterset_id BLOB NOT NULL , " +
"element_number INTEGER NOT NULL , " +
"element_type INTEGER NOT NULL , " +
"filter_id BLOB , " +
"filter_comparison INTEGER , " +
"filter_against VARCHAR , " +
"PRIMARY KEY (filterset_id, element_number) , " +
"FOREIGN KEY (filterset_id) REFERENCES filterset(id) )";
}
} | 42.708333 | 91 | 0.48 | [
"Apache-2.0"
] | RobDixonIII/Bloom | Shared/Bloom.Data/Tables/FiltersetElementTable.cs | 1,027 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using SeniorBlockchain.Controllers;
using SeniorBlockchain.Utilities;
using SeniorBlockchain.Utilities.JsonErrors;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
namespace SeniorBlockchain.Features.RPC.Controllers
{
/// <summary>
/// Controller providing API operations on the RPC feature.
/// </summary>
[Authorize]
[ApiController]
[ApiVersion("1")]
[Route("api/[controller]")]
public class RPCController : Controller
{
/// <summary>Instance logger.</summary>
private readonly ILogger logger;
/// <summary>Full Node.</summary>
private readonly IFullNode fullNode;
/// <summary>RPC Settings.</summary>
private readonly RpcSettings rpcSettings;
/// <summary>RPC Client Factory.</summary>
private readonly IRPCClientFactory rpcClientFactory;
/// <summary>ControllerActionDescriptor dictionary.</summary>
private Dictionary<string, ControllerActionDescriptor> ActionDescriptors { get; set; }
/// <summary>
/// Initializes a new instance of the object.
/// </summary>
/// <param name="fullNode">The full node.</param>
/// <param name="loggerFactory">Factory to be used to create logger for the node.</param>
/// <param name="rpcSettings">The RPC Settings of the full node.</param>
public RPCController(IFullNode fullNode, ILoggerFactory loggerFactory, RpcSettings rpcSettings, IRPCClientFactory rpcClientFactory)
{
Guard.NotNull(fullNode, nameof(fullNode));
Guard.NotNull(loggerFactory, nameof(loggerFactory));
Guard.NotNull(rpcSettings, nameof(rpcSettings));
Guard.NotNull(rpcClientFactory, nameof(rpcClientFactory));
this.fullNode = fullNode;
this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
this.rpcSettings = rpcSettings;
this.rpcClientFactory = rpcClientFactory;
}
/// <summary>
/// Returns the collection of available action descriptors.
/// </summary>
private Dictionary<string, ControllerActionDescriptor> GetActionDescriptors()
{
if (this.ActionDescriptors == null)
{
this.ActionDescriptors = new Dictionary<string, ControllerActionDescriptor>();
var actionDescriptorProvider = this.fullNode?.RPCHost.Services.GetService(typeof(IActionDescriptorCollectionProvider)) as IActionDescriptorCollectionProvider;
// This approach is similar to the one used by RPCRouteHandler so should only give us the descriptors
// that RPC would normally act on subject to the method name matching the "ActionName".
foreach (ControllerActionDescriptor actionDescriptor in actionDescriptorProvider?.ActionDescriptors.Items.OfType<ControllerActionDescriptor>())
this.ActionDescriptors[actionDescriptor.ActionName] = actionDescriptor;
}
return this.ActionDescriptors;
}
/// <summary>
/// Processes a Remote Procedural Call.
/// </summary>
/// <param name="request">The request to process.</param>
/// <returns></returns>
private RPCResponse SendRPCRequest(RPCRequest request)
{
// Find the binding to 127.0.0.1 or the first available. The logic in RPC settings ensures there will be at least 1.
IPEndPoint nodeEndPoint = this.rpcSettings.Bind.Where(b => b.Address.ToString() == "127.0.0.1").FirstOrDefault() ?? this.rpcSettings.Bind[0];
IRPCClient rpcClient = this.rpcClientFactory.Create(this.rpcSettings, new Uri($"http://{nodeEndPoint}"), this.fullNode.Network);
return rpcClient.SendCommand(request);
}
/// <summary>
/// Makes a Remote Procedural Call method by name.
/// </summary>
/// <param name="body">A JObject containing the name of the method to process.</param>
/// <returns>A JSON result that varies depending on the RPC method.</returns>
[Route("callbyname")]
[HttpPost]
public IActionResult CallByName([FromBody]JObject body)
{
Guard.NotNull(body, nameof(body));
try
{
if (!this.rpcSettings.Server)
{
return ErrorHelpers.BuildErrorResponse(HttpStatusCode.MethodNotAllowed, "Method not allowed", "Method not allowed when RPC is disabled.");
}
StringComparison ignoreCase = StringComparison.InvariantCultureIgnoreCase;
string methodName = (string)body.GetValue("methodName", ignoreCase);
ControllerActionDescriptor actionDescriptor = null;
if (!this.GetActionDescriptors()?.TryGetValue(methodName, out actionDescriptor) ?? false)
throw new Exception($"RPC method '{ methodName }' not found.");
// Prepare the named parameters that were passed via the query string in the order that they are expected by SendCommand.
List<ControllerParameterDescriptor> paramInfos = actionDescriptor.Parameters.OfType<ControllerParameterDescriptor>().ToList();
var paramsAsObjects = new object[paramInfos.Count];
for (int i = 0; i < paramInfos.Count; i++)
{
ControllerParameterDescriptor pInfo = paramInfos[i];
bool hasValue = body.TryGetValue(pInfo.Name, ignoreCase, out JToken jValue);
if (hasValue && !jValue.HasValues)
{
paramsAsObjects[i] = jValue.ToString();
}
else
{
paramsAsObjects[i] = pInfo.ParameterInfo.DefaultValue?.ToString();
}
}
RPCRequest request = new RPCRequest(methodName, paramsAsObjects);
// Build RPC request object.
RPCResponse response = this.SendRPCRequest(request);
// Throw error if any.
if (response?.Error?.Message != null)
throw new Exception(response.Error.Message);
// Return a Json result from the API call.
return this.Json(response?.Result);
}
catch (Exception e)
{
this.logger.LogError("Exception occurred: {0}", e.ToString());
return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString());
}
}
/// <summary>
/// Lists the available Remote Procedural Call methods on this node.
/// </summary>
/// <returns>A JSON result that lists the RPC methods.</returns>
[Route("listmethods")]
[HttpGet]
public IActionResult ListMethods()
{
try
{
if (!this.rpcSettings.Server)
{
return ErrorHelpers.BuildErrorResponse(HttpStatusCode.MethodNotAllowed, "Method not allowed", "Method not allowed when RPC is disabled.");
}
var listMethods = new List<Models.RpcCommandModel>();
foreach (ControllerActionDescriptor descriptor in this.GetActionDescriptors().Values.Where(desc => desc.ActionName == desc.ActionName.ToLower()))
{
CustomAttributeData attr = descriptor.MethodInfo.CustomAttributes.Where(x => x.AttributeType == typeof(ActionDescription)).FirstOrDefault();
string description = attr?.ConstructorArguments.FirstOrDefault().Value as string ?? "";
var parameters = new List<string>();
foreach (ControllerParameterDescriptor param in descriptor.Parameters.OfType<ControllerParameterDescriptor>())
{
if (!param.ParameterInfo.IsRetval)
{
string value = $"<{param.ParameterInfo.Name.ToLower()}>";
if (param.ParameterInfo.HasDefaultValue)
value = $"[{value}]";
parameters.Add(value);
}
}
string method = $"{descriptor.ActionName} {string.Join(" ", parameters.ToArray())}";
listMethods.Add(new Models.RpcCommandModel { Command = method.Trim(), Description = description });
}
return this.Json(listMethods);
}
catch (Exception e)
{
this.logger.LogError("Exception occurred: {0}", e.ToString());
return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString());
}
}
}
} | 45.156863 | 174 | 0.604755 | [
"MIT"
] | seniorblockchain/blockchain | src/Features/SeniorBlockchain.Features.RPC/Controllers/RPCController.cs | 9,214 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
namespace Azure.ResourceManager.Network.Models
{
/// <summary> Parameters that define the flow log format. </summary>
public partial class FlowLogFormatParameters
{
/// <summary> Initializes a new instance of FlowLogFormatParameters. </summary>
public FlowLogFormatParameters()
{
}
/// <summary> Initializes a new instance of FlowLogFormatParameters. </summary>
/// <param name="flowLogFormatType"> The file type of flow log. </param>
/// <param name="version"> The version (revision) of the flow log. </param>
internal FlowLogFormatParameters(FlowLogFormatType? flowLogFormatType, int? version)
{
FlowLogFormatType = flowLogFormatType;
Version = version;
}
/// <summary> The file type of flow log. </summary>
public FlowLogFormatType? FlowLogFormatType { get; set; }
/// <summary> The version (revision) of the flow log. </summary>
public int? Version { get; set; }
}
}
| 35.242424 | 92 | 0.651763 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/Models/FlowLogFormatParameters.cs | 1,163 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Norm;
using Npgsql;
using NpgsqlTypes;
using Xunit;
namespace PostgreSqlUnitTests
{
[Collection("PostgreSqlDatabase")]
public class QueryMultipleMapsUnitTests
{
public record Record1(int Id1, string Foo1, string Bar1);
public record Record2(int Id2, string Foo2, string Bar2);
public record Record3(string Foo3, string Bar3, int Id3);
private readonly PostgreSqlFixture fixture;
private readonly string Qurey = @"
select
1 as id1,
'foo1' as foo1,
'bar1' as bar1,
2 as id2,
'foo2' as foo2,
'bar2' as bar2,
'foo3' as foo3,
'bar3' as bar3,
3 as id3,
4 as id4,
5 as id5,
6 as id6,
7 as id7,
8 as id8, 9 as id9,
10 as id10;";
public QueryMultipleMapsUnitTests(PostgreSqlFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public void MapTwoRecords_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var (result1, result2) = connection.Read<Record1, Record2>(Qurey).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal("foo1", result1.Foo1);
Assert.Equal("bar1", result1.Bar1);
Assert.Equal(2, result2.Id2);
Assert.Equal("foo2", result2.Foo2);
Assert.Equal("bar2", result2.Bar2);
}
[Fact]
public void MapTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var result1 = connection.Read<(int Id1, string Foo1, string Bar1)>(Qurey).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal("foo1", result1.Foo1);
Assert.Equal("bar1", result1.Bar1);
var result2 = connection.Read<(int Id1, string Foo1, string Bar1, int Id2, string Foo2, string Bar2, string Foo3, string Bar3)>(Qurey).Single();
Assert.Equal(1, result2.Id1);
Assert.Equal("foo1", result2.Foo1);
Assert.Equal("bar1", result2.Bar1);
Assert.Equal(2, result2.Id2);
Assert.Equal("foo2", result2.Foo2);
Assert.Equal("bar2", result2.Bar2);
Assert.Equal("foo3", result2.Foo3);
Assert.Equal("bar3", result2.Bar3);
}
[Fact]
public void Map_Two_Simple_Tuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var (result1, result2) = connection.Read<(int Id1, string Foo1, string Bar1), (int Id2, string Foo2, string Bar2)>(Qurey).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal("foo1", result1.Foo1);
Assert.Equal("bar1", result1.Bar1);
Assert.Equal(2, result2.Id2);
Assert.Equal("foo2", result2.Foo2);
Assert.Equal("bar2", result2.Bar2);
}
[Fact]
public void Map_Two_Complex_Simple_Tuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var (result3, result4) = connection.Read<(int Id1, string Foo1, string Bar1, int Id2, string Foo2, string Bar2, string Foo3), (string Bar3, int Id3)>(Qurey).Single();
Assert.Equal(1, result3.Id1);
Assert.Equal("foo1", result3.Foo1);
Assert.Equal("bar1", result3.Bar1);
Assert.Equal(2, result3.Id2);
Assert.Equal("foo2", result3.Foo2);
Assert.Equal("bar2", result3.Bar2);
Assert.Equal("foo3", result3.Foo3);
Assert.Equal("bar3", result4.Bar3);
Assert.Equal(3, result4.Id3);
}
[Fact]
public void Map_Two_Complex_Simple_Tuples_Edge_Case_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var (result5, result6) = connection.Read<(int Id1, string Foo1, string Bar1, int Id2, string Foo2, string Bar2, string Foo3, string Bar3), (int Id3, int Id4)>(Qurey).Single();
Assert.Equal(1, result5.Id1);
Assert.Equal("foo1", result5.Foo1);
Assert.Equal("bar1", result5.Bar1);
Assert.Equal(2, result5.Id2);
Assert.Equal("foo2", result5.Foo2);
Assert.Equal("bar2", result5.Bar2);
Assert.Equal("foo3", result5.Foo3);
Assert.Equal("bar3", result5.Bar3);
Assert.Equal(3, result6.Id3);
Assert.Equal(4, result6.Id4);
}
[Fact]
public void Map_Two_Complex_Complex_Tuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var (result7, result8) = connection.Read<
(int Id1, string Foo1, string Bar1, int Id2, string Foo2, string Bar2, string Foo3, string Bar3),
(int Id3, int Id4, int Id5, int Id6, int Id7, int Id8, int Id9, int Id10) >(Qurey).Single();
Assert.Equal(1, result7.Id1);
Assert.Equal("foo1", result7.Foo1);
Assert.Equal("bar1", result7.Bar1);
Assert.Equal(2, result7.Id2);
Assert.Equal("foo2", result7.Foo2);
Assert.Equal("bar2", result7.Bar2);
Assert.Equal("foo3", result7.Foo3);
Assert.Equal("bar3", result7.Bar3);
Assert.Equal(3, result8.Id3);
Assert.Equal(4, result8.Id4);
Assert.Equal(5, result8.Id5);
Assert.Equal(6, result8.Id6);
Assert.Equal(7, result8.Id7);
Assert.Equal(8, result8.Id8);
Assert.Equal(9, result8.Id9);
Assert.Equal(10, result8.Id10);
}
[Fact]
public void Map_Three_Records_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var (result1, result2, result3) = connection.Read<Record1, Record2, Record3>(Qurey).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal("foo1", result1.Foo1);
Assert.Equal("bar1", result1.Bar1);
Assert.Equal(2, result2.Id2);
Assert.Equal("foo2", result2.Foo2);
Assert.Equal("bar2", result2.Bar2);
Assert.Equal("foo3", result3.Foo3);
Assert.Equal("bar3", result3.Bar3);
Assert.Equal(3, result3.Id3);
}
[Fact]
public void Map_Mistmatch1_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
Assert.Throws<NormMultipleMappingsException>(() => connection.Read<Record1, int>(Qurey).Single());
}
[Fact]
public void Map_Mistmatch2_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
Assert.Throws<NormMultipleMappingsException>(() => connection.Read<int, Record1>(Qurey).Single());
}
[Fact]
public void Map_Mistmatch3_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
Assert.Throws<NormMultipleMappingsException>(() => connection.Read<Record1, (int Id2, string Foo2, string Bar2)>(Qurey).Single());
}
[Fact]
public void Map_Three_NamedTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 6).Select((e, i) => $"{e+i} as id{e + i}")));
var (result1, result2, result3) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6)>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
}
[Fact]
public void Map_Three_NamedTuples_TooShort_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 6).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4)>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
}
[Fact]
public void Map_Three_NamedTuples_TooLong_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 5).Select((e, i) => $"{e + i} as id{e + i}")));
Assert.Throws<IndexOutOfRangeException>(() => connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6)>(sql).Single());
}
[Fact]
public void Map_Four_NamedTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 8).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6),
(int Id7, int Id8)>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
}
record R12(int Id1, int Id2);
record R34(int Id3, int Id4);
record R56(int Id5, int Id6);
record R78(int Id7, int Id8);
[Fact]
public void Map_Four_Records_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 8).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4) = connection.Read<
R12,
R34,
R56,
R78>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
}
[Fact]
public void Map_Five_NamedTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 10).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6),
(int Id7, int Id8),
(int Id9, int Id10) > (sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
}
record R910(int Id9, int Id10);
[Fact]
public void Map_Five_Records_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 10).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5) = connection.Read<
R12,
R34,
R56,
R78,
R910>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
}
[Fact]
public void Map_Six_NamedTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 12).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6),
(int Id7, int Id8),
(int Id9, int Id10),
(int Id11, int Id12)>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
}
record R1112(int Id11, int Id12);
[Fact]
public void Map_Six_Records_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 12).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6) = connection.Read<
R12,
R34,
R56,
R78,
R910,
R1112>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
}
[Fact]
public void Map_Seven_NamedTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 14).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6),
(int Id7, int Id8),
(int Id9, int Id10),
(int Id11, int Id12),
(int Id13, int Id14)> (sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
}
record R1314(int Id13, int Id14);
[Fact]
public void Map_Seven_Records_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 14).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7) = connection.Read<
R12,
R34,
R56,
R78,
R910,
R1112,
R1314>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
}
[Fact]
public void Map_Eight_NamedTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 16).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7, result8) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6),
(int Id7, int Id8),
(int Id9, int Id10),
(int Id11, int Id12),
(int Id13, int Id14),
(int Id15, int Id16)>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
Assert.Equal(15, result8.Id15);
Assert.Equal(16, result8.Id16);
}
record R1516(int Id15, int Id16);
[Fact]
public void Map_Eight_Records_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 16).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7, result8) = connection.Read<
R12,
R34,
R56,
R78,
R910,
R1112,
R1314,
R1516>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
Assert.Equal(15, result8.Id15);
Assert.Equal(16, result8.Id16);
}
[Fact]
public void Map_Nine_NamedTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 18).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7, result8, result9) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6),
(int Id7, int Id8),
(int Id9, int Id10),
(int Id11, int Id12),
(int Id13, int Id14),
(int Id15, int Id16),
(int Id17, int Id18)>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
Assert.Equal(15, result8.Id15);
Assert.Equal(16, result8.Id16);
Assert.Equal(17, result9.Id17);
Assert.Equal(18, result9.Id18);
}
record R1718(int Id17, int Id18);
[Fact]
public void Map_Nine_Records_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 18).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7, result8, result9) = connection.Read<
R12,
R34,
R56,
R78,
R910,
R1112,
R1314,
R1516,
R1718>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
Assert.Equal(15, result8.Id15);
Assert.Equal(16, result8.Id16);
Assert.Equal(17, result9.Id17);
Assert.Equal(18, result9.Id18);
}
[Fact]
public void Map_Ten_NamedTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 20).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7, result8, result9, result10) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6),
(int Id7, int Id8),
(int Id9, int Id10),
(int Id11, int Id12),
(int Id13, int Id14),
(int Id15, int Id16),
(int Id17, int Id18),
(int Id19, int Id20)>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
Assert.Equal(15, result8.Id15);
Assert.Equal(16, result8.Id16);
Assert.Equal(17, result9.Id17);
Assert.Equal(18, result9.Id18);
Assert.Equal(19, result10.Id19);
Assert.Equal(20, result10.Id20);
}
record R1920(int Id19, int Id20);
[Fact]
public void Map_Ten_Records_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 20).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7, result8, result9, result10) = connection.Read<
R12,
R34,
R56,
R78,
R910,
R1112,
R1314,
R1516,
R1718,
R1920>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
Assert.Equal(15, result8.Id15);
Assert.Equal(16, result8.Id16);
Assert.Equal(17, result9.Id17);
Assert.Equal(18, result9.Id18);
Assert.Equal(19, result10.Id19);
Assert.Equal(20, result10.Id20);
}
[Fact]
public void Map_Eleven_NamedTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 22).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6),
(int Id7, int Id8),
(int Id9, int Id10),
(int Id11, int Id12),
(int Id13, int Id14),
(int Id15, int Id16),
(int Id17, int Id18),
(int Id19, int Id20),
(int Id21, int Id22)>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
Assert.Equal(15, result8.Id15);
Assert.Equal(16, result8.Id16);
Assert.Equal(17, result9.Id17);
Assert.Equal(18, result9.Id18);
Assert.Equal(19, result10.Id19);
Assert.Equal(20, result10.Id20);
Assert.Equal(21, result11.Id21);
Assert.Equal(22, result11.Id22);
}
record R2122(int Id21, int Id22);
[Fact]
public void Map_Eleven_Records_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 22).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11) = connection.Read<
R12,
R34,
R56,
R78,
R910,
R1112,
R1314,
R1516,
R1718,
R1920,
R2122>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
Assert.Equal(15, result8.Id15);
Assert.Equal(16, result8.Id16);
Assert.Equal(17, result9.Id17);
Assert.Equal(18, result9.Id18);
Assert.Equal(19, result10.Id19);
Assert.Equal(20, result10.Id20);
Assert.Equal(21, result11.Id21);
Assert.Equal(22, result11.Id22);
}
[Fact]
public void Map_Twelve_NamedTuples_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 24).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12) = connection.Read<
(int Id1, int Id2),
(int Id3, int Id4),
(int Id5, int Id6),
(int Id7, int Id8),
(int Id9, int Id10),
(int Id11, int Id12),
(int Id13, int Id14),
(int Id15, int Id16),
(int Id17, int Id18),
(int Id19, int Id20),
(int Id21, int Id22),
(int Id23, int Id24)>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
Assert.Equal(15, result8.Id15);
Assert.Equal(16, result8.Id16);
Assert.Equal(17, result9.Id17);
Assert.Equal(18, result9.Id18);
Assert.Equal(19, result10.Id19);
Assert.Equal(20, result10.Id20);
Assert.Equal(21, result11.Id21);
Assert.Equal(22, result11.Id22);
Assert.Equal(23, result12.Id23);
Assert.Equal(24, result12.Id24);
}
record R2324(int Id23, int Id24);
[Fact]
public void Map_Twelve_Records_Sync()
{
using var connection = new NpgsqlConnection(fixture.ConnectionString);
var sql = string.Concat("select ",
string.Join(", ", Enumerable.Repeat(1, 24).Select((e, i) => $"{e + i} as id{e + i}")));
var (result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12) = connection.Read<
R12,
R34,
R56,
R78,
R910,
R1112,
R1314,
R1516,
R1718,
R1920,
R2122,
R2324>(sql).Single();
Assert.Equal(1, result1.Id1);
Assert.Equal(2, result1.Id2);
Assert.Equal(3, result2.Id3);
Assert.Equal(4, result2.Id4);
Assert.Equal(5, result3.Id5);
Assert.Equal(6, result3.Id6);
Assert.Equal(7, result4.Id7);
Assert.Equal(8, result4.Id8);
Assert.Equal(9, result5.Id9);
Assert.Equal(10, result5.Id10);
Assert.Equal(11, result6.Id11);
Assert.Equal(12, result6.Id12);
Assert.Equal(13, result7.Id13);
Assert.Equal(14, result7.Id14);
Assert.Equal(15, result8.Id15);
Assert.Equal(16, result8.Id16);
Assert.Equal(17, result9.Id17);
Assert.Equal(18, result9.Id18);
Assert.Equal(19, result10.Id19);
Assert.Equal(20, result10.Id20);
Assert.Equal(21, result11.Id21);
Assert.Equal(22, result11.Id22);
Assert.Equal(23, result12.Id23);
Assert.Equal(24, result12.Id24);
}
}
}
| 33.421559 | 187 | 0.51617 | [
"MIT"
] | vb-consulting/Norm.net | Tests/PostgreSqlUnitTests/QueryMultipleMapsUnitTests.cs | 34,727 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Fabric;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace FabricObserverWeb
{
[Route("api/ObserverManager")]
[Produces("text/html")]
[ApiController]
public class ObserverManagerController : ControllerBase
{
private const int MaxRetries = 3;
private readonly StatelessServiceContext serviceContext;
private readonly FabricClient fabricClient;
private const string script = @"
<script type='text/javascript'>
function toggle(e) {
var container = document.getElementById(e);
var plusMarker = document.getElementById('plus');
if (container === null)
return;
if (container.style.display === 'none') {
container.style.display = 'block';
plusMarker.innerText = '-';
window.scrollBy(0, 350);
} else {
container.style.display = 'none';
plusMarker.innerText = '+';
}
}
</script>";
private StringBuilder sb;
/// <summary>
/// Initializes a new instance of the <see cref="ObserverManagerController"/> class.
/// </summary>
/// <param name="serviceContext">service context.</param>
/// <param name="fabricClient">FabricClient instance.</param>
public ObserverManagerController(StatelessServiceContext serviceContext, FabricClient fabricClient)
{
this.serviceContext = serviceContext;
this.fabricClient = fabricClient;
}
// GET: api/ObserverManager
[Produces("text/html")]
[HttpGet]
public string Get()
{
string html = string.Empty;
string nodeName = serviceContext.NodeContext.NodeName;
var configSettings = serviceContext.CodePackageActivationContext.GetConfigurationPackageObject("Config").Settings;
string logFolder = null;
string obsManagerLogFilePath = null;
if (configSettings != null)
{
logFolder = Utilities.GetConfigurationSetting(configSettings, "FabricObserverLogs", "FabricObserverLogFolderName");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// Add current drive letter if not supplied for Windows path target.
if (!logFolder[..3].Contains(":\\"))
{
string windrive = Environment.SystemDirectory[..3];
logFolder = Path.Combine(windrive, logFolder);
}
}
else
{
// Remove supplied drive letter if Linux is the runtime target.
if (logFolder[..3].Contains(":\\"))
{
logFolder = logFolder.Remove(0, 3);
}
}
var obsManagerLogFolderPath = Path.Combine(logFolder, "ObserverManager");
obsManagerLogFilePath = Path.Combine(obsManagerLogFolderPath, "ObserverManager.log");
}
// Implicit retry loop. Will run only once if no exceptions arise.
// Can only run at most MaxRetries times.
for (int i = 0; i < MaxRetries; i++)
{
try
{
string netFileInfoPath = Path.Combine(logFolder, "NetInfo.txt");
string sysFileInfoPath = Path.Combine(logFolder, "SysInfo.txt");
string evtVwrErrorLogPath = Path.Combine(logFolder, "EventVwrErrors.txt");
string diskFileInfoPath = Path.Combine(logFolder, "disks.txt");
string sfInfraInfoPath = Path.Combine(logFolder, "SFInfraInfo.txt");
string sysInfofileText = string.Empty, evtVwrErrorsText = string.Empty, log = string.Empty, diskInfoTxt = string.Empty, appHealthText = string.Empty, sfInfraText = string.Empty, netInfofileText = string.Empty;
// Only show info from current day, by default. This is just for web UI (html).
if (System.IO.File.Exists(obsManagerLogFilePath)
&& System.IO.File.GetCreationTimeUtc(obsManagerLogFilePath).ToShortDateString() == DateTime.UtcNow.ToShortDateString())
{
log = System.IO.File.ReadAllText(obsManagerLogFilePath, Encoding.UTF8).Replace("\n", "<br/>");
}
if (System.IO.File.Exists(netFileInfoPath))
{
netInfofileText = "\n\n" + System.IO.File.ReadAllText(netFileInfoPath, Encoding.UTF8).Trim();
}
if (System.IO.File.Exists(sysFileInfoPath))
{
sysInfofileText = System.IO.File.ReadAllText(sysFileInfoPath, Encoding.UTF8).Trim();
}
if (System.IO.File.Exists(evtVwrErrorLogPath))
{
evtVwrErrorsText = System.IO.File.ReadAllText(evtVwrErrorLogPath).Replace("\n", "<br/>");
}
if (System.IO.File.Exists(diskFileInfoPath))
{
diskInfoTxt = System.IO.File.ReadAllText(diskFileInfoPath, Encoding.UTF8).Trim();
}
if (System.IO.File.Exists(sfInfraInfoPath))
{
sfInfraText = System.IO.File.ReadAllText(sfInfraInfoPath, Encoding.UTF8).Trim();
}
// Node links..
string nodeLinks = string.Empty;
var nodeList = fabricClient.QueryManager.GetNodeListAsync().Result;
var ordered = nodeList.OrderBy(node => node.NodeName);
string host = Request.Host.Value;
// Request originating from ObserverWeb node hyperlinks.
if (Request.QueryString.HasValue && Request.Query.ContainsKey("fqdn"))
{
host = Request.Query["fqdn"];
foreach (var node in ordered)
{
nodeLinks += "| <a href='" + Request.Scheme + "://" + host + "/api/ObserverManager/" + node.NodeName + "'>" + node.NodeName + "</a> | ";
}
}
sb = new StringBuilder();
_ = sb.AppendLine("<html>\n\t<head>");
_ = sb.AppendLine("\n\t\t<title>FabricObserver Node Health Information: Errors and Warnings</title>");
_ = sb.AppendLine("\n\t\t" + script);
_ = sb.AppendLine("\n\t\t<style type=\"text/css\">\n" +
"\t\t\t.container {\n" +
"\t\t\t\tfont-family: Consolas; font-size: 14px; background-color: lightblue; padding: 5px; border: 1px solid grey; " +
"width: 98%;\n" +
"\t\t\t}\n" +
"\t\t\t.header {\n" +
"\t\t\t\tfont-size: 25px; text-align: center; background-color: lightblue; " +
"padding 5px; margin-bottom: 10px;\n" +
"\t\t\t}\n" +
"\t\t\tpre {\n" +
"\t\t\t\toverflow-x: auto; white-space: pre-wrap; white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; word-wrap: break-word;" +
"\t\t\t}\n" +
"\t\t\t a:link { text-decoration: none; }" +
"\n\t\t</style>");
_ = sb.AppendLine("\n\t</head>");
_ = sb.AppendLine("\n\t<body>");
_ = sb.AppendLine("\n\t\t\t <br/>");
if (!string.IsNullOrWhiteSpace(sysInfofileText))
{
_ = sb.AppendLine("\n\t\t\t<div class=\"container\"><div style=\"position: relative; width: 80%; margin-left: auto; margin-right: auto; font-family: Consolas;\"><br/>" +
"<h2>Host Machine and Service Fabric Information: Node " + serviceContext.NodeContext.NodeName + "</h2>" + nodeLinks + "<pre>" +
sysInfofileText + "\n\nDisk Info: \n\n" + diskInfoTxt + netInfofileText + "\n\n" + sfInfraText + "</pre></div></div>");
}
_ = sb.AppendLine("\n\t\t\t\t<div class=\"container\"><div style=\"position: relative; width: 100%; margin-left: auto; margin-right: auto;\">" +
"<br/><strong>Daily Errors and Warnings on " + nodeName + " - " + DateTime.UtcNow.ToString("MM/dd/yyyy") + " UTC</strong><br/><br/>" + log + appHealthText + "</div>");
if (!string.IsNullOrWhiteSpace(evtVwrErrorsText))
{
_ = sb.AppendLine("\n\t\t\t" + evtVwrErrorsText);
}
_ = sb.AppendLine("\n\t\t\t</div>");
_ = sb.AppendLine("\n\t</body>");
_ = sb.AppendLine("</html>");
html = sb.ToString();
_ = sb.Clear();
break;
}
catch (IOException e)
{
html = e.ToString();
}
// If we get here, let's wait a few seconds before the next iteration.
Task.Delay(2000).Wait();
}
return html;
}
// GET: api/ObserverManager/_SFRole_0
[HttpGet("{name}", Name = "GetNode")]
public string Get(string name)
{
try
{
var node = fabricClient.QueryManager.GetNodeListAsync(name).Result;
if (node.Count <= 0)
{
return "no node found with that name.";
}
var addr = node[0].IpAddressOrFQDN;
// Only use this API over SSL, but not in LRC.
if (!addr.Contains("http://"))
{
addr = "http://" + addr;
}
string fqdn = "?fqdn=" + Request.Host;
var req = WebRequest.Create(addr + ":5000/api/ObserverManager" + fqdn);
req.Credentials = CredentialCache.DefaultCredentials;
var response = (HttpWebResponse)req.GetResponse();
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream ?? throw new InvalidOperationException("Get: dataStream is null."));
string responseFromServer = reader.ReadToEnd();
var ret = responseFromServer;
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
return ret;
}
catch (Exception e)
{
return e.ToString();
}
}
}
} | 46.330769 | 229 | 0.487631 | [
"MIT"
] | NCarlsonMSFT/service-fabric-observer | FabricObserverWeb/Controllers/ObserverManagerController.cs | 12,048 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using EnsureThat;
using FellowOakDicom;
using FellowOakDicom.IO.Buffer;
namespace Microsoft.Health.Dicom.Tests.Common.Comparers;
/// <summary>
/// Compare if 2 DicomItem equals or not.
/// Most DicomItem doesn't have method Equals implented, so has to make it ourselves.
/// </summary>
public class DicomItemEqualityComparer : IEqualityComparer<DicomItem>
{
public static DicomItemEqualityComparer Default { get; } = new DicomItemEqualityComparer();
public bool Equals([AllowNull] DicomItem x, [AllowNull] DicomItem y)
{
if (x == null || y == null)
{
return object.ReferenceEquals(x, y);
}
if (x.GetType() != y.GetType())
{
return false;
}
if (typeof(DicomElement).IsAssignableFrom(x.GetType()))
{
return DicomElementEquals((DicomElement)x, (DicomElement)y);
}
// It's not perfect, but enough for our test
return x.Equals(y);
}
private bool DicomItemEquals(DicomItem x, DicomItem y)
{
return x.Tag == y.Tag && x.ValueRepresentation == y.ValueRepresentation;
}
private bool DicomElementEquals(DicomElement x, DicomElement y)
{
return DicomItemEquals(x, y) && x.Count == y.Count && ByteBufferEquals(x.Buffer, y.Buffer);
}
private bool ByteBufferEquals(IByteBuffer x, IByteBuffer y)
{
if (x == null || y == null)
{
return object.ReferenceEquals(x, y);
}
if (x.Size != y.Size)
{
return false;
}
for (int i = 0; i < x.Size; i++)
{
if (x.Data[i] != y.Data[i])
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DicomItem obj)
{
EnsureArg.IsNotNull(obj, nameof(obj));
return obj.GetHashCode();
}
}
| 28.47561 | 101 | 0.549465 | [
"MIT"
] | IoTFier/dicom-server | src/Microsoft.Health.Dicom.Tests.Common/Comparers/DicomItemEqualityComparer.cs | 2,337 | C# |
namespace ClearHl7.Codes.V231
{
/// <summary>
/// HL7 Version 2 Table 0286 - Provider Role.
/// </summary>
/// <remarks>https://www.hl7.org/fhir/v2/0286</remarks>
public enum CodeProviderRole
{
/// <summary>
/// CP - Consulting Provider.
/// </summary>
ConsultingProvider,
/// <summary>
/// PP - Primary Care Provider.
/// </summary>
PrimaryCareProvider,
/// <summary>
/// RP - Referring Provider.
/// </summary>
ReferringProvider,
/// <summary>
/// RT - Referred to Provider.
/// </summary>
ReferredToProvider
}
} | 24.068966 | 59 | 0.492837 | [
"MIT"
] | davebronson/clear-hl7-net | src/ClearHl7.Codes/V231/CodeProviderRole.cs | 700 | C# |
// MADE Apps licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace MADE.UI.Controls
{
using System.Collections.Generic;
using System.Windows.Input;
using Windows.UI.Xaml;
/// <summary>
/// Defines an interface for a multi value input text box control.
/// </summary>
public interface IChipBox
{
/// <summary>
/// Occurs when the text has changed within the suggestion box.
/// </summary>
event ChipBoxTextChangedEventHandler TextChanged;
/// <summary>
/// Occurs when a chip has been removed.
/// </summary>
event ChipBoxChipRemovedEventHandler ChipRemoved;
/// <summary>
/// Gets or sets the <see cref="ICommand"/> associated with when the text has changed within the suggestion box.
/// </summary>
ICommand TextChangeCommand { get; set; }
/// <summary>
/// Gets or sets the <see cref="ICommand"/> associated with when a chip has been removed.
/// </summary>
ICommand ChipRemoveCommand { get; set; }
/// <summary>
/// Gets or sets the data used for the header of each control.
/// </summary>
object Header { get; set; }
/// <summary>
/// Gets or sets the template used to display the content of the control's header.
/// </summary>
DataTemplate HeaderTemplate { get; set; }
/// <summary>
/// Gets or sets an object source used to generate the chip content of the control.
/// </summary>
IList<ChipItem> Chips { get; set; }
/// <summary>
/// Gets or sets the template associated with the content displayed in the chip.
/// </summary>
DataTemplate ChipContentTemplate { get; set; }
/// <summary>
/// Gets or sets the style of the items view.
/// </summary>
Style ChipItemsViewStyle { get; set; }
/// <summary>
/// Gets or sets the suggestions that are displayed to the user when typing.
/// </summary>
object Suggestions { get; set; }
/// <summary>
/// Gets or sets the template used to display the suggestions that are displayed to the user when typing.
/// </summary>
DataTemplate SuggestionsItemTemplate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to allow duplicate values to be accepted.
/// </summary>
bool AllowDuplicate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to allow free text input.
/// </summary>
bool AllowFreeText { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the control is in a read-only state.
/// </summary>
bool IsReadonly { get; set; }
}
}
| 33.895349 | 120 | 0.589708 | [
"MIT"
] | MADE-Apps/MADE-Uno | src/MADE.UI.Controls.ChipBox/IChipBox.cs | 2,915 | C# |
using ApplicationCore.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApplicationCore.Specifications
{
public class TaskSpecification :BaseSpecification<TaskEntity>
{
public TaskSpecification()
: base(null)
{
}
}
}
| 17.941176 | 65 | 0.678689 | [
"MIT"
] | alexsoler/Queue-Manager | src/AplicationCore/Specifications/TaskSpecification.cs | 307 | C# |
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.Logging.V2;
using Moq;
using Xunit;
namespace Google.Cloud.Diagnostics.Common.Tests
{
public class ErrorReportingOptionsTest
{
private const string _projectId = "pid";
private static readonly LoggingServiceV2Client _loggingClient = new Mock<LoggingServiceV2Client>().Object;
[Fact]
public void CreateConsumer_ErrorToLogsConsumer()
{
var eventTarget = EventTarget.ForLogging(_projectId, "test-log", _loggingClient);
var options = ErrorReportingOptions.Create(eventTarget);
var consumer = options.CreateConsumer();
Assert.IsType<RpcRetryConsumer<LogEntry>>(consumer);
var retryConsumer = (RpcRetryConsumer<LogEntry>) consumer;
Assert.IsType<GrpcLogConsumer>(retryConsumer._consumer);
}
[Fact]
public void CreateConsumer_BufferedConsumer()
{
var bufferOptions = BufferOptions.SizedBuffer();
var eventTarget = EventTarget.ForLogging(_projectId, "test-log", _loggingClient);
var options = ErrorReportingOptions.Create(eventTarget, bufferOptions);
var consumer = options.CreateConsumer();
Assert.IsType<SizedBufferingConsumer<LogEntry>>(consumer);
}
}
}
| 38.959184 | 114 | 0.695652 | [
"Apache-2.0"
] | Mattlk13/google-cloud-dotnet | apis/Google.Cloud.Diagnostics.Common/Google.Cloud.Diagnostics.Common.Tests/ErrorReporting/ErrorReportingOptionsTest.cs | 1,911 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 12.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "12.0.0.0")]
public partial class AWSQueryRequestMarshaller : BaseRequestMarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("namespace ");
#line 11 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// ");
#line 14 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(" Request Marshaller\r\n /// </summary> \r\n public class ");
#line 16 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("RequestMarshaller : IMarshaller<IRequest, ");
#line 16 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(@"Request> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name=""input""></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((");
#line 25 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(@"Request)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name=""publicRequest""></param>
/// <returns></returns>
public IRequest Marshall(");
#line 33 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Request publicRequest)\r\n {\r\n IRequest request = new DefaultRequ" +
"est(publicRequest, \"");
#line 35 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write("\");\r\n request.Parameters.Add(\"Action\", \"");
#line 36 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("\");\r\n request.Parameters.Add(\"Version\", \"");
#line 37 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ServiceModel.APIVersion));
#line default
#line hidden
this.Write("\");\r\n\r\n if(publicRequest != null)\r\n {\r\n");
#line 41 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
var requestStructure = this.Operation.RequestStructure;
if(requestStructure != null)
ProcessMembers(0, "", "publicRequest", requestStructure.Members);
#line default
#line hidden
this.Write(" }\r\n return request;\r\n }\r\n }\r\n}\r\n\r\n");
return this.GenerationEnvironment.ToString();
}
#line 52 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
void ProcessMembers(int level, string parameterContext, string variableName, IEnumerable<Member> members)
{
string variableNameFragment = variableName.Replace(".", string.Empty);
foreach(var member in members)
{
if (GeneratorHelpers.UseCustomMarshall(member, this.Operation))
continue;
var marshallName = GeneratorHelpers.DetermineAWSQueryMarshallName(member, this.Operation);
#line default
#line hidden
#line 63 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 63 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" if(");
#line default
#line hidden
#line 63 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 63 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 63 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 63 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("())\r\n");
#line default
#line hidden
#line 64 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 64 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 65 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
if(member.IsList )
{
string context = ComposeContext(parameterContext, marshallName);
string listItemContext = ComposeContext(context,
GeneratorHelpers.DetermineAWSQueryListMemberPrefix(member),
variableNameFragment + "listValueIndex",
GeneratorHelpers.DetermineAWSQueryListMemberSuffix(this.Operation, member));
#line default
#line hidden
#line 74 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 74 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" int ");
#line default
#line hidden
#line 74 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableNameFragment));
#line default
#line hidden
#line 74 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("listValueIndex = 1;\r\n");
#line default
#line hidden
#line 75 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 75 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" foreach(var ");
#line default
#line hidden
#line 75 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableNameFragment));
#line default
#line hidden
#line 75 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("listValue in ");
#line default
#line hidden
#line 75 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 75 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 75 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 75 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(")\r\n");
#line default
#line hidden
#line 76 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 76 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 77 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
if(member.Shape.ListShape.IsStructure)
{
ProcessMembers(level + 2, listItemContext, variableNameFragment + "listValue", member.Shape.ListShape.Members);
}
else
{
if(string.IsNullOrEmpty(member.CustomMarshallerTransformation))
{
#line default
#line hidden
#line 87 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 87 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 87 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listItemContext));
#line default
#line hidden
#line 87 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", StringUtils.From");
#line default
#line hidden
#line 87 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.Shape.ListShape.GetPrimitiveType()));
#line default
#line hidden
#line 87 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 87 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableNameFragment));
#line default
#line hidden
#line 87 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("listValue));\r\n");
#line default
#line hidden
#line 88 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
else
{
#line default
#line hidden
#line 93 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 93 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 93 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listItemContext));
#line default
#line hidden
#line 93 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", ");
#line default
#line hidden
#line 93 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.CustomMarshallerTransformation + "(" + variableNameFragment + "listValue)"));
#line default
#line hidden
#line 93 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 94 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
}
#line default
#line hidden
#line 98 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 98 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" ");
#line default
#line hidden
#line 98 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableNameFragment));
#line default
#line hidden
#line 98 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("listValueIndex++;\r\n");
#line default
#line hidden
#line 99 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 99 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 100 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
else if(member.IsMap)
{
string context = ComposeContext(parameterContext, marshallName);
string mapItemContext = ComposeContext(context, member.Shape.IsFlattened ? "" : "entry", "mapIndex");
string mapKeyContext = ComposeContext(mapItemContext, member.Shape.KeyMarshallName);
string mapValueContext = ComposeContext(mapItemContext, member.Shape.ValueMarshallName);
#line default
#line hidden
#line 109 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 109 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" int mapIndex = 1;\r\n");
#line default
#line hidden
#line 110 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 110 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" foreach(var key in ");
#line default
#line hidden
#line 110 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 110 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 110 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 110 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".Keys)\r\n");
#line default
#line hidden
#line 111 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 111 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 112 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 112 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" ");
#line default
#line hidden
#line 112 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.Shape.ValueShape.IsStructure ? member.Shape.ValueShape.Name : member.Shape.ValueShape.GetPrimitiveType()));
#line default
#line hidden
#line 112 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" value;\r\n");
#line default
#line hidden
#line 113 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 113 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" bool hasValue = ");
#line default
#line hidden
#line 113 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 113 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 113 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 113 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".TryGetValue(key, out value);\r\n");
#line default
#line hidden
#line 114 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 114 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 114 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(mapKeyContext));
#line default
#line hidden
#line 114 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", StringUtils.From");
#line default
#line hidden
#line 114 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.Shape.KeyShape.GetPrimitiveType()));
#line default
#line hidden
#line 114 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("(key));\r\n");
#line default
#line hidden
#line 115 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 115 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" if (hasValue)\r\n");
#line default
#line hidden
#line 116 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 116 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 117 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
if(member.Shape.ValueShape.IsStructure)
{
ProcessMembers(level + 3, mapValueContext, "value", member.Shape.ValueShape.Members);
}
else
{
if(string.IsNullOrEmpty(member.CustomMarshallerTransformation))
{
#line default
#line hidden
#line 127 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 127 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 127 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(mapValueContext));
#line default
#line hidden
#line 127 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", StringUtils.From");
#line default
#line hidden
#line 127 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.Shape.ValueShape.GetPrimitiveType()));
#line default
#line hidden
#line 127 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("(value));\r\n");
#line default
#line hidden
#line 128 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
else
{
#line default
#line hidden
#line 132 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 132 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 132 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(mapValueContext));
#line default
#line hidden
#line 132 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", ");
#line default
#line hidden
#line 132 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.CustomMarshallerTransformation + "(value)"));
#line default
#line hidden
#line 132 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 133 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
}
#line default
#line hidden
#line 137 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 137 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 138 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 138 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" mapIndex++;\r\n");
#line default
#line hidden
#line 139 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 139 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 140 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
else if(member.IsStructure)
{
string context = ComposeContext(parameterContext, marshallName);
ProcessMembers(level + 1, context, variableName + "." + member.PropertyName, member.Shape.Members);
}
else
{
string context = ComposeContext(parameterContext, marshallName);
if(string.IsNullOrEmpty(member.CustomMarshallerTransformation))
{
#line default
#line hidden
#line 153 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 153 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 153 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(context));
#line default
#line hidden
#line 153 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", StringUtils.From");
#line default
#line hidden
#line 153 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.GetPrimitiveType()));
#line default
#line hidden
#line 153 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 153 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 153 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 153 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 153 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 154 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
else
{
#line default
#line hidden
#line 158 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 158 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 158 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(context));
#line default
#line hidden
#line 158 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", ");
#line default
#line hidden
#line 158 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.CustomMarshallerTransformation + "(" + variableName + "." + member.PropertyName + ")"));
#line default
#line hidden
#line 158 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 159 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
}
#line default
#line hidden
#line 163 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 163 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 164 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
}
string ComposeContext(string context, string marshallName)
{
return ComposeContext(context, marshallName, null, null);
}
string ComposeContext(string context, string marshallName, string variableName)
{
return ComposeContext(context, marshallName, variableName, null);
}
string ComposeContext(string context, string marshallName, string variableName, string suffixMember)
{
string nc = context;
if (!string.IsNullOrEmpty(marshallName))
nc = AppendText(nc, marshallName);
if (!string.IsNullOrEmpty(variableName))
nc = AppendVariable(nc, variableName);
if (!string.IsNullOrEmpty(suffixMember))
nc = AppendText(nc, suffixMember);
return nc;
}
private static char quoteChar = '\"';
private static string quote = quoteChar.ToString();
string AppendVariable(string context, string variable)
{
variable = variable.Trim(quoteChar);
return Append(context, variable);
}
string AppendText(string context, string text)
{
if (!text.StartsWith(quote))
text = quote + text;
if (!text.EndsWith(quote))
text = text + quote;
return Append(context, text);
}
string Append(string context, string text)
{
string nc = context;
if (!string.IsNullOrEmpty(nc) && !nc.EndsWith("."))
nc += " + \".\" + ";
nc += text;
return nc;
}
#line default
#line hidden
}
#line default
#line hidden
}
| 37.152174 | 165 | 0.658255 | [
"Apache-2.0"
] | jasoncwik/aws-sdk-net | generator/ServiceClientGeneratorLib/Generators/Marshallers/AWSQueryRequestMarshaller.cs | 41,018 | C# |
using FakeItEasy;
using i5.Toolkit.Core.Editor.TestHelpers;
using i5.Toolkit.Core.ModelImporters;
using i5.Toolkit.Core.ServiceCore;
using i5.Toolkit.Core.TestHelpers;
using i5.Toolkit.Core.TestUtilities;
using i5.Toolkit.Core.Utilities;
using i5.Toolkit.Core.Utilities.ContentLoaders;
using NUnit.Framework;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.TestTools;
namespace i5.Toolkit.Core.Tests.ModelImporters
{
/// <summary>
/// Tests for the ObjImporter class
/// </summary>
public class ObjImporterTests
{
/// <summary>
/// Contents of the .obj files
/// There is a file with no object, one object and three objects
/// </summary>
private static string emptyObj, cubeObj, threeObj;
/// <summary>
/// Contents of the .mtl files
/// There is a file with no material, one material and three materials
/// </summary>
private static string emptyMtl, cubeMtl, threeMtl;
/// <summary>
/// Called one time to load the contents of the .obj and .mtl files
/// </summary>
[OneTimeSetUp]
public void LoadData()
{
string basePath = "Tests/Editor/Importers/Data/";
cubeObj = File.ReadAllText(PackagePathUtils.GetPackagePath() + basePath + "Cube.obj");
emptyObj = File.ReadAllText(PackagePathUtils.GetPackagePath() + basePath + "EmptyObj.obj");
threeObj = File.ReadAllText(PackagePathUtils.GetPackagePath() + basePath + "ThreeObj.obj");
cubeMtl = File.ReadAllText(PackagePathUtils.GetPackagePath() + basePath + "Cube.mtl");
emptyMtl = File.ReadAllText(PackagePathUtils.GetPackagePath() + basePath + "EmptyObj.mtl");
threeMtl = File.ReadAllText(PackagePathUtils.GetPackagePath() + basePath + "ThreeObj.mtl");
}
/// <summary>
/// Resets the scene to the standard test scene before executed each test
/// </summary>
[SetUp]
public void ResetScene()
{
EditModeTestUtilities.ResetScene();
}
/// <summary>
/// Reusable function to set up the ObjImporter service and to register it at the service manager
/// </summary>
/// <param name="objContent">The .obj that the fake loader of the obj importer should load</param>
/// <param name="mtlContent">The .mtl that the fake loader of the obj importer should load</param>
/// <returns></returns>
private ObjImporter SetUpObjImporter(string objContent, string mtlContent)
{
ObjImporter objImporter = new ObjImporter();
IServiceManager serviceManager = A.Fake<IServiceManager>();
objImporter.Initialize(serviceManager);
objImporter.ContentLoader = FakeContentLoaderFactory.CreateFakeLoader(objContent);
objImporter.MtlLibrary.ContentLoader = FakeContentLoaderFactory.CreateFakeLoader(mtlContent);
return objImporter;
}
/// <summary>
/// Checks that the ContentLoader is initialized with the UnityWebRequestLoader by default
/// </summary>
[Test]
public void ContentLoader_Initialized_InitWithUnityWebRequestLoader()
{
ObjImporter objImporter = new ObjImporter();
IServiceManager serviceManager = A.Fake<IServiceManager>();
objImporter.Initialize(serviceManager);
Assert.NotNull(objImporter.ContentLoader);
Assert.True(objImporter.ContentLoader.GetType() == typeof(UnityWebRequestLoader));
}
/// <summary>
/// Checks that the service initialization automatically initializes the MtlLibrary
/// </summary>
[Test]
public void Initialize_Initialized_MtlLibrarySetUp()
{
ObjImporter objImporter = new ObjImporter();
IServiceManager serviceManager = A.Fake<IServiceManager>();
objImporter.Initialize(serviceManager);
Assert.NotNull(objImporter.MtlLibrary);
}
/// <summary>
/// Checks that hte obj importer creates a new pool
/// </summary>
[Test]
public void Initialize_CreatesNewPool()
{
ObjImporter objImporter = new ObjImporter();
IServiceManager serviceManager = A.Fake<IServiceManager>();
int poolCount = ObjectPool<GameObject>.CountPools();
objImporter.Initialize(serviceManager);
Assert.AreEqual(poolCount + 1, ObjectPool<GameObject>.CountPools());
}
[Test]
public void Cleanup_RemovesPool()
{
ObjImporter objImporter = new ObjImporter();
IServiceManager serviceManager = A.Fake<IServiceManager>();
int poolCount = ObjectPool<GameObject>.CountPools();
objImporter.Initialize(serviceManager);
Assert.AreEqual(poolCount + 1, ObjectPool<GameObject>.CountPools());
objImporter.Cleanup();
Assert.AreEqual(poolCount, ObjectPool<GameObject>.CountPools());
}
/// <summary>
/// Checks that ImportAsync returns null if the web request failed
/// </summary>
/// <returns></returns>
[UnityTest]
public IEnumerator ImportAsync_WebRequestFailed_ReturnNull()
{
ObjImporter objImporter = new ObjImporter();
IServiceManager serviceManager = A.Fake<IServiceManager>();
objImporter.Initialize(serviceManager);
objImporter.ContentLoader = FakeContentLoaderFactory.CreateFakeFailLoader<string>();
LogAssert.Expect(LogType.Error, new Regex(@"\w*Error fetching obj. No object imported\w*"));
Task<GameObject> task = objImporter.ImportAsync("http://test.org/test.obj");
yield return AsyncTest.WaitForTask(task);
GameObject res = task.Result;
Assert.Null(res);
}
/// <summary>
/// Checks that ImportAsync sets the name of the GameObject correctly based on the name of the .obj file
/// </summary>
/// <returns></returns>
[UnityTest]
public IEnumerator ImportAsync_WebRequestSuccess_SetName()
{
ObjImporter objImporter = SetUpObjImporter(cubeObj, cubeMtl);
Task<GameObject> task = objImporter.ImportAsync("http://test.org/test.obj");
yield return AsyncTest.WaitForTask(task);
GameObject res = task.Result;
Assert.NotNull(res);
Assert.AreEqual("test", res.name);
}
/// <summary>
/// Checks that a GameObject is returned if an empty .obj is loaded
/// and that the corresponding warnings and errors are given
/// </summary>
/// <returns></returns>
[UnityTest]
public IEnumerator ImportAsync_EmptyObj_ReturnGameObject()
{
ObjImporter objImporter = SetUpObjImporter(emptyObj, emptyMtl);
LogAssert.Expect(LogType.Warning, new Regex(@"\w*There is an object without parsed vertices\w*"));
LogAssert.Expect(LogType.Error, new Regex(@"\w*No objects could be constructed.\w*"));
Task<GameObject> task = objImporter.ImportAsync("http://test.org/test.obj");
yield return AsyncTest.WaitForTask(task);
GameObject res = task.Result;
Assert.NotNull(res);
Assert.AreEqual(0, res.transform.childCount);
}
/// <summary>
/// Checks that a child object was created if the cube .obj file is imported
/// </summary>
/// <returns></returns>
[UnityTest]
public IEnumerator ImportAsync_CubeObj_HasChild()
{
ObjImporter objImporter = SetUpObjImporter(cubeObj, cubeMtl);
Task<GameObject> testTask = objImporter.ImportAsync("http://test.org/test.obj");
yield return AsyncTest.WaitForTask(testTask);
GameObject res = testTask.Result;
Assert.NotNull(res);
Assert.AreEqual(1, res.transform.childCount);
}
/// <summary>
/// Checks that ImportAsync generates a child object with MeshFilter and MeshRenderer components
/// when importing the cube .obj file
/// </summary>
/// <returns></returns>
[UnityTest]
public IEnumerator ImportAsync_CubeObj_ChildHasComponents()
{
ObjImporter objImporter = SetUpObjImporter(cubeObj, cubeMtl);
Task<GameObject> task = objImporter.ImportAsync("http://test.org/test.obj");
yield return AsyncTest.WaitForTask(task);
GameObject res = task.Result;
MeshFilter mf = res.transform.GetChild(0).GetComponent<MeshFilter>();
Assert.NotNull(mf);
MeshRenderer mr = res.transform.GetChild(0).GetComponent<MeshRenderer>();
Assert.NotNull(mr);
}
/// <summary>
/// Checks that ImportAsync assigns the correct mesh to the created child GameObject
/// </summary>
/// <returns></returns>
[UnityTest]
public IEnumerator ImportAsync_CubeObj_ChildHasCorrectMesh()
{
ObjImporter objImporter = SetUpObjImporter(cubeObj, cubeMtl);
Task<GameObject> task = objImporter.ImportAsync("http://test.org/test.obj");
yield return AsyncTest.WaitForTask(task);
GameObject res = task.Result;
MeshFilter mf = res.transform.GetChild(0).GetComponent<MeshFilter>();
Assert.AreEqual(24, mf.sharedMesh.vertices.Length); // 8 * 3 = 24 (every vertex belongs to three triangles)
Assert.AreEqual(36, mf.sharedMesh.triangles.Length); // 12 *3 = 36
}
/// <summary>
/// Checks that ImportAsync assigns the correct material to the generated child GameObject
/// </summary>
/// <returns></returns>
[UnityTest]
public IEnumerator ImportAsync_CubeObj_ChildHasCorrectMaterial()
{
ObjImporter objImporter = SetUpObjImporter(cubeObj, cubeMtl);
Task<GameObject> task = objImporter.ImportAsync("http://test.org/test.obj");
yield return AsyncTest.WaitForTask(task);
GameObject res = task.Result;
MeshRenderer mr = res.transform.GetChild(0).GetComponent<MeshRenderer>();
Assert.AreEqual("TestMaterial", mr.sharedMaterial.name);
}
/// <summary>
/// Checks that ImportAsync creates three child objects for the three objects in ThreeObj.obj
/// </summary>
/// <returns></returns>
[UnityTest]
public IEnumerator ImportAsync_ThreeObj_HasThreeChildren()
{
ObjImporter objImporter = SetUpObjImporter(threeObj, threeMtl);
Task<GameObject> task = objImporter.ImportAsync("http://test.org/test.obj");
yield return AsyncTest.WaitForTask(task);
GameObject res = task.Result;
Assert.AreEqual(3, res.transform.childCount);
}
/// <summary>
/// Checks that ImportAsync creates an object wtih a default material if the .obj file could be loaded
/// but the .mtl file could not be loaded
/// </summary>
/// <returns></returns>
[UnityTest]
public IEnumerator ImportAsync_ObjFetchSuccessMtlFetchFail_CreateObjectWithDefaultMat()
{
ObjImporter objImporter = SetUpObjImporter(cubeObj, "");
objImporter.MtlLibrary.ContentLoader = FakeContentLoaderFactory.CreateFakeFailLoader<string>();
LogAssert.Expect(LogType.Error, new Regex(@"\w*This is a simulated fail\w*"));
LogAssert.Expect(LogType.Error, new Regex(@"\w*Could not load .mtl file\w*"));
Task<GameObject> task = objImporter.ImportAsync("http://test.org/test.obj");
yield return AsyncTest.WaitForTask(task);
GameObject res = task.Result;
Assert.NotNull(res);
Assert.AreEqual(1, res.transform.childCount);
MeshRenderer mr = res.transform.GetChild(0).GetComponent<MeshRenderer>();
Assert.AreEqual("New Material", mr.sharedMaterial.name);
}
}
} | 41.418301 | 120 | 0.614486 | [
"MIT"
] | BorisJov/i5-Toolkit-for-Unity | Assets/i5 Toolkit for Unity/Tests/Editor/Importers/ObjImporterTests.cs | 12,676 | C# |
using System;
using Abp.AspNetCore.SignalR.Hubs;
using Abp.Auditing;
using Castle.Core.Logging;
using Microsoft.AspNetCore.SignalR;
namespace Abp.RealTime
{
public class OnlineClientInfoProvider : IOnlineClientInfoProvider
{
private readonly IClientInfoProvider _clientInfoProvider;
public OnlineClientInfoProvider(IClientInfoProvider clientInfoProvider)
{
_clientInfoProvider = clientInfoProvider;
Logger = NullLogger.Instance;
}
public ILogger Logger { get; set; }
public IOnlineClient CreateClientForCurrentConnection(HubCallerContext context)
{
return new OnlineClient(
context.ConnectionId,
GetIpAddressOfClient(context),
context.GetTenantId(),
context.GetUserIdOrNull()
);
}
private string GetIpAddressOfClient(HubCallerContext context)
{
try
{
return _clientInfoProvider.ClientIpAddress;
}
catch (Exception ex)
{
Logger.Error("Can not find IP address of the client! connectionId: " + context.ConnectionId);
Logger.Error(ex.Message, ex);
return "";
}
}
}
}
| 28.021277 | 109 | 0.600607 | [
"MIT"
] | 861191244/aspnetboilerplate | src/Abp.AspNetCore.SignalR/RealTime/OnlineClientInfoProvider.cs | 1,317 | C# |
using System;
using AdventOfCode.UserClasses;
namespace AdventOfCode.Solutions.Year2019
{
class Day05 : ASolution
{
readonly long[] BaseProgram;
readonly IntCode2 cpu;
public Day05() : base(05, 2019, "")
{
BaseProgram = Input.ToLongArray(",");
cpu = new IntCode2(BaseProgram);
}
protected override string SolvePartOne()
{
long lastItem = long.MinValue;
cpu.ReadyInput(1);
foreach(long item in cpu.RunProgram())
{
Console.WriteLine(item);
lastItem = item;
}
return lastItem.ToString();
}
protected override string SolvePartTwo()
{
Console.WriteLine("Begin Part 2");
cpu.ClearInputs();
cpu.ReadyInput(5);
long lastItem = long.MinValue;
foreach (long item in cpu.RunProgram())
{
Console.WriteLine(item);
lastItem = item;
}
return lastItem.ToString();
}
}
} | 25.318182 | 51 | 0.507181 | [
"MIT"
] | Bpendragon/AdventOfCodeCSharp | AdventOfCode/Solutions/Year2019/Day05-Solution.cs | 1,114 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Task02_CompanyApp.BG
{
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | 18.882353 | 60 | 0.691589 | [
"MIT"
] | atanas-georgiev/TelerikAcademy | 16.ASP.NET-Web-Forms/Homeworks/04. ASP.NET-Master-Pages/Task02_CompanyApp/BG/About.aspx.cs | 323 | C# |
using Aspose.Diagram;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aspose.Diagram.Examples.CSharp.Working_Shapes
{
public class RerouteConnectors
{
public static void Run()
{
// ExStart:RerouteConnectors
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Shapes();
// Call a Diagram class constructor to load the VSDX diagram
Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx");
// Get page by name
Page page = diagram.Pages.GetPage("Page-3");
// Get a particular connector shape
Shape shape = page.Shapes.GetShape(18);
// Set reroute option
shape.Layout.ConFixedCode.Value = ConFixedCodeValue.NeverReroute;
// Save Visio diagram
diagram.Save(dataDir + "RerouteConnectors_out.vsdx", SaveFileFormat.VSDX);
// ExEnd:RerouteConnectors
}
}
}
| 31.272727 | 86 | 0.625969 | [
"MIT"
] | aliahmedaspose/Aspose.Diagram-for-.NET | Examples/CSharp/Working-Shapes/RerouteConnectors.cs | 1,034 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.VoiceID")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Voice ID. Released the Amazon Voice ID SDK, for usage with the Amazon Connect Voice ID feature released for Amazon Connect.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.7.0.44")] | 45.96875 | 210 | 0.74847 | [
"Apache-2.0"
] | raz2017/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/VoiceID/Properties/AssemblyInfo.cs | 1,471 | C# |
using System;
using System.Collections.Generic;
using Content.Server.AI.Operators.Sequences;
using Content.Server.AI.Utility.Considerations;
using Content.Server.AI.Utility.Considerations.Containers;
using Content.Server.AI.Utility.Considerations.Inventory;
using Content.Server.AI.Utility.Considerations.Movement;
using Content.Server.AI.WorldState;
using Content.Server.AI.WorldState.States;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
namespace Content.Server.AI.Utility.Actions.Clothing.Shoes
{
public sealed class PickUpShoes : UtilityAction
{
public EntityUid Target { get; set; } = default!;
public override void SetupOperators(Blackboard context)
{
ActionOperators = new GoPickupEntitySequence(Owner, Target).Sequence;
}
protected override void UpdateBlackboard(Blackboard context)
{
base.UpdateBlackboard(context);
context.GetState<TargetEntityState>().SetValue(Target);
}
protected override IReadOnlyCollection<Func<float>> GetConsiderations(Blackboard context)
{
var considerationsManager = IoCManager.Resolve<ConsiderationsManager>();
return new[]
{
considerationsManager.Get<CanPutTargetInInventoryCon>()
.BoolCurve(context),
considerationsManager.Get<TargetDistanceCon>()
.PresetCurve(context, PresetCurve.Distance),
considerationsManager.Get<TargetAccessibleCon>()
.BoolCurve(context),
};
}
}
}
| 35.065217 | 97 | 0.680099 | [
"MIT"
] | A-Box-12/space-station-14 | Content.Server/AI/Utility/Actions/Clothing/Shoes/PickUpShoes.cs | 1,613 | C# |
using Moq;
using NUnit.Framework;
using System;
namespace OtpSharp.Tests
{
[TestFixture]
public class OtpKeyInteractionTests
{
private Mock<IKeyProvider> keyMock
{
get
{
var mockable = new Mock<IKeyProvider>();
// setup the mock to just return the RFC test key as the computed hash no matter what.
// This will ensure that the OTP type has something to truncate and format and won't blow up.
mockable.Setup(x => x.ComputeHmac(It.IsAny<OtpHashMode>(), It.IsAny<byte[]>())).Returns(OtpCalculationTests.RfcTestKey);
return mockable;
}
}
private readonly DateTime totpDate = new DateTime(2000, 1, 1);
/// <summary>
/// This is the data that should be passed into the compute hmac for the given date above
/// </summary>
private readonly byte[] totpData = KeyUtilities.GetBigEndianBytes(31556160L);
private const long hotpCounter = 1;
private readonly byte[] hotpData = KeyUtilities.GetBigEndianBytes(1L);
[Test]
public void Totp_Sha1_Default_Called()
{
var mock = this.keyMock;
IKeyProvider key = mock.Object;
var totp = new Totp(key);
totp.ComputeTotp(totpDate);
mock.Verify(k => k.ComputeHmac(OtpHashMode.Sha1, totpData));
}
[Test]
public void Totp_Sha1_Called()
{
var mock = this.keyMock;
IKeyProvider key = mock.Object;
var totp = new Totp(key, mode: OtpHashMode.Sha1);
totp.ComputeTotp(totpDate);
mock.Verify(k => k.ComputeHmac(OtpHashMode.Sha1, totpData));
}
[Test]
public void Totp_Sha256_Called()
{
var mock = this.keyMock;
IKeyProvider key = mock.Object;
var totp = new Totp(key, mode: OtpHashMode.Sha256);
totp.ComputeTotp(totpDate);
mock.Verify(k => k.ComputeHmac(OtpHashMode.Sha256, totpData));
}
[Test]
public void Totp_Sha512_Called()
{
var mock = this.keyMock;
IKeyProvider key = mock.Object;
var totp = new Totp(key, mode: OtpHashMode.Sha512);
totp.ComputeTotp(totpDate);
mock.Verify(k => k.ComputeHmac(OtpHashMode.Sha512, totpData));
}
[Test]
public void Hotp_Sha1_Default_Called()
{
var mock = this.keyMock;
IKeyProvider key = mock.Object;
var hotp = new Hotp(key);
hotp.ComputeHotp(hotpCounter);
mock.Verify(k => k.ComputeHmac(OtpHashMode.Sha1, hotpData));
}
[Test]
public void Hotp_Sha1_Called()
{
var mock = this.keyMock;
IKeyProvider key = mock.Object;
var hotp = new Hotp(key, mode: OtpHashMode.Sha1);
hotp.ComputeHotp(hotpCounter);
mock.Verify(k => k.ComputeHmac(OtpHashMode.Sha1, hotpData));
}
[Test]
public void Hotp_Sha256_Called()
{
var mock = this.keyMock;
IKeyProvider key = mock.Object;
var hotp = new Hotp(key, mode: OtpHashMode.Sha256);
hotp.ComputeHotp(hotpCounter);
mock.Verify(k => k.ComputeHmac(OtpHashMode.Sha256, hotpData));
}
[Test]
public void Hotp_Sha512_Called()
{
var mock = this.keyMock;
IKeyProvider key = mock.Object;
var hotp = new Hotp(key, mode: OtpHashMode.Sha512);
hotp.ComputeHotp(hotpCounter);
mock.Verify(k => k.ComputeHmac(OtpHashMode.Sha512, hotpData));
}
}
} | 30.818898 | 137 | 0.5442 | [
"MIT"
] | arlm/otp-sharp | OtpSharp.Tests/OtpKeyInteractionTests.cs | 3,916 | C# |
/* _BEGIN_TEMPLATE_
{
"id": "YOD_017",
"name": [
"暗影塑形师",
"Shadow Sculptor"
],
"text": [
"<b>连击:</b>在本回合中,你每使用一张其他牌,便抽一张牌。",
"<b>Combo:</b> Draw a card for each card you've played this turn."
],
"cardClass": "ROGUE",
"type": "MINION",
"cost": 5,
"rarity": "EPIC",
"set": "YEAR_OF_THE_DRAGON",
"collectible": true,
"dbfId": 56093
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_YOD_017 : SimTemplate
{
}
} | 17.222222 | 70 | 0.576344 | [
"MIT"
] | chi-rei-den/Silverfish | cards/YEAR_OF_THE_DRAGON/YOD/Sim_YOD_017.cs | 525 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Quix.Snowflake.Application.TimeSeries;
using Quix.Sdk.Process;
using Quix.Sdk.Process.Models;
using Quix.Snowflake.Application.Metadata;
namespace Quix.Snowflake.Application.Streaming
{
public class StreamPersistingComponent : StreamComponent, IDisposable
{
private readonly ILogger<StreamPersistingComponent> logger;
private readonly IMetadataBufferedPersistingService metadataBufferedPersistingService;
private readonly ITimeSeriesBufferedPersistingService timeSeriesBufferedPersistingService;
public StreamPersistingComponent(ILogger<StreamPersistingComponent> logger,
IMetadataBufferedPersistingService metadataBufferedPersistingService,
ITimeSeriesBufferedPersistingService timeSeriesBufferedPersistingService)
{
this.logger = logger;
this.metadataBufferedPersistingService = metadataBufferedPersistingService;
this.timeSeriesBufferedPersistingService = timeSeriesBufferedPersistingService;
this.Input.LinkTo(this.Output);
// main data
this.Input.Subscribe<ParameterDataRaw>(this.OnParameterDataReceived);
this.Input.Subscribe<EventDataRaw[]>(this.OnMultipleEventDataReceived);
this.Input.Subscribe<EventDataRaw>(this.OnEventDataReceived);
// metadata
this.Input.Subscribe<ParameterDefinitions>(OnParameterDefinitionsReceived);
this.Input.Subscribe<EventDefinitions>(OnEventDefinitionsReceived);
this.Input.Subscribe<StreamProperties>(OnStreamPropertiesReceived);
this.Input.Subscribe<StreamEnd>(OnStreamEndReceived);
}
private async Task OnEventDataReceived(EventDataRaw arg)
{
var asArray = new[] {arg};
await this.metadataBufferedPersistingService.Buffer(this.StreamProcess.StreamId, asArray);
await this.timeSeriesBufferedPersistingService.Buffer(this.StreamProcess.StreamId, asArray);
}
private async Task OnMultipleEventDataReceived(EventDataRaw[] arg)
{
await metadataBufferedPersistingService.Buffer(this.StreamProcess.StreamId, arg);
await this.timeSeriesBufferedPersistingService.Buffer(this.StreamProcess.StreamId, arg);
}
private async Task OnParameterDataReceived(ParameterDataRaw arg)
{
var discardRange = await this.metadataBufferedPersistingService.GetDiscardRange(this.StreamProcess.StreamId, arg.Epoch + arg.Timestamps.Min());
await metadataBufferedPersistingService.Buffer(this.StreamProcess.StreamId, arg);
await this.timeSeriesBufferedPersistingService.Buffer(this.StreamProcess.StreamId, arg);
}
private Task OnStreamEndReceived(StreamEnd arg)
{
return metadataBufferedPersistingService.Buffer(this.StreamProcess.StreamId, arg);
}
private Task OnStreamPropertiesReceived(StreamProperties arg)
{
return metadataBufferedPersistingService.Buffer(this.StreamProcess.StreamId, arg);
}
private Task OnEventDefinitionsReceived(EventDefinitions arg)
{
return metadataBufferedPersistingService.Buffer(this.StreamProcess.StreamId, arg);
}
private Task OnParameterDefinitionsReceived(ParameterDefinitions arg)
{
return metadataBufferedPersistingService.Buffer(this.StreamProcess.StreamId, arg);
}
public void Dispose()
{
}
}
} | 43.164706 | 155 | 0.718452 | [
"Apache-2.0"
] | quixai/quix-library | csharp/destinations/snowflake/Quix.Snowflake.Application/Streaming/StreamPersistingComponent.cs | 3,669 | C# |
/*
* Copyright 2015-2018 Mohawk College of Applied Arts and Technology
*
*
* 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.
*
* User: fyfej
* Date: 2017-9-1
*/
using MARC.HI.EHRS.SVC.Auditing.Data;
using MARC.HI.EHRS.SVC.Auditing.Services;
using OpenIZ.Core.Model;
using OpenIZ.Core.Model.Acts;
using OpenIZ.Core.Model.Attributes;
using OpenIZ.Core.Model.Entities;
using OpenIZ.Core.Model.Interfaces;
using OpenIZ.Core.Model.Roles;
using OpenIZ.Core.Model.Security;
using OpenIZ.Mobile.Core.Configuration;
using OpenIZ.Mobile.Core.Data.Model;
using OpenIZ.Mobile.Core.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace OpenIZ.Mobile.Core.Security.Audit
{
/// <summary>
/// Event type codes
/// </summary>
public enum EventTypeCodes
{
[XmlEnum("SecurityAuditCode-ApplicationActivity")]
ApplicationActtivity,
[XmlEnum("SecurityAuditCode-AuditLogUsed")]
AuditLogUsed,
[XmlEnum("SecurityAuditCode-Export")]
Export,
[XmlEnum("SecurityAuditCode-Import")]
Import,
[XmlEnum("SecurityAuditCode-NetworkActivity")]
NetworkActivity,
[XmlEnum("SecurityAuditCode-OrderRecord")]
OrderRecord,
[XmlEnum("SecurityAuditCode-PatientRecord")]
PatientRecord,
[XmlEnum("SecurityAuditCode-ProcedureRecord")]
ProcedureRecord,
[XmlEnum("SecurityAuditCode-Query")]
Query,
[XmlEnum("SecurityAuditCode-SecurityAlert")]
SecurityAlert,
[XmlEnum("SecurityAuditCode-UserAuthentication")]
UserAuthentication,
[XmlEnum("SecurityAuditCode-ApplicationStart")]
ApplicationStart,
[XmlEnum("SecurityAuditCode-ApplicationStop")]
ApplicationStop,
[XmlEnum("SecurityAuditCode-Login")]
Login,
[XmlEnum("SecurityAuditCode-Logout")]
Logout,
[XmlEnum("SecurityAuditCode-Attach")]
Attach,
[XmlEnum("SecurityAuditCode-Detach")]
Detach,
[XmlEnum("SecurityAuditCode-NodeAuthentication")]
NodeAuthentication,
[XmlEnum("SecurityAuditCode-EmergencyOverrideStarted")]
EmergencyOverrideStarted,
[XmlEnum("SecurityAuditCode-Useofarestrictedfunction")]
UseOfARestrictedFunction,
[XmlEnum("SecurityAuditCode-Securityattributeschanged")]
SecurityAttributesChanged,
[XmlEnum("SecurityAuditCode-Securityroleschanged")]
SecurityRolesChanged,
[XmlEnum("SecurityAuditCode-Usersecurityattributechanged")]
UserSecurityChanged
}
/// <summary>
/// Security utility
/// </summary>
public static class AuditUtil
{
/// <summary>
/// Audit that the audit log was used
/// </summary>
/// <param name="action"></param>
/// <param name="outcome"></param>
/// <param name="query"></param>
/// <param name="auditIds"></param>
public static void AuditAuditLogUsed(ActionType action, OutcomeIndicator outcome, String query, params Guid[] auditIds)
{
AuditData audit = new AuditData(DateTime.Now, action, outcome, EventIdentifierType.SecurityAlert, CreateAuditActionCode(EventTypeCodes.AuditLogUsed));
// User actors
//AddDeviceActor(audit);
AddUserActor(audit);
// Add objects to which the thing was done
audit.AuditableObjects = auditIds.Select(o => new AuditableObject()
{
IDTypeCode = AuditableObjectIdType.ReportNumber,
LifecycleType = action == ActionType.Delete ? AuditableObjectLifecycle.PermanentErasure : AuditableObjectLifecycle.Disclosure,
ObjectId = o.ToString(),
Role = AuditableObjectRole.SecurityResource,
Type = AuditableObjectType.SystemObject
}).ToList();
if (!String.IsNullOrEmpty(query))
{
audit.AuditableObjects.Add(new AuditableObject()
{
IDTypeCode = AuditableObjectIdType.SearchCritereon,
LifecycleType = AuditableObjectLifecycle.Access,
QueryData = query,
Role = AuditableObjectRole.Query,
Type = AuditableObjectType.SystemObject
});
}
AddAncillaryObject(audit);
ApplicationContext.Current.GetService<LocalAuditRepositoryService>().Insert(audit);
}
/// <summary>
/// Adds ancillary object information to the audit log
/// </summary>
private static void AddAncillaryObject(AuditData audit)
{
// Add audit actors for this device and for the current user
var securityConfig = ApplicationContext.Current.Configuration.GetSection<SecurityConfigurationSection>();
var subscriptionConfig = ApplicationContext.Current.Configuration.GetSection<SynchronizationConfigurationSection>();
// Add auditable object which identifies the device
audit.AuditableObjects.Add(new AuditableObject()
{
IDTypeCode = AuditableObjectIdType.Custom,
CustomIdTypeCode = new AuditCode("Device","OpenIZTable"),
ObjectId = securityConfig.DeviceName,
Role = AuditableObjectRole.DataRepository,
Type = AuditableObjectType.SystemObject,
ObjectData = new List<ObjectDataExtension>()
{
new ObjectDataExtension("versionCode", Encoding.UTF8.GetBytes(ApplicationContext.Current.GetType().GetTypeInfo().Assembly.GetName().Version.ToString()))
}
});
// Add auditable object which identifies the facility
var facilityId = subscriptionConfig.Facilities?.FirstOrDefault();
if(!String.IsNullOrEmpty(facilityId))
audit.AuditableObjects.Add(new AuditableObject()
{
IDTypeCode = AuditableObjectIdType.Custom,
CustomIdTypeCode = new AuditCode("Place", "OpenIZTable"),
ObjectId = facilityId,
Role = AuditableObjectRole.Location,
Type = AuditableObjectType.Organization
});
}
/// <summary>
/// Audit the export of data
/// </summary>
public static void AuditDataExport()
{
AuditCode eventTypeId = CreateAuditActionCode(EventTypeCodes.Export);
AuditData audit = new AuditData(DateTime.Now, ActionType.Execute, OutcomeIndicator.Success, EventIdentifierType.SecurityAlert, eventTypeId);
AddDeviceActor(audit);
AddUserActor(audit);
AddAncillaryObject(audit);
SendAudit(audit);
}
/// <summary>
/// A utility which can be used to send a data audit
/// </summary>
public static void AuditDataAction<TData>(EventTypeCodes typeCode, ActionType action, AuditableObjectLifecycle lifecycle, EventIdentifierType eventType, OutcomeIndicator outcome, String queryPerformed, params TData[] data) where TData : IdentifiedData
{
AuditCode eventTypeId = CreateAuditActionCode(typeCode);
AuditData audit = new AuditData(DateTime.Now, action, outcome, eventType, eventTypeId);
AddDeviceActor(audit);
AddUserActor(audit);
// Objects
audit.AuditableObjects = data.Select(o => {
var idTypeCode = AuditableObjectIdType.Custom;
var roleCode = AuditableObjectRole.Resource;
var objType = AuditableObjectType.Other;
if (o is Patient)
{
idTypeCode = AuditableObjectIdType.PatientNumber;
roleCode = AuditableObjectRole.Patient;
objType = AuditableObjectType.Person;
}
else if (o is UserEntity || o is Provider)
{
idTypeCode = AuditableObjectIdType.UserIdentifier;
objType = AuditableObjectType.Person;
roleCode = AuditableObjectRole.Provider;
}
else if (o is Entity)
idTypeCode = AuditableObjectIdType.EnrolleeNumber;
else if (o is Act)
{
idTypeCode = AuditableObjectIdType.EncounterNumber;
roleCode = AuditableObjectRole.Report;
}
else if (o is SecurityUser)
{
idTypeCode = AuditableObjectIdType.UserIdentifier;
roleCode = AuditableObjectRole.SecurityUser;
objType = AuditableObjectType.SystemObject;
}
return new AuditableObject()
{
IDTypeCode = idTypeCode,
CustomIdTypeCode = idTypeCode == AuditableObjectIdType.Custom ? new AuditCode(o.GetType().Name, "OpenIZTable") : null,
LifecycleType = lifecycle,
ObjectId = o.Key?.ToString(),
Role = roleCode,
Type = objType
};
}).ToList();
// Query performed
if (!String.IsNullOrEmpty(queryPerformed))
{
audit.AuditableObjects.Add(new AuditableObject()
{
IDTypeCode = AuditableObjectIdType.SearchCritereon,
LifecycleType = AuditableObjectLifecycle.Access,
ObjectId = typeof(TData).Name,
QueryData = queryPerformed,
Role = AuditableObjectRole.Query,
Type = AuditableObjectType.SystemObject
});
}
AddAncillaryObject(audit);
SendAudit(audit);
}
/// <summary>
/// Create a security attribute action audit
/// </summary>
public static void AuditSecurityAttributeAction(IEnumerable<Object> objects, bool success, IEnumerable<string> changedProperties)
{
var audit = new AuditData(DateTime.Now, ActionType.Update, success ? OutcomeIndicator.Success : OutcomeIndicator.EpicFail, EventIdentifierType.SecurityAlert, CreateAuditActionCode(EventTypeCodes.SecurityAttributesChanged));
//AddDeviceActor(audit);
AddUserActor(audit);
audit.AuditableObjects = objects.Select(obj => new AuditableObject()
{
IDTypeCode = AuditableObjectIdType.Custom,
CustomIdTypeCode = new AuditCode(obj.GetType().Name, "OpenIZTable"),
ObjectId = ((obj as DbIdentified)?.Key ?? (obj as IIdentifiedEntity)?.Key ?? Guid.Empty).ToString(),
LifecycleType = AuditableObjectLifecycle.Amendment,
ObjectData = changedProperties.Select(
kv => new ObjectDataExtension(
kv.Contains("=") ? kv.Substring(0, kv.IndexOf("=")) : kv,
kv.Contains("=") ? Encoding.UTF8.GetBytes(kv.Substring(kv.IndexOf("=") + 1)) : new byte[0]
)
).ToList(),
Role = AuditableObjectRole.SecurityResource,
Type = AuditableObjectType.SystemObject
}).ToList();
AddAncillaryObject(audit);
SendAudit(audit);
}
/// <summary>
/// Send specified audit
/// </summary>
internal static void SendAudit(AuditData audit)
{
ApplicationContext.Current.GetService<IAuditorService>()?.SendAudit(audit);
}
/// <summary>
/// Add user actor
/// </summary>
internal static void AddUserActor(AuditData audit)
{
var configService = ApplicationContext.Current.Configuration.GetSection<SecurityConfigurationSection>();
// For the user
audit.Actors.Add(new AuditActorData()
{
NetworkAccessPointId = configService.DeviceName,
NetworkAccessPointType = NetworkAccessPointType.MachineName,
UserName = AuthenticationContext.Current.Principal.Identity.Name,
AlternativeUserId = AuthenticationContext.Current.Session?.Key?.ToString(),
UserIdentifier = AuthenticationContext.Current.Session?.SecurityUser?.Key?.ToString(),
UserIsRequestor = true
});
}
/// <summary>
/// Add device actor
/// </summary>
internal static void AddDeviceActor(AuditData audit)
{
// Add audit actors for this device and for the current user
var networkService = ApplicationContext.Current.GetService<INetworkInformationService>();
var configService = ApplicationContext.Current.Configuration.GetSection<SecurityConfigurationSection>();
// For the current device name
audit.Actors.Add(new AuditActorData()
{
NetworkAccessPointId = configService.DeviceName,
NetworkAccessPointType = NetworkAccessPointType.MachineName,
UserName = configService.DeviceName,
ActorRoleCode = new List<AuditCode>() {
new AuditCode("110153", "DCM") { DisplayName = "Source" }
}
});
}
/// <summary>
/// Create audit action code
/// </summary>
internal static AuditCode CreateAuditActionCode(EventTypeCodes typeCode)
{
var typeCodeWire = typeof(EventTypeCodes).GetRuntimeField(typeCode.ToString()).GetCustomAttribute<XmlEnumAttribute>();
return new AuditCode(typeCodeWire.Name, "SecurityAuditCode");
}
/// <summary>
/// Audit application start or stop
/// </summary>
public static void AuditApplicationStartStop(EventTypeCodes eventType)
{
AuditData audit = new AuditData(DateTime.Now, ActionType.Execute, OutcomeIndicator.Success, EventIdentifierType.ApplicationActivity, CreateAuditActionCode(eventType));
AddDeviceActor(audit);
AddAncillaryObject(audit);
SendAudit(audit);
}
/// <summary>
/// Audit a login of a principal
/// </summary>
public static void AuditLogin(IPrincipal principal, String identityName, IIdentityProviderService identityProvider, bool successfulLogin =true)
{
if ((principal?.Identity?.Name ?? identityName) == ApplicationContext.Current.Configuration.GetSection<SecurityConfigurationSection>().DeviceName) return; // don't worry about this
AuditData audit = new AuditData(DateTime.Now, ActionType.Execute, successfulLogin ? OutcomeIndicator.Success : OutcomeIndicator.EpicFail, EventIdentifierType.UserAuthentication, CreateAuditActionCode(EventTypeCodes.Login));
var configService = ApplicationContext.Current.Configuration.GetSection<SecurityConfigurationSection>();
audit.Actors.Add(new AuditActorData()
{
NetworkAccessPointType = NetworkAccessPointType.MachineName,
NetworkAccessPointId = configService.DeviceName,
UserName = principal?.Identity?.Name ?? identityName,
UserIsRequestor = true,
ActorRoleCode = (principal as ClaimsPrincipal)?.Claims.Where(o=>o.Type == ClaimsIdentity.DefaultRoleClaimType).Select(o=>new AuditCode(o.Value, "OizRoles")).ToList()
});
AddDeviceActor(audit);
audit.AuditableObjects.Add(new AuditableObject()
{
IDTypeCode = AuditableObjectIdType.Uri,
NameData = identityProvider.GetType().AssemblyQualifiedName,
ObjectId = $"http://openiz.org/mobile/auth/{identityProvider.GetType().FullName.Replace(".", "/")}",
Type = AuditableObjectType.SystemObject,
Role = AuditableObjectRole.Job
});
AddAncillaryObject(audit);
SendAudit(audit);
}
/// <summary>
/// Audit a login of a principal
/// </summary>
public static void AuditLogout(IPrincipal principal)
{
if (principal == null)
throw new ArgumentNullException(nameof(principal));
AuditData audit = new AuditData(DateTime.Now, ActionType.Execute, OutcomeIndicator.Success, EventIdentifierType.UserAuthentication, CreateAuditActionCode(EventTypeCodes.Logout));
var configService = ApplicationContext.Current.Configuration.GetSection<SecurityConfigurationSection>();
audit.Actors.Add(new AuditActorData()
{
NetworkAccessPointId = configService.DeviceName,
NetworkAccessPointType = NetworkAccessPointType.MachineName,
UserName = principal.Identity.Name,
UserIsRequestor = true
});
AddDeviceActor(audit);
AddAncillaryObject(audit);
SendAudit(audit);
}
/// <summary>
/// Audit the use of a restricted function
/// </summary>
public static void AuditRestrictedFunction(UnauthorizedAccessException ex, Uri url)
{
AuditData audit = new AuditData(DateTime.Now, ActionType.Execute, OutcomeIndicator.EpicFail, EventIdentifierType.SecurityAlert, CreateAuditActionCode(EventTypeCodes.UseOfARestrictedFunction));
AddUserActor(audit);
AddDeviceActor(audit);
audit.AuditableObjects.Add(new AuditableObject()
{
IDTypeCode = AuditableObjectIdType.Uri,
LifecycleType = AuditableObjectLifecycle.Access,
ObjectId = url.ToString(),
Role = AuditableObjectRole.Resource,
Type = AuditableObjectType.SystemObject
});
AddAncillaryObject(audit);
SendAudit(audit);
}
}
}
| 42.252796 | 259 | 0.614073 | [
"Apache-2.0"
] | MohawkMEDIC/openizdc | OpenIZ.Mobile.Core/Security/Audit/AuditUtil.cs | 18,889 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cats.Models.Hubs;
using Cats.Models.Hubs.ViewModels;
using Telerik.Web.Mvc;
using Cats.Models.Hubs.ViewModels.Common;
using Cats.Services.Hub;
namespace Cats.Web.Hub.Controllers
{
[Authorize]
public class LossesAndAdjustmentsController : BaseController
{
private readonly IUserProfileService _userProfileService;
private readonly ICommodityService _commodityService;
private readonly IStoreService _storeService;
private readonly IProgramService _programService;
private readonly IHubService _hubService;
private readonly IUnitService _unitService;
private readonly IAdjustmentReasonService _adjustmentReasonService;
private readonly IAdjustmentService _adjustmentService;
private readonly ITransactionService _TransactionService;
private readonly IProjectCodeService _projectCodeService;
private readonly IShippingInstructionService _shippingInstructionService;
public LossesAndAdjustmentsController(IUserProfileService userProfileService,
ICommodityService commodityService,
IStoreService storeService,
IProgramService programService,
IHubService hubService,
IUnitService unitService,
IAdjustmentReasonService adjustmentReasonService,
IAdjustmentService adjustmentService,
ITransactionService transactionService,
IProjectCodeService projectCodeService,
IShippingInstructionService shippingInstructionService)
: base(userProfileService)
{
_userProfileService = userProfileService;
_commodityService = commodityService;
_storeService = storeService;
_programService = programService;
_hubService = hubService;
_unitService = unitService;
_adjustmentReasonService = adjustmentReasonService;
_adjustmentService = adjustmentService;
_TransactionService = transactionService;
_projectCodeService = projectCodeService;
_shippingInstructionService = shippingInstructionService;
}
[Authorize]
public ActionResult Index()
{
return View(_adjustmentService.GetAllLossAndAdjustmentLog(UserProfile.DefaultHub.HubID).OrderByDescending(c => c.Date));
}
public ActionResult CreateLoss()
{
List<Commodity> commodity;
List<StoreViewModel> stores;
List<AdjustmentReason> adjustmentReasonMinus;
List<AdjustmentReason> adjustmentReasonPlus;
List<Unit> units;
List<ProgramViewModel> programs;
UserProfile user = _userProfileService.GetUser(User.Identity.Name);
commodity = _commodityService.GetAllParents();
stores = _hubService.GetAllStoreByUser(user);
adjustmentReasonMinus = _adjustmentReasonService.GetAllAdjustmentReason().Where(c => c.Direction == "-").ToList();
adjustmentReasonPlus = _adjustmentReasonService.GetAllAdjustmentReason().Where(c => c.Direction == "+").ToList();
units = _unitService.GetAllUnit().ToList();
programs = _programService.GetAllProgramsForReport();
LossesAndAdjustmentsViewModel viewModel = new LossesAndAdjustmentsViewModel(commodity, stores, adjustmentReasonMinus, adjustmentReasonPlus,units, programs, user, 1);
return View(viewModel);
}
public ActionResult CreateAdjustment()
{
List<Commodity> commodity;
List<StoreViewModel> stores;
List<AdjustmentReason> adjustmentReasonMinus;
List<AdjustmentReason> adjustmentReasonPlus;
List<Unit> units;
List<ProgramViewModel> programs;
UserProfile user = _userProfileService.GetUser(User.Identity.Name);
commodity = _commodityService.GetAllParents();
stores = _hubService.GetAllStoreByUser(user);
adjustmentReasonMinus = _adjustmentReasonService.GetAllAdjustmentReason().Where(c => c.Direction == "-").ToList();
adjustmentReasonPlus = _adjustmentReasonService.GetAllAdjustmentReason().Where(c => c.Direction == "+").ToList();
units = _unitService.GetAllUnit().ToList();
programs = _programService.GetAllProgramsForReport();
LossesAndAdjustmentsViewModel viewModel = new LossesAndAdjustmentsViewModel(commodity, stores, adjustmentReasonMinus, adjustmentReasonPlus, units, programs, user, 2);
return View(viewModel);
}
[HttpPost]
public ActionResult CreateLoss(LossesAndAdjustmentsViewModel viewModel)
{
List<Commodity> commodity;
List<StoreViewModel> stores;
List<AdjustmentReason> adjustmentReasonMinus;
List<AdjustmentReason> adjustmentReasonPlus;
List<Unit> units;
List<ProgramViewModel> programs;
UserProfile user = _userProfileService.GetUser(User.Identity.Name);
commodity = _commodityService.GetAllParents();
stores = _hubService.GetAllStoreByUser(user);
adjustmentReasonMinus = _adjustmentReasonService.GetAllAdjustmentReason().Where(c => c.Direction == "-").ToList();
adjustmentReasonPlus = _adjustmentReasonService.GetAllAdjustmentReason().Where(c => c.Direction == "+").ToList();
units = _unitService.GetAllUnit().ToList();
programs = _programService.GetAllProgramsForReport();
//if (ModelState.IsValid)
//{
LossesAndAdjustmentsViewModel newViewModel = new LossesAndAdjustmentsViewModel(commodity, stores,
adjustmentReasonMinus,
adjustmentReasonPlus,
units, programs, user, 1);
if (viewModel.QuantityInMt >
_TransactionService.GetCommodityBalanceForStore(viewModel.StoreId, viewModel.CommodityId,
viewModel.ShippingInstructionId,
viewModel.ProjectCodeId))
{
ModelState.AddModelError("QuantityInMT", "You have nothing to loss");
return View(newViewModel);
}
if (viewModel.QuantityInMt <= 0)
{
ModelState.AddModelError("QuantityInMT", "You have nothing to loss");
return View(newViewModel);
}
viewModel.IsLoss = true;
_adjustmentService.AddNewLossAndAdjustment(viewModel, user);
return RedirectToAction("Index");
//}
//return View();
}
[HttpPost]
public ActionResult CreateAdjustment(LossesAndAdjustmentsViewModel viewModel)
{
LossesAndAdjustmentsViewModel newViewModel = new LossesAndAdjustmentsViewModel();
UserProfile user = _userProfileService.GetUser(User.Identity.Name);
viewModel.IsLoss = false;
_adjustmentService.AddNewLossAndAdjustment(viewModel, user);
return RedirectToAction("Index");
}
[HttpPost]
public JsonResult GetStoreMan(int? storeId)
{
string storeMan = String.Empty;
if (storeId != null)
{
storeMan = _storeService.FindById(storeId.Value).StoreManName;
}
return Json(storeMan, JsonRequestBehavior.AllowGet);
}
public ActionResult Log()
{
return View(_adjustmentService.GetAllLossAndAdjustmentLog(UserProfile.DefaultHub.HubID));
}
public ActionResult Filter()
{
return PartialView();
}
public ActionResult GetStacksForToStore(int? ToStoreId)
{
return Json(new SelectList(_storeService.GetStacksByStoreId(ToStoreId), JsonRequestBehavior.AllowGet));
}
public ActionResult GetProjecCodetForCommodity(int? CommodityId)
{
var projectCodes = _projectCodeService.GetProjectCodesForCommodity(UserProfile.DefaultHub.HubID, CommodityId.Value);
return Json(new SelectList(projectCodes, "ProjectCodeId", "ProjectName"), JsonRequestBehavior.AllowGet);
}
public ActionResult GetSINumberForProjectCode(int? ProjectCodeId)
{
if (ProjectCodeId.HasValue)
{
UserProfile user = _userProfileService.GetUser(User.Identity.Name);
return Json(new SelectList(_shippingInstructionService.GetShippingInstructionsForProjectCode(user.DefaultHub.HubID, ProjectCodeId.Value), "ShippingInstructionId", "ShippingInstructionName"), JsonRequestBehavior.AllowGet);
}
else
{
return Json(new SelectList(new List<ShippingInstructionViewModel>()));
}
}
public ActionResult ViewDetial(string TransactionId)
{
var lossAndAdjustment = _adjustmentService.GetAllLossAndAdjustmentLog(UserProfile.DefaultHub.HubID).FirstOrDefault(c => c.TransactionId == Guid.Parse(TransactionId));
return PartialView(lossAndAdjustment);
}
[HttpPost]
public ActionResult GetFilters()
{
var filters = new List<SelectListItem>();
filters.Add(new SelectListItem { Value = "L", Text = "Loss"});
filters.Add(new SelectListItem { Value ="A", Text ="Adjustment"});
return Json(new SelectList(filters, "Value", "Text"));
}
[GridAction]
public ActionResult FilteredGrid(string filterId)
{
if (filterId != null && filterId != string.Empty)
{
var lossAndAdjustmentLogViewModel = _adjustmentService.GetAllLossAndAdjustmentLog(UserProfile.DefaultHub.HubID).Where(c => c.Type == filterId).OrderByDescending(c => c.Date);
return View(new GridModel(lossAndAdjustmentLogViewModel));
}
return View(new GridModel(_adjustmentService.GetAllLossAndAdjustmentLog(UserProfile.DefaultHub.HubID).OrderByDescending(c => c.Date)));
}
public ActionResult GetStoreForParentCommodity(int? commodityParentId, int? SINumber)
{
if (commodityParentId.HasValue && SINumber.HasValue)
{
UserProfile user = _userProfileService.GetUser(User.Identity.Name);
return Json(new SelectList(ConvertStoreToStoreViewModel(_storeService.GetStoresWithBalanceOfCommodityAndSINumber(commodityParentId.Value, SINumber.Value, user.DefaultHub.HubID)), "StoreId", "StoreName"));
}
else
{
return Json(new SelectList(new List<StoreViewModel>()));
}
}
public ActionResult SINumberBalance(int? parentCommodityId, int? projectcode, int? SINumber, int? StoreId, int? StackId)
{
StoreBalanceViewModel viewModel = new StoreBalanceViewModel();
UserProfile user = _userProfileService.GetUser(User.Identity.Name);
if (!StoreId.HasValue && !StackId.HasValue && parentCommodityId.HasValue && projectcode.HasValue && SINumber.HasValue)
{
viewModel.ParentCommodityNameB = _commodityService.FindById(parentCommodityId.Value).Name;
viewModel.ProjectCodeNameB =_projectCodeService.FindById(projectcode.Value).Value;
viewModel.ShppingInstructionNumberB = _shippingInstructionService.FindById(SINumber.Value).Value;
viewModel.QtBalance = _TransactionService.GetCommodityBalanceForHub(user.DefaultHub.HubID, parentCommodityId.Value, SINumber.Value, projectcode.Value);
}
else if (StoreId.HasValue && !StackId.HasValue && parentCommodityId.HasValue && projectcode.HasValue && SINumber.HasValue)
{
viewModel.ParentCommodityNameB = _commodityService.FindById(parentCommodityId.Value).Name;
viewModel.ProjectCodeNameB = _projectCodeService.FindById(projectcode.Value).Value;
viewModel.ShppingInstructionNumberB = _shippingInstructionService.FindById(SINumber.Value).Value;
viewModel.QtBalance = _TransactionService.GetCommodityBalanceForStore(StoreId.Value, parentCommodityId.Value, SINumber.Value, projectcode.Value);
var store = _storeService.FindById(StoreId.Value);
viewModel.StoreNameB = string.Format("{0} - {1}", store.Name, store.StoreManName);
}
else if (StoreId.HasValue && StackId.HasValue && parentCommodityId.HasValue && projectcode.HasValue && SINumber.HasValue)
{
viewModel.ParentCommodityNameB = _commodityService.FindById(parentCommodityId.Value).Name;
viewModel.ProjectCodeNameB = _projectCodeService.FindById(projectcode.Value).Value;
viewModel.ShppingInstructionNumberB = _shippingInstructionService.FindById(SINumber.Value).Value;
viewModel.QtBalance = _TransactionService.GetCommodityBalanceForStack(StoreId.Value, StackId.Value, parentCommodityId.Value, SINumber.Value, projectcode.Value);
var store = _storeService.FindById(StoreId.Value);
viewModel.StoreNameB = string.Format("{0} - {1}", store.Name, store.StoreManName);
viewModel.StackNumberB = StackId.Value.ToString();
}
return PartialView(viewModel);
}
List<StoreViewModel> ConvertStoreToStoreViewModel(List<Store> Stores)
{
List<StoreViewModel> viewModel = new List<StoreViewModel>();
foreach (var store in Stores)
{
viewModel.Add(new StoreViewModel { StoreId = store.StoreID, StoreName = string.Format("{0} - {1} ", store.Name, store.StoreManName) });
}
return viewModel;
}
}
}
| 47.10443 | 237 | 0.624656 | [
"Apache-2.0"
] | IYoni/cats | Cats.Web.Hub/Controllers/LossesAndAdjustmentsController.cs | 14,887 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.TestPlatform.Extensions.BlameDataCollector
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection;
using Microsoft.VisualStudio.TestPlatform.Utilities;
using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers;
using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces;
/// <summary>
/// The blame collector.
/// </summary>
[DataCollectorFriendlyName("Blame")]
[DataCollectorTypeUri("datacollector://Microsoft/TestPlatform/Extensions/Blame/v1")]
public class BlameCollector : DataCollector, ITestExecutionEnvironmentSpecifier
{
private const int DefaultInactivityTimeInMinutes = 60;
private DataCollectionSink dataCollectionSink;
private DataCollectionEnvironmentContext context;
private DataCollectionEvents events;
private DataCollectionLogger logger;
private IProcessDumpUtility processDumpUtility;
private List<Guid> testSequence;
private Dictionary<Guid, BlameTestObject> testObjectDictionary;
private IBlameReaderWriter blameReaderWriter;
private IFileHelper fileHelper;
private XmlElement configurationElement;
private int testStartCount;
private int testEndCount;
private bool collectProcessDumpOnTrigger;
private bool collectProcessDumpOnTestHostHang;
private bool collectDumpAlways;
private bool processFullDumpEnabled;
private bool inactivityTimerAlreadyFired;
private string attachmentGuid;
private IInactivityTimer inactivityTimer;
private TimeSpan inactivityTimespan = TimeSpan.FromMinutes(DefaultInactivityTimeInMinutes);
private int testHostProcessId;
private bool dumpWasCollectedByHangDumper;
private string targetFramework;
private List<KeyValuePair<string, string>> environmentVariables = new List<KeyValuePair<string, string>>();
/// <summary>
/// Initializes a new instance of the <see cref="BlameCollector"/> class.
/// Using XmlReaderWriter by default
/// </summary>
public BlameCollector()
: this(new XmlReaderWriter(), new ProcessDumpUtility(), null, new FileHelper())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BlameCollector"/> class.
/// </summary>
/// <param name="blameReaderWriter">
/// BlameReaderWriter instance.
/// </param>
/// <param name="processDumpUtility">
/// IProcessDumpUtility instance.
/// </param>
/// <param name="inactivityTimer">
/// InactivityTimer instance.
/// </param>
/// <param name="fileHelper">
/// Filehelper instance.
/// </param>
internal BlameCollector(
IBlameReaderWriter blameReaderWriter,
IProcessDumpUtility processDumpUtility,
IInactivityTimer inactivityTimer,
IFileHelper fileHelper)
{
this.blameReaderWriter = blameReaderWriter;
this.processDumpUtility = processDumpUtility;
this.inactivityTimer = inactivityTimer;
this.fileHelper = fileHelper;
}
/// <summary>
/// Gets environment variables that should be set in the test execution environment
/// </summary>
/// <returns>Environment variables that should be set in the test execution environment</returns>
public IEnumerable<KeyValuePair<string, string>> GetTestExecutionEnvironmentVariables()
{
return this.environmentVariables;
}
/// <summary>
/// Initializes parameters for the new instance of the class <see cref="BlameDataCollector"/>
/// </summary>
/// <param name="configurationElement">The Xml Element to save to</param>
/// <param name="events">Data collection events to which methods subscribe</param>
/// <param name="dataSink">A data collection sink for data transfer</param>
/// <param name="logger">Data Collection Logger to send messages to the client </param>
/// <param name="environmentContext">Context of data collector environment</param>
public override void Initialize(
XmlElement configurationElement,
DataCollectionEvents events,
DataCollectionSink dataSink,
DataCollectionLogger logger,
DataCollectionEnvironmentContext environmentContext)
{
ValidateArg.NotNull(logger, nameof(logger));
this.events = events;
this.dataCollectionSink = dataSink;
this.context = environmentContext;
this.configurationElement = configurationElement;
this.testSequence = new List<Guid>();
this.testObjectDictionary = new Dictionary<Guid, BlameTestObject>();
this.logger = logger;
// Subscribing to events
this.events.TestHostLaunched += this.TestHostLaunchedHandler;
this.events.SessionEnd += this.SessionEndedHandler;
this.events.TestCaseStart += this.EventsTestCaseStart;
this.events.TestCaseEnd += this.EventsTestCaseEnd;
if (this.configurationElement != null)
{
var collectDumpNode = this.configurationElement[Constants.DumpModeKey];
this.collectProcessDumpOnTrigger = collectDumpNode != null;
if (this.collectProcessDumpOnTrigger)
{
this.ValidateAndAddTriggerBasedProcessDumpParameters(collectDumpNode);
// enabling dumps on MacOS needs to be done explicitly https://github.com/dotnet/runtime/pull/40105
this.environmentVariables.Add(new KeyValuePair<string, string>("COMPlus_DbgEnableElfDumpOnMacOS", "1"));
this.environmentVariables.Add(new KeyValuePair<string, string>("COMPlus_DbgEnableMiniDump", "1"));
var guid = Guid.NewGuid().ToString();
var dumpDirectory = Path.Combine(Path.GetTempPath(), guid);
Directory.CreateDirectory(dumpDirectory);
var dumpPath = Path.Combine(dumpDirectory, $"dotnet_%d_crashdump.dmp");
this.environmentVariables.Add(new KeyValuePair<string, string>("COMPlus_DbgMiniDumpName", dumpPath));
}
var collectHangBasedDumpNode = this.configurationElement[Constants.CollectDumpOnTestSessionHang];
this.collectProcessDumpOnTestHostHang = collectHangBasedDumpNode != null;
if (this.collectProcessDumpOnTestHostHang)
{
// enabling dumps on MacOS needs to be done explicitly https://github.com/dotnet/runtime/pull/40105
this.environmentVariables.Add(new KeyValuePair<string, string>("COMPlus_DbgEnableElfDumpOnMacOS", "1"));
this.ValidateAndAddHangBasedProcessDumpParameters(collectHangBasedDumpNode);
}
var tfm = this.configurationElement[Constants.TargetFramework]?.InnerText;
if (!string.IsNullOrWhiteSpace(tfm))
{
this.targetFramework = tfm;
}
}
this.attachmentGuid = Guid.NewGuid().ToString().Replace("-", string.Empty);
if (this.collectProcessDumpOnTestHostHang)
{
this.inactivityTimer = this.inactivityTimer ?? new InactivityTimer(this.CollectDumpAndAbortTesthost);
this.ResetInactivityTimer();
}
}
/// <summary>
/// Disposes of the timer when called to prevent further calls.
/// Kills the other instance of proc dump if launched for collecting trigger based dumps.
/// Starts and waits for a new proc dump process to collect a single dump and then
/// kills the testhost process.
/// </summary>
private void CollectDumpAndAbortTesthost()
{
this.inactivityTimerAlreadyFired = true;
var message = string.Format(CultureInfo.CurrentUICulture, Resources.Resources.InactivityTimeout, (int)this.inactivityTimespan.TotalMinutes);
EqtTrace.Warning(message);
this.logger.LogWarning(this.context.SessionDataCollectionContext, message);
try
{
EqtTrace.Verbose("Calling dispose on Inactivity timer.");
this.inactivityTimer.Dispose();
}
catch
{
EqtTrace.Verbose("Inactivity timer is already disposed.");
}
try
{
this.processDumpUtility.StartHangBasedProcessDump(this.testHostProcessId, this.GetTempDirectory(), this.processFullDumpEnabled, this.targetFramework);
}
catch (Exception ex)
{
ConsoleOutput.Instance.Error(true, $"Blame: Creating hang dump failed with error {ex}.");
}
if (this.collectProcessDumpOnTrigger)
{
// Detach procdump from the testhost process to prevent testhost process from crashing
// if/when we try to kill the existing proc dump process.
this.processDumpUtility.DetachFromTargetProcess(this.testHostProcessId);
}
try
{
var dumpFiles = this.processDumpUtility.GetDumpFiles();
foreach (var dumpFile in dumpFiles)
{
try
{
if (!string.IsNullOrEmpty(dumpFile))
{
this.dumpWasCollectedByHangDumper = true;
var fileTransferInformation = new FileTransferInformation(this.context.SessionDataCollectionContext, dumpFile, true, this.fileHelper);
this.dataCollectionSink.SendFileAsync(fileTransferInformation);
}
}
catch (Exception ex)
{
// Eat up any exception here and log it but proceed with killing the test host process.
EqtTrace.Error(ex);
}
if (!dumpFiles.Any())
{
EqtTrace.Error("BlameCollector.CollectDumpAndAbortTesthost: blame:CollectDumpOnHang was enabled but dump file was not generated.");
}
}
}
catch (Exception ex)
{
ConsoleOutput.Instance.Error(true, $"Blame: Collecting hang dump failed with error {ex}.");
}
try
{
var p = Process.GetProcessById(this.testHostProcessId);
try
{
if (!p.HasExited)
{
p.Kill();
}
}
catch (InvalidOperationException)
{
}
}
catch (Exception ex)
{
EqtTrace.Error(ex);
}
}
private void ValidateAndAddTriggerBasedProcessDumpParameters(XmlElement collectDumpNode)
{
foreach (XmlAttribute blameAttribute in collectDumpNode.Attributes)
{
switch (blameAttribute)
{
case XmlAttribute attribute when string.Equals(attribute.Name, Constants.CollectDumpAlwaysKey, StringComparison.OrdinalIgnoreCase):
if (string.Equals(attribute.Value, Constants.TrueConfigurationValue, StringComparison.OrdinalIgnoreCase) || string.Equals(attribute.Value, Constants.FalseConfigurationValue, StringComparison.OrdinalIgnoreCase))
{
bool.TryParse(attribute.Value, out this.collectDumpAlways);
}
else
{
this.logger.LogWarning(this.context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterValueIncorrect, attribute.Name, Constants.TrueConfigurationValue, Constants.FalseConfigurationValue));
}
break;
case XmlAttribute attribute when string.Equals(attribute.Name, Constants.DumpTypeKey, StringComparison.OrdinalIgnoreCase):
if (string.Equals(attribute.Value, Constants.FullConfigurationValue, StringComparison.OrdinalIgnoreCase) || string.Equals(attribute.Value, Constants.MiniConfigurationValue, StringComparison.OrdinalIgnoreCase))
{
this.processFullDumpEnabled = string.Equals(attribute.Value, Constants.FullConfigurationValue, StringComparison.OrdinalIgnoreCase);
}
else
{
this.logger.LogWarning(this.context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterValueIncorrect, attribute.Name, Constants.FullConfigurationValue, Constants.MiniConfigurationValue));
}
break;
default:
this.logger.LogWarning(this.context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterKeyIncorrect, blameAttribute.Name));
break;
}
}
}
private void ValidateAndAddHangBasedProcessDumpParameters(XmlElement collectDumpNode)
{
foreach (XmlAttribute blameAttribute in collectDumpNode.Attributes)
{
switch (blameAttribute)
{
case XmlAttribute attribute when string.Equals(attribute.Name, Constants.TestTimeout, StringComparison.OrdinalIgnoreCase):
if (!string.IsNullOrWhiteSpace(attribute.Value) && TimeSpanParser.TryParse(attribute.Value, out var timeout))
{
this.inactivityTimespan = timeout;
}
else
{
this.logger.LogWarning(this.context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.UnexpectedValueForInactivityTimespanValue, attribute.Value));
}
break;
case XmlAttribute attribute when string.Equals(attribute.Name, Constants.HangDumpTypeKey, StringComparison.OrdinalIgnoreCase):
if (string.Equals(attribute.Value, Constants.FullConfigurationValue, StringComparison.OrdinalIgnoreCase) || string.Equals(attribute.Value, Constants.MiniConfigurationValue, StringComparison.OrdinalIgnoreCase))
{
this.processFullDumpEnabled = string.Equals(attribute.Value, Constants.FullConfigurationValue, StringComparison.OrdinalIgnoreCase);
}
else
{
this.logger.LogWarning(this.context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterValueIncorrect, attribute.Name, Constants.FullConfigurationValue, Constants.MiniConfigurationValue));
}
break;
default:
this.logger.LogWarning(this.context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterKeyIncorrect, blameAttribute.Name));
break;
}
}
}
/// <summary>
/// Called when Test Case Start event is invoked
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">TestCaseStartEventArgs</param>
private void EventsTestCaseStart(object sender, TestCaseStartEventArgs e)
{
this.ResetInactivityTimer();
if (EqtTrace.IsInfoEnabled)
{
EqtTrace.Info("Blame Collector : Test Case Start");
}
var blameTestObject = new BlameTestObject(e.TestElement);
// Add guid to list of test sequence to maintain the order.
this.testSequence.Add(blameTestObject.Id);
// Add the test object to the dictionary.
this.testObjectDictionary.Add(blameTestObject.Id, blameTestObject);
// Increment test start count.
this.testStartCount++;
}
/// <summary>
/// Called when Test Case End event is invoked
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">TestCaseEndEventArgs</param>
private void EventsTestCaseEnd(object sender, TestCaseEndEventArgs e)
{
this.ResetInactivityTimer();
if (EqtTrace.IsInfoEnabled)
{
EqtTrace.Info("Blame Collector : Test Case End");
}
this.testEndCount++;
// Update the test object in the dictionary as the test has completed.
if (this.testObjectDictionary.ContainsKey(e.TestElement.Id))
{
this.testObjectDictionary[e.TestElement.Id].IsCompleted = true;
}
}
/// <summary>
/// Called when Session End event is invoked
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="args">SessionEndEventArgs</param>
private void SessionEndedHandler(object sender, SessionEndEventArgs args)
{
this.ResetInactivityTimer();
if (EqtTrace.IsInfoEnabled)
{
EqtTrace.Info("Blame Collector : Session End");
}
try
{
// If the last test crashes, it will not invoke a test case end and therefore
// In case of crash testStartCount will be greater than testEndCount and we need to write the sequence
// And send the attachment
if (this.testStartCount > this.testEndCount)
{
var filepath = Path.Combine(this.GetTempDirectory(), Constants.AttachmentFileName + "_" + this.attachmentGuid);
filepath = this.blameReaderWriter.WriteTestSequence(this.testSequence, this.testObjectDictionary, filepath);
var fileTranferInformation = new FileTransferInformation(this.context.SessionDataCollectionContext, filepath, true);
this.dataCollectionSink.SendFileAsync(fileTranferInformation);
}
if (this.collectProcessDumpOnTrigger)
{
// If there was a test case crash or if we need to collect dump on process exit.
//
// Do not try to collect dump when we already collected one from the hang dump
// we won't dump the killed process again and that would just show a warning on the command line
if ((this.testStartCount > this.testEndCount || this.collectDumpAlways) && !this.dumpWasCollectedByHangDumper)
{
try
{
var dumpFiles = this.processDumpUtility.GetDumpFiles();
foreach (var dumpFile in dumpFiles)
{
if (!string.IsNullOrEmpty(dumpFile))
{
try
{
var fileTranferInformation = new FileTransferInformation(this.context.SessionDataCollectionContext, dumpFile, true);
this.dataCollectionSink.SendFileAsync(fileTranferInformation);
}
catch (FileNotFoundException ex)
{
EqtTrace.Warning(ex.ToString());
this.logger.LogWarning(args.Context, ex.ToString());
}
}
}
}
catch (FileNotFoundException ex)
{
EqtTrace.Warning(ex.ToString());
this.logger.LogWarning(args.Context, ex.ToString());
}
}
}
}
finally
{
// Attempt to terminate the proc dump process if proc dump was enabled
if (this.collectProcessDumpOnTrigger)
{
this.processDumpUtility.DetachFromTargetProcess(this.testHostProcessId);
}
this.DeregisterEvents();
}
}
/// <summary>
/// Called when Test Host Initialized is invoked
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="args">TestHostLaunchedEventArgs</param>
private void TestHostLaunchedHandler(object sender, TestHostLaunchedEventArgs args)
{
this.ResetInactivityTimer();
this.testHostProcessId = args.TestHostProcessId;
if (!this.collectProcessDumpOnTrigger)
{
return;
}
try
{
this.processDumpUtility.StartTriggerBasedProcessDump(args.TestHostProcessId, this.GetTempDirectory(), this.processFullDumpEnabled, this.targetFramework);
}
catch (TestPlatformException e)
{
if (EqtTrace.IsWarningEnabled)
{
EqtTrace.Warning("BlameCollector.TestHostLaunchedHandler: Could not start process dump. {0}", e);
}
this.logger.LogWarning(args.Context, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.ProcDumpCouldNotStart, e.Message));
}
catch (Exception e)
{
if (EqtTrace.IsWarningEnabled)
{
EqtTrace.Warning("BlameCollector.TestHostLaunchedHandler: Could not start process dump. {0}", e);
}
this.logger.LogWarning(args.Context, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.ProcDumpCouldNotStart, e.ToString()));
}
}
/// <summary>
/// Resets the inactivity timer
/// </summary>
private void ResetInactivityTimer()
{
if (!this.collectProcessDumpOnTestHostHang || this.inactivityTimerAlreadyFired)
{
return;
}
EqtTrace.Verbose("Reset the inactivity timer since an event was received.");
try
{
this.inactivityTimer.ResetTimer(this.inactivityTimespan);
}
catch (Exception e)
{
EqtTrace.Warning($"Failed to reset the inactivity timer with error {e}");
}
}
/// <summary>
/// Method to de-register handlers and cleanup
/// </summary>
private void DeregisterEvents()
{
this.events.SessionEnd -= this.SessionEndedHandler;
this.events.TestCaseStart -= this.EventsTestCaseStart;
this.events.TestCaseEnd -= this.EventsTestCaseEnd;
}
private string GetTempDirectory()
{
string tempPath = null;
var netDumperPath = this.environmentVariables.SingleOrDefault(p => p.Key == "COMPlus_DbgMiniDumpName").Value;
try
{
if (!string.IsNullOrWhiteSpace(netDumperPath))
{
tempPath = Path.GetDirectoryName(netDumperPath);
}
}
catch (ArgumentException)
{
// the path was not correct do nothing
}
var tmp = !string.IsNullOrWhiteSpace(tempPath) ? tempPath : Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tmp);
return tmp;
}
}
}
| 44.45053 | 274 | 0.581064 | [
"MIT"
] | urbankovak/vstest | src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs | 25,161 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Playnite.SDK.Models
{
/// <summary>
/// Represents web link.
/// </summary>
public class Link : ObservableObject
{
private string name;
/// <summary>
/// Gets or sets name of the link.
/// </summary>
public string Name
{
get => name;
set
{
name = value;
OnPropertyChanged();
}
}
private string url;
/// <summary>
/// Gets or sets web based URL.
/// </summary>
public string Url
{
get => url;
set
{
url = value;
OnPropertyChanged();
}
}
/// <summary>
/// Creates new instance of Link.
/// </summary>
public Link()
{
}
/// <summary>
/// Creates new instance of Link with specific values.
/// </summary>
/// <param name="name">Link name.</param>
/// <param name="url">Link URL.</param>
public Link(string name, string url)
{
Name = name;
Url = url;
}
}
}
| 21.677419 | 62 | 0.454613 | [
"MIT"
] | riftgg/Playnite | source/Playnite.SDK.NetStandard/Models/Link.cs | 1,346 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Microsoft.Scripting.Generation;
namespace Microsoft.Scripting.Runtime
{
class ScriptingRuntimeHelpers
{
private const int MIN_CACHE = -100;
private const int MAX_CACHE = 1000;
/// <summary>
/// A singleton boxed boolean true.
/// </summary>
public static readonly object True = true;
/// <summary>
///A singleton boxed boolean false.
/// </summary>
public static readonly object False = false;
internal static readonly MethodInfo BooleanToObjectMethod = typeof(ScriptingRuntimeHelpers).GetMethod("BooleanToObject");
internal static readonly MethodInfo Int32ToObjectMethod = typeof(ScriptingRuntimeHelpers).GetMethod("Int32ToObject");
/// <summary>
/// Gets a singleton boxed value for the given integer if possible, otherwise boxes the integer.
/// </summary>
/// <param name="value">The value to box.</param>
/// <returns>The boxed value.</returns>
public static object Int32ToObject(Int32 value)
{
// caches improves pystone by ~5-10% on MS .Net 1.1, this is a very integer intense app
// TODO: investigate if this still helps perf. There's evidence that it's harmful on
// .NET 3.5 and 4.0
//if (value < MAX_CACHE && value >= MIN_CACHE)
//{
// return cache[value - MIN_CACHE];
//}
return (object)value;//just return value
}
private static readonly string[] chars = MakeSingleCharStrings();
private static string[] MakeSingleCharStrings()
{
string[] result = new string[255];
for (char ch = (char)0; ch < result.Length; ch++)
{
result[ch] = new string(ch, 1);
}
return result;
}
public static object BooleanToObject(bool value)
{
return value ? True : False;
}
/// <summary>
/// Helper method to create an instance. Work around for Silverlight where Activator.CreateInstance
/// is SecuritySafeCritical.
///
/// TODO: Why can't we just emit the right thing for default(T)?
/// It's always null for reference types and it's well defined for value types
/// </summary>
public static T CreateInstance<T>()
{
return default(T);
}
public static Exception MakeIncorrectBoxTypeError(Type type, object received)
{
return Error.UnexpectedType("StrongBox<" + type.Name + ">", CompilerHelpers.GetType(received).Name);
}
public static ArgumentTypeException SimpleTypeError(string message)
{
return new ArgumentTypeException(message);
}
}
}
| 34.431818 | 130 | 0.581848 | [
"Apache-2.0"
] | jadu/Phalanger | Source/Microsoft.DynamicLight/Runtime/_ScriptingRuntimeHelpers.cs | 3,032 | C# |
using System.Windows.Controls;
namespace FrameworkTester.Views
{
/// <summary>
/// WinBioEnrollCapture.xaml の相互作用ロジック
/// </summary>
public partial class WinBioEnrollCapture : Page
{
public WinBioEnrollCapture()
{
InitializeComponent();
}
}
}
| 20 | 52 | 0.58125 | [
"MIT"
] | poseidonjm/WinBiometricDotNet | examples/FrameworkTester/Views/WinBioEnrollCapture.xaml.cs | 340 | C# |
// Copyright 2016-2017 Confluent 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.
//
// Refer to LICENSE for more information.
using System;
using System.Collections.Generic;
using Xunit;
using System.Threading.Tasks;
namespace Confluent.Kafka.IntegrationTests
{
/// <summary>
/// Test every Producer<TKey,TValue>.ProduceAsync method overload
/// that provides delivery reports via a Task.
/// (null key/value case)
/// </summary>
public static partial class Tests
{
[Theory, MemberData(nameof(KafkaParameters))]
public static void SerializingProducer_ProduceAsync_Null_Task(string bootstrapServers, string topic, string partitionedTopic)
{
var producerConfig = new Dictionary<string, object>
{
{ "bootstrap.servers", bootstrapServers },
{ "api.version.request", true }
};
var drs = new List<Task<Message<Null, Null>>>();
using (var producer = new Producer<Null, Null>(producerConfig, null, null))
{
drs.Add(producer.ProduceAsync(partitionedTopic, null, null, 0, true));
drs.Add(producer.ProduceAsync(partitionedTopic, null, null, 0));
drs.Add(producer.ProduceAsync(partitionedTopic, null, null, true));
drs.Add(producer.ProduceAsync(partitionedTopic, null, null));
producer.Flush(TimeSpan.FromSeconds(10));
}
for (int i=0; i<4; ++i)
{
var dr = drs[i].Result;
Assert.Equal(ErrorCode.NoError, dr.Error.Code);
Assert.True(dr.Partition == 0 || dr.Partition == 1);
Assert.Equal(partitionedTopic, dr.Topic);
Assert.True(dr.Offset >= 0);
Assert.Null(dr.Key);
Assert.Null(dr.Value);
Assert.Equal(TimestampType.CreateTime, dr.Timestamp.Type);
Assert.True(Math.Abs((DateTime.UtcNow - dr.Timestamp.UtcDateTime).TotalMinutes) < 1.0);
}
Assert.Equal(0, drs[0].Result.Partition);
Assert.Equal(0, drs[1].Result.Partition);
}
}
}
| 38.267606 | 133 | 0.618697 | [
"Apache-2.0"
] | sstaton/daxko-kafka-etl | test/Confluent.Kafka.IntegrationTests/Tests/SerializingProducer_ProduceAsync_Null_Task.cs | 2,717 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
#pragma warning disable
using System;
using System.Collections;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
{
public class X509CertStoreSelector
: IX509Selector
{
// TODO Missing criteria?
private byte[] authorityKeyIdentifier;
private int basicConstraints = -1;
private X509Certificate certificate;
private DateTimeObject certificateValid;
private ISet extendedKeyUsage;
private bool ignoreX509NameOrdering;
private X509Name issuer;
private bool[] keyUsage;
private ISet policy;
private DateTimeObject privateKeyValid;
private BigInteger serialNumber;
private X509Name subject;
private byte[] subjectKeyIdentifier;
private SubjectPublicKeyInfo subjectPublicKey;
private DerObjectIdentifier subjectPublicKeyAlgID;
public X509CertStoreSelector()
{
}
public X509CertStoreSelector(
X509CertStoreSelector o)
{
this.authorityKeyIdentifier = o.AuthorityKeyIdentifier;
this.basicConstraints = o.BasicConstraints;
this.certificate = o.Certificate;
this.certificateValid = o.CertificateValid;
this.extendedKeyUsage = o.ExtendedKeyUsage;
this.ignoreX509NameOrdering = o.IgnoreX509NameOrdering;
this.issuer = o.Issuer;
this.keyUsage = o.KeyUsage;
this.policy = o.Policy;
this.privateKeyValid = o.PrivateKeyValid;
this.serialNumber = o.SerialNumber;
this.subject = o.Subject;
this.subjectKeyIdentifier = o.SubjectKeyIdentifier;
this.subjectPublicKey = o.SubjectPublicKey;
this.subjectPublicKeyAlgID = o.SubjectPublicKeyAlgID;
}
public virtual object Clone()
{
return new X509CertStoreSelector(this);
}
public byte[] AuthorityKeyIdentifier
{
get { return Arrays.Clone(authorityKeyIdentifier); }
set { authorityKeyIdentifier = Arrays.Clone(value); }
}
public int BasicConstraints
{
get { return basicConstraints; }
set
{
if (value < -2)
throw new ArgumentException("value can't be less than -2", "value");
basicConstraints = value;
}
}
public X509Certificate Certificate
{
get { return certificate; }
set { this.certificate = value; }
}
public DateTimeObject CertificateValid
{
get { return certificateValid; }
set { certificateValid = value; }
}
public ISet ExtendedKeyUsage
{
get { return CopySet(extendedKeyUsage); }
set { extendedKeyUsage = CopySet(value); }
}
public bool IgnoreX509NameOrdering
{
get { return ignoreX509NameOrdering; }
set { this.ignoreX509NameOrdering = value; }
}
public X509Name Issuer
{
get { return issuer; }
set { issuer = value; }
}
public string IssuerAsString
{
get { return issuer != null ? issuer.ToString() : null; }
}
public bool[] KeyUsage
{
get { return CopyBoolArray(keyUsage); }
set { keyUsage = CopyBoolArray(value); }
}
/// <summary>
/// An <code>ISet</code> of <code>DerObjectIdentifier</code> objects.
/// </summary>
public ISet Policy
{
get { return CopySet(policy); }
set { policy = CopySet(value); }
}
public DateTimeObject PrivateKeyValid
{
get { return privateKeyValid; }
set { privateKeyValid = value; }
}
public BigInteger SerialNumber
{
get { return serialNumber; }
set { serialNumber = value; }
}
public X509Name Subject
{
get { return subject; }
set { subject = value; }
}
public string SubjectAsString
{
get { return subject != null ? subject.ToString() : null; }
}
public byte[] SubjectKeyIdentifier
{
get { return Arrays.Clone(subjectKeyIdentifier); }
set { subjectKeyIdentifier = Arrays.Clone(value); }
}
public SubjectPublicKeyInfo SubjectPublicKey
{
get { return subjectPublicKey; }
set { subjectPublicKey = value; }
}
public DerObjectIdentifier SubjectPublicKeyAlgID
{
get { return subjectPublicKeyAlgID; }
set { subjectPublicKeyAlgID = value; }
}
public virtual bool Match(
object obj)
{
X509Certificate c = obj as X509Certificate;
if (c == null)
return false;
if (!MatchExtension(authorityKeyIdentifier, c, X509Extensions.AuthorityKeyIdentifier))
return false;
if (basicConstraints != -1)
{
int bc = c.GetBasicConstraints();
if (basicConstraints == -2)
{
if (bc != -1)
return false;
}
else
{
if (bc < basicConstraints)
return false;
}
}
if (certificate != null && !certificate.Equals(c))
return false;
if (certificateValid != null && !c.IsValid(certificateValid.Value))
return false;
if (extendedKeyUsage != null)
{
IList eku = c.GetExtendedKeyUsage();
// Note: if no extended key usage set, all key purposes are implicitly allowed
if (eku != null)
{
foreach (DerObjectIdentifier oid in extendedKeyUsage)
{
if (!eku.Contains(oid.Id))
return false;
}
}
}
if (issuer != null && !issuer.Equivalent(c.IssuerDN, !ignoreX509NameOrdering))
return false;
if (keyUsage != null)
{
bool[] ku = c.GetKeyUsage();
// Note: if no key usage set, all key purposes are implicitly allowed
if (ku != null)
{
for (int i = 0; i < 9; ++i)
{
if (keyUsage[i] && !ku[i])
return false;
}
}
}
if (policy != null)
{
Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CertificatePolicies);
if (extVal == null)
return false;
Asn1Sequence certPolicies = Asn1Sequence.GetInstance(
X509ExtensionUtilities.FromExtensionValue(extVal));
if (policy.Count < 1 && certPolicies.Count < 1)
return false;
bool found = false;
foreach (PolicyInformation pi in certPolicies)
{
if (policy.Contains(pi.PolicyIdentifier))
{
found = true;
break;
}
}
if (!found)
return false;
}
if (privateKeyValid != null)
{
Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod);
if (extVal == null)
return false;
PrivateKeyUsagePeriod pkup = PrivateKeyUsagePeriod.GetInstance(
X509ExtensionUtilities.FromExtensionValue(extVal));
DateTime dt = privateKeyValid.Value;
DateTime notAfter = pkup.NotAfter.ToDateTime();
DateTime notBefore = pkup.NotBefore.ToDateTime();
if (dt.CompareTo(notAfter) > 0 || dt.CompareTo(notBefore) < 0)
return false;
}
if (serialNumber != null && !serialNumber.Equals(c.SerialNumber))
return false;
if (subject != null && !subject.Equivalent(c.SubjectDN, !ignoreX509NameOrdering))
return false;
if (!MatchExtension(subjectKeyIdentifier, c, X509Extensions.SubjectKeyIdentifier))
return false;
if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(c)))
return false;
if (subjectPublicKeyAlgID != null
&& !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(c).AlgorithmID))
return false;
return true;
}
internal static bool IssuersMatch(
X509Name a,
X509Name b)
{
return a == null ? b == null : a.Equivalent(b, true);
}
private static bool[] CopyBoolArray(
bool[] b)
{
return b == null ? null : (bool[]) b.Clone();
}
private static ISet CopySet(
ISet s)
{
return s == null ? null : new HashSet(s);
}
private static SubjectPublicKeyInfo GetSubjectPublicKey(
X509Certificate c)
{
return SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(c.GetPublicKey());
}
private static bool MatchExtension(
byte[] b,
X509Certificate c,
DerObjectIdentifier oid)
{
if (b == null)
return true;
Asn1OctetString extVal = c.GetExtensionValue(oid);
if (extVal == null)
return false;
return Arrays.AreEqual(b, extVal.GetOctets());
}
}
}
#pragma warning restore
#endif
| 23.569801 | 93 | 0.68234 | [
"MIT"
] | Bregermann/TargetCrack | Target Crack/Assets/Best HTTP/Source/SecureProtocol/x509/store/X509CertStoreSelector.cs | 8,273 | C# |
using System;
class PrintNumbers
{
static void Main()
{
Console.WriteLine(1);
Console.WriteLine(101);
Console.WriteLine(1001);
Console.WriteLine();
int a = 1;
int b = 101;
int c = 1001;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine();
string d = "1";//as string
string e = "101";
string f = "1001";
Console.WriteLine(d);
Console.WriteLine(e);
Console.WriteLine(f);
Console.WriteLine();
Console.WriteLine("1\n101\n1001");//as string
Console.WriteLine();
}
}
| 17.842105 | 53 | 0.523599 | [
"MIT"
] | DobrinStefkin/HomeworkFirstLecture | PrintNumbers/PrintNumbers.cs | 680 | 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/mfmediaengine.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IMFSourceBufferAppendMode" /> struct.</summary>
public static unsafe class IMFSourceBufferAppendModeTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IMFSourceBufferAppendMode" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IMFSourceBufferAppendMode).GUID, Is.EqualTo(IID_IMFSourceBufferAppendMode));
}
/// <summary>Validates that the <see cref="IMFSourceBufferAppendMode" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IMFSourceBufferAppendMode>(), Is.EqualTo(sizeof(IMFSourceBufferAppendMode)));
}
/// <summary>Validates that the <see cref="IMFSourceBufferAppendMode" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IMFSourceBufferAppendMode).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IMFSourceBufferAppendMode" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IMFSourceBufferAppendMode), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IMFSourceBufferAppendMode), Is.EqualTo(4));
}
}
}
}
| 39.211538 | 145 | 0.657185 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | tests/Interop/Windows/um/mfmediaengine/IMFSourceBufferAppendModeTests.cs | 2,041 | C# |
using CefSharp;
using System;
using System.Linq;
using System.Collections.Generic;
namespace wechat_spider_core
{
public class SpiderTask
{
public long SpiderId { get; set; }
public string NickName { get; set; }
public string Alias { get; set; }
public List<string> Roles { get; set; }
public int CurrentPage { get; set; } = 1;
public SearchBiz AppModel { get; set; }
public DateTime? LastUpdateDate { get; set; }
public SpiderTask(string name)
{
Roles = new List<string>();
NickName = name;
}
public bool Ready(string role, string runDate)
{
return Roles.Any(c => c == role) && (!LastUpdateDate.HasValue || LastUpdateDate.Value.ToString("yyyyMMddHH") != runDate);
}
public void Run()
{
SearchQueryModel searchQuery = new SearchQueryModel
{
token = Config.Token,
query = NickName
};
ChromeWebBrowser.chromeBrowser.ExecuteScriptAsync($"httpGet('https://mp.weixin.qq.com/cgi-bin/searchbiz{searchQuery}','queryList')");
}
public void ToQueryArticleList(int page)
{
ArticleReuqestModel articleReuqestModel = new ArticleReuqestModel
{
token = Config.Token,
begin = page.ToString(),
fakeid = AppModel.fakeid
};
ChromeWebBrowser.chromeBrowser.ExecuteScriptAsync($"httpGet('https://mp.weixin.qq.com/cgi-bin/appmsg{articleReuqestModel}','article')");
}
}
}
| 29.196429 | 148 | 0.574312 | [
"MIT"
] | zainzhoucom/wechat_spider_core | wechat_spider_core/spider/SpiderTask.cs | 1,637 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.MachineLearningServices.V20200801.Inputs
{
/// <summary>
/// Settings for a personal compute instance.
/// </summary>
public sealed class PersonalComputeInstanceSettingsArgs : Pulumi.ResourceArgs
{
/// <summary>
/// A user explicitly assigned to a personal compute instance.
/// </summary>
[Input("assignedUser")]
public Input<Inputs.AssignedUserArgs>? AssignedUser { get; set; }
public PersonalComputeInstanceSettingsArgs()
{
}
}
}
| 29.344828 | 81 | 0.681551 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/MachineLearningServices/V20200801/Inputs/PersonalComputeInstanceSettingsArgs.cs | 851 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace PgpSharp
{
/// <summary>
/// Main interface for pgp tool.
/// </summary>
public interface IPgpTool
{
/// <summary>
/// Gets or sets a different keyring folder than default.
/// </summary>
/// <value>
/// The keyring folder.
/// </value>
string KeyringFolder { get; set; }
/// <summary>
/// Processes data with stream input.
/// </summary>
/// <param name="input">The input.</param>
/// <returns>Output stream.</returns>
Stream ProcessData(StreamDataInput input);
/// <summary>
/// Processes data with file input.
/// </summary>
/// <param name="input">The input.</param>
void ProcessData(FileDataInput input);
/// <summary>
/// Lists the known keys.
/// </summary>
/// <param name="target">The target.</param>
/// <returns></returns>
IEnumerable<KeyId> ListKeys(KeyTarget target);
}
}
| 26.023256 | 65 | 0.548704 | [
"MIT"
] | soukoku/PgpSharp | src/PgpSharp/IPgpTool.cs | 1,121 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace GraphQL.Language.AST
{
public class Arguments : AbstractNode, IEnumerable<Argument>
{
private readonly List<Argument> _arguments = new List<Argument>();
public override IEnumerable<INode> Children => _arguments;
public void Add(Argument arg)
{
_arguments.Add(arg ?? throw new ArgumentNullException(nameof(arg)));
}
public IValue ValueFor(string name) => _arguments.FirstOrDefault(x => x.Name == name)?.Value;
protected bool Equals(Arguments args) => false;
public override bool IsEqualTo(INode obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Arguments) obj);
}
public IEnumerator<Argument> GetEnumerator() => _arguments.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| 30.444444 | 101 | 0.64781 | [
"MIT"
] | ZickZakk/graphql-dotnet | src/GraphQL/Language/AST/Arguments.cs | 1,096 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace PartialViews.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 25.515152 | 88 | 0.685273 | [
"MIT"
] | AnzhelikaKravchuk/asp-dot-net-core-in-action-2e | Chapter07/E_PartialViews/PartialViews/Pages/Error.cshtml.cs | 842 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Windows.Automation;
namespace TestUtilities.UI
{
/// <summary>
/// Wraps the Delete/Remove/Cancel dialog displayed when removing something from a hierarchy window (such as the solution explorer).
/// </summary>
public class RemoveItemDialog : AutomationDialog
{
public RemoveItemDialog(IntPtr hwnd)
: base(null, AutomationElement.FromHandle(hwnd))
{
}
public RemoveItemDialog(VisualStudioApp app, AutomationElement element)
: base(app, element)
{
}
public static RemoveItemDialog FromDte(VisualStudioApp app)
{
return new RemoveItemDialog(app, AutomationElement.FromHandle(app.OpenDialogWithDteExecuteCommand("Edit.Delete")));
}
public override void OK()
{
throw new NotSupportedException();
}
public void Remove()
{
WaitForInputIdle();
WaitForClosed(DefaultTimeout, () => ClickButtonByName("Remove"));
}
public void Delete()
{
WaitForInputIdle();
WaitForClosed(DefaultTimeout, () => ClickButtonByName("Delete"));
}
}
}
| 30.340426 | 161 | 0.606592 | [
"Apache-2.0"
] | Abd-Elrazek/nodejstools | Common/Tests/Utilities.UI/UI/RemoveItemDialog.cs | 1,380 | C# |
namespace ModIO.API
{
public class AddGameMediaParameters : RequestParameters
{
// ---------[ FIELDS ]---------
// Image file which will represent your game's logo. Must be gif, jpg or png format and
// cannot exceed 8MB in filesize. Dimensions must be at least 640x360 and we recommended you
// supply a high resolution image with a 16 / 9 ratio. mod.io will use this logo to create
// three thumbnails with the dimensions of 320x180, 640x360 and 1280x720.
public BinaryUpload logo
{
set
{
this.SetBinaryData("logo", value.fileName, value.data);
}
}
// Image file which will represent your game's icon. Must be gif, jpg or png format and
// cannot exceed 1MB in filesize. Dimensions must be at least 64x64 and a transparent png
// that works on a colorful background is recommended. mod.io will use this icon to create
// three thumbnails with the dimensions of 64x64, 128x128 and 256x256.
public BinaryUpload icon
{
set
{
this.SetBinaryData("icon", value.fileName, value.data);
}
}
// Image file which will represent your game's header. Must be gif, jpg or png format and
// cannot exceed 256KB in filesize. Dimensions of 400x100 and a light transparent png that
// works on a dark background is recommended.
public BinaryUpload headerImage
{
set
{
this.SetBinaryData("header", value.fileName, value.data);
}
}
}
}
| 39.404762 | 100 | 0.599396 | [
"MIT"
] | TrutzX/9Nations | Assets/Plugins/mod.io/Scripts/API/RequestParameters/AddGameMediaParameters.cs | 1,655 | 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 xray-2016-04-12.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.XRay.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.XRay.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for FaultRootCauseEntity Object
/// </summary>
public class FaultRootCauseEntityUnmarshaller : IUnmarshaller<FaultRootCauseEntity, XmlUnmarshallerContext>, IUnmarshaller<FaultRootCauseEntity, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
FaultRootCauseEntity IUnmarshaller<FaultRootCauseEntity, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public FaultRootCauseEntity Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
FaultRootCauseEntity unmarshalledObject = new FaultRootCauseEntity();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Exceptions", targetDepth))
{
var unmarshaller = new ListUnmarshaller<RootCauseException, RootCauseExceptionUnmarshaller>(RootCauseExceptionUnmarshaller.Instance);
unmarshalledObject.Exceptions = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Name", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Name = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Remote", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.Remote = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static FaultRootCauseEntityUnmarshaller _instance = new FaultRootCauseEntityUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static FaultRootCauseEntityUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.355769 | 174 | 0.614157 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/XRay/Generated/Model/Internal/MarshallTransformations/FaultRootCauseEntityUnmarshaller.cs | 3,885 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using timesheet.data;
namespace timesheet.data.Migrations
{
[DbContext(typeof(TimesheetDb))]
[Migration("20190109115334_initial")]
partial class initial
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.4-rtm-31024")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("timesheet.model.Employee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(10);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255);
b.HasKey("Id");
b.ToTable("Employees");
});
#pragma warning restore 612, 618
}
}
}
| 34.444444 | 125 | 0.603226 | [
"MIT"
] | josephalwyn/timesheet.api-master | timesheet.data/Migrations/20190109115334_initial.Designer.cs | 1,552 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) STB Chain. All rights reserved.
* Licensed under the Source EULA. See License in the project root for license information.
* Source code : https://github.com/stbchain
* Website : http://www.soft2b.com/
*---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------*/
using System;
namespace STB.Core.Structures.Peers
{
/// <summary>
/// INSERT INTO peers (peer_host, peer) VALUES('127.0.0.1', 'ws://127.0.0.1:8081');
/// </summary>
public class PeerEvents
{
/// <summary>
/// domain or IP
/// </summary>
public string PeerHost { get; set; }
public DateTime? EventDate { get; set; } = DateTime.Now;
public string Event { get; set; }
}
} | 37 | 96 | 0.420998 | [
"MIT"
] | stbchain/stb.core | src/STB.Core/Structures/Peers/PeerEvents.cs | 962 | 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.Vod.V20180717.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class AiReviewPoliticalTaskOutput : AbstractModel
{
/// <summary>
/// 视频涉政评分,分值为0到100。
/// </summary>
[JsonProperty("Confidence")]
public float? Confidence{ get; set; }
/// <summary>
/// 涉政结果建议,取值范围:
/// <li>pass。</li>
/// <li>review。</li>
/// <li>block。</li>
/// </summary>
[JsonProperty("Suggestion")]
public string Suggestion{ get; set; }
/// <summary>
/// 视频鉴政结果标签。内容审核模板[画面鉴政任务控制参数](https://cloud.tencent.com/document/api/266/31773#PoliticalImgReviewTemplateInfo)里 LabelSet 参数与此参数取值范围的对应关系:
/// violation_photo:
/// <li>violation_photo:违规图标。</li>
/// 其他(即 politician/entertainment/sport/entrepreneur/scholar/celebrity/military):
/// <li>politician:政治人物。</li>
/// </summary>
[JsonProperty("Label")]
public string Label{ get; set; }
/// <summary>
/// 有涉政嫌疑的视频片段列表。
/// </summary>
[JsonProperty("SegmentSet")]
public MediaContentReviewPoliticalSegmentItem[] SegmentSet{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "Confidence", this.Confidence);
this.SetParamSimple(map, prefix + "Suggestion", this.Suggestion);
this.SetParamSimple(map, prefix + "Label", this.Label);
this.SetParamArrayObj(map, prefix + "SegmentSet.", this.SegmentSet);
}
}
}
| 33.805556 | 147 | 0.622843 | [
"Apache-2.0"
] | kimii/tencentcloud-sdk-dotnet | TencentCloud/Vod/V20180717/Models/AiReviewPoliticalTaskOutput.cs | 2,636 | C# |
using Aurora.Controls;
using Aurora.Profiles.GTA5.GSI;
using Aurora.Settings;
using System;
using System.Diagnostics;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Xceed.Wpf.Toolkit;
namespace Aurora.Profiles.GTA5
{
/// <summary>
/// Interaction logic for Control_GTA5.xaml
/// </summary>
public partial class Control_GTA5 : UserControl
{
private Application profile_manager;
private Timer preview_wantedlevel_timer;
private int frame = 0;
public Control_GTA5(Application profile)
{
InitializeComponent();
profile_manager = profile;
SetSettings();
preview_wantedlevel_timer = new Timer(1000);
preview_wantedlevel_timer.Elapsed += Preview_wantedlevel_timer_Elapsed;
}
private void SetSettings()
{
this.game_enabled.IsChecked = profile_manager.Settings.IsEnabled;
}
private void preview_state_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (IsLoaded)
{
(this.profile_manager.Config.Event._game_state as GameState_GTA5).CurrentState = (Profiles.GTA5.GSI.PlayerState)Enum.Parse(typeof(Profiles.GTA5.GSI.PlayerState), this.preview_team.SelectedIndex.ToString());
}
}
private void Preview_wantedlevel_timer_Elapsed(object sender, ElapsedEventArgs e)
{
if(frame % 2 == 0)
{
(profile_manager.Config.Event._game_state as GameState_GTA5).LeftSirenColor = System.Drawing.Color.Red;
(profile_manager.Config.Event._game_state as GameState_GTA5).RightSirenColor = System.Drawing.Color.Blue;
}
else
{
(profile_manager.Config.Event._game_state as GameState_GTA5).LeftSirenColor = System.Drawing.Color.Blue;
(profile_manager.Config.Event._game_state as GameState_GTA5).RightSirenColor = System.Drawing.Color.Red;
}
frame++;
}
private void preview_wantedlevel_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if(IsLoaded && sender is IntegerUpDown && (sender as IntegerUpDown).Value.HasValue)
{
int value = (sender as IntegerUpDown).Value.Value;
if (value == 0)
{
preview_wantedlevel_timer.Stop();
(profile_manager.Config.Event._game_state as GameState_GTA5).HasCops = false;
}
else
{
preview_wantedlevel_timer.Start();
preview_wantedlevel_timer.Interval = 600D - 50D * value;
(profile_manager.Config.Event._game_state as GameState_GTA5).HasCops = true;
}
}
}
private void patch_button_Click(object sender, RoutedEventArgs e)
{
try
{
App.InstallLogitech();
}
catch (Exception exc)
{
Global.logger.Error("Could not start Aurora Logitech Patcher. Error: " + exc);
}
}
private void game_enabled_Checked(object sender, RoutedEventArgs e)
{
if (IsLoaded)
{
profile_manager.Settings.IsEnabled = (this.game_enabled.IsChecked.HasValue) ? this.game_enabled.IsChecked.Value : false;
profile_manager.SaveProfiles();
}
}
}
}
| 35.150943 | 223 | 0.583199 | [
"MIT"
] | ADoesGit/Aurora | Project-Aurora/Project-Aurora/Profiles/GTA5/Control_GTA5.xaml.cs | 3,623 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using IntergalacticTravel.Contracts;
using IntergalacticTravel.Exceptions;
using IntergalacticTravel.Extensions;
namespace IntergalacticTravel
{
public class TeleportStation : ITeleportStation
{
protected readonly IResources resources;
protected readonly IBusinessOwner owner;
protected readonly ILocation location;
protected readonly IEnumerable<IPath> galacticMap;
public TeleportStation(IBusinessOwner owner, IEnumerable<IPath> galacticMap, ILocation location)
{
this.owner = owner;
this.galacticMap = galacticMap;
this.location = location;
this.resources = new Resources();
}
public void TeleportUnit(IUnit unitToTeleport, ILocation targetLocation)
{
IPath pathToTheTargetPlanet;
this.ValidateThatTeleportationServiceIsApplicable(unitToTeleport, targetLocation, out pathToTheTargetPlanet);
this.GetPayment(pathToTheTargetPlanet, unitToTeleport);
this.ChangeUnitLocation(pathToTheTargetPlanet, unitToTeleport, targetLocation);
}
public IResources PayProfits(IBusinessOwner owner)
{
if (this.owner.IdentificationNumber != owner.IdentificationNumber)
{
throw new UnauthorizedAccessException("Payments are allowed only to the owner");
}
var payment = this.resources.Clone();
this.resources.Clear();
return payment;
}
private void ChangeUnitLocation(IPath pathToTheTargetPlanet, IUnit unitToTeleport, ILocation targetLocation)
{
pathToTheTargetPlanet.TargetLocation.Planet.Units.Add(unitToTeleport);
unitToTeleport.CurrentLocation.Planet.Units.Remove(unitToTeleport);
unitToTeleport.PreviousLocation = unitToTeleport.CurrentLocation;
unitToTeleport.CurrentLocation = targetLocation;
}
private void GetPayment(IPath pathToTheTargetPlanet, IUnit unitToTeleport)
{
var cost = pathToTheTargetPlanet.Cost;
var payment = unitToTeleport.Pay(cost);
this.resources.Add(payment);
}
private bool LocationsMatch(ILocation firstLocation, ILocation secondLocation)
{
return firstLocation.Planet.Galaxy.Name == secondLocation.Planet.Galaxy.Name &&
firstLocation.Planet.Name == secondLocation.Planet.Name;
}
private bool LocationsAndCoordinatesMatch(ILocation firstLocation, ILocation secondLocation)
{
return firstLocation.Coordinates.Latitude == secondLocation.Coordinates.Latitude &&
firstLocation.Coordinates.Longtitude == secondLocation.Coordinates.Longtitude &&
this.LocationsMatch(firstLocation, secondLocation);
}
private void ValidateThatTeleportationServiceIsApplicable(IUnit unitToTeleport, ILocation targetLocation, out IPath pathToTheTargetPlanet)
{
if (unitToTeleport.IsNull())
{
throw new ArgumentNullException("unitToTeleport");
}
if (targetLocation.IsNull())
{
throw new ArgumentNullException("destination");
}
if (!this.LocationsMatch(this.location, unitToTeleport.CurrentLocation))
{
throw new TeleportOutOfRangeException("unitToTeleport.CurrentLocation");
}
var pathsToTheTargetGalaxy = galacticMap
.Where(path => path.TargetLocation.Planet.Galaxy.Name == targetLocation.Planet.Galaxy.Name)
.ToList();
if (pathsToTheTargetGalaxy.IsNullOrEmpty())
{
throw new LocationNotFoundException("A path to a Galaxy with the provided name cannot be found in the TeleportStation's galactic map.");
}
pathToTheTargetPlanet = pathsToTheTargetGalaxy.FirstOrDefault(path => path.TargetLocation.Planet.Name == targetLocation.Planet.Name);
if (pathToTheTargetPlanet.IsNull())
{
throw new LocationNotFoundException("A path to a Planet with the provided name cannot be found in the TeleportStation's galactic map.");
}
foreach (var unitInCity in pathToTheTargetPlanet.TargetLocation.Planet.Units)
{
if (this.LocationsAndCoordinatesMatch(targetLocation, unitInCity.CurrentLocation))
{
throw new InvalidTeleportationLocationException("There is already a unit placed on the desired location. Cannot activate the teleportation service because the units will overlap.");
}
}
if (!unitToTeleport.CanPay(pathToTheTargetPlanet.Cost))
{
throw new InsufficientResourcesException("The unit cannot be teleported, because THERE AIN'T NO SUCH THING AS A FREE LUNCH.");
}
}
}
}
| 41.308943 | 201 | 0.658138 | [
"MIT"
] | MichaelaIvanova/Unit-Testing | Topics/Exams/2016_07/Exam_Author solution/IntergalacticTravel/TeleportStation.cs | 5,083 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Bu kod araç tarafından oluşturuldu.
// Çalışma Zamanı Sürümü:4.0.30319.42000
//
// Bu dosyada yapılacak değişiklikler yanlış davranışa neden olabilir ve
// kod yeniden oluşturulursa kaybolur.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("WebOBS.Core")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("WebOBS.Core")]
[assembly: System.Reflection.AssemblyTitleAttribute("WebOBS.Core")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// MSBuild WriteCodeFragment sınıfı tarafından oluşturuldu.
| 42 | 80 | 0.659722 | [
"MIT"
] | cihatfurkaneken/school-management | WebOBS.Core/obj/Debug/netcoreapp3.1/WebOBS.Core.AssemblyInfo.cs | 1,031 | 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("NetDist.Jobs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NetDist.Jobs")]
[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("cbf0a765-9689-4730-b6c1-df189926fc93")]
// 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.756757 | 84 | 0.743737 | [
"MIT"
] | Roemer/NetDist | src/NetDist.Jobs/Properties/AssemblyInfo.cs | 1,400 | C# |
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace InteractionFramework
{
class Program
{
// Entry point of the program.
static void Main ( string[] args )
{
// One of the more flexable ways to access the configuration data is to use the Microsoft's Configuration model,
// this way we can avoid hard coding the environment secrets. I opted to use the Json and environment variable providers here.
IConfiguration config = new ConfigurationBuilder()
.AddEnvironmentVariables(prefix: "DC_")
.AddJsonFile("appsettings.json", optional: true)
.Build();
RunAsync(config).GetAwaiter().GetResult();
}
static async Task RunAsync (IConfiguration configuration)
{
// Dependency injection is a key part of the Interactions framework but it needs to be disposed at the end of the app's lifetime.
using var services = ConfigureServices(configuration);
var client = services.GetRequiredService<DiscordSocketClient>();
var commands = services.GetRequiredService<InteractionService>();
client.Log += LogAsync;
commands.Log += LogAsync;
// Slash Commands and Context Commands are can be automatically registered, but this process needs to happen after the client enters the READY state.
// Since Global Commands take around 1 hour to register, we should use a test guild to instantly update and test our commands. To determine the method we should
// register the commands with, we can check whether we are in a DEBUG environment and if we are, we can register the commands to a predetermined test guild.
client.Ready += async ( ) =>
{
if (IsDebug())
// Id of the test guild can be provided from the Configuration object
await commands.RegisterCommandsToGuildAsync(configuration.GetValue<ulong>("testGuild"), true);
else
await commands.RegisterCommandsGloballyAsync(true);
};
// Here we can initialize the service that will register and execute our commands
await services.GetRequiredService<CommandHandler>().InitializeAsync();
// Bot token can be provided from the Configuration object we set up earlier
await client.LoginAsync(TokenType.Bot, configuration["token"]);
await client.StartAsync();
await Task.Delay(Timeout.Infinite);
}
static Task LogAsync(LogMessage message)
{
Console.WriteLine(message.ToString());
return Task.CompletedTask;
}
static ServiceProvider ConfigureServices ( IConfiguration configuration )
=> new ServiceCollection()
.AddSingleton(configuration)
.AddSingleton<DiscordSocketClient>()
.AddSingleton(x => new InteractionService(x.GetRequiredService<DiscordSocketClient>()))
.AddSingleton<CommandHandler>()
.BuildServiceProvider();
static bool IsDebug ( )
{
#if DEBUG
return true;
#else
return false;
#endif
}
}
}
| 42.035714 | 172 | 0.633815 | [
"MIT"
] | DenVot/Discord.Net | samples/InteractionFramework/Program.cs | 3,531 | C# |
//-----------------------------------------------------------------------
// <copyright file="Extensions.cs" company="Junle Li">
// Copyright (c) Junle Li. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Vsxmd.Units
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
/// <summary>
/// Extensions helper.
/// </summary>
internal static class Extensions
{
/// <summary>
/// Convert the <see cref="MemberKind"/> to its lowercase name.
/// </summary>
/// <param name="memberKind">The member kind.</param>
/// <returns>The member kind's lowercase name.</returns>
internal static string ToLowerString(this MemberKind memberKind) =>
#pragma warning disable CA1308 // We use lower case in URL anchor.
memberKind.ToString().ToLowerInvariant();
#pragma warning restore CA1308
/// <summary>
/// Concatenates the <paramref name="value"/>s with the <paramref name="separator"/>.
/// </summary>
/// <param name="value">The string values.</param>
/// <param name="separator">The separator.</param>
/// <returns>The concatenated string.</returns>
internal static string Join(this IEnumerable<string> value, string separator) =>
string.Join(separator, value);
/// <summary>
/// Suffix the <paramref name="suffix"/> to the <paramref name="value"/>, and generate a new string.
/// </summary>
/// <param name="value">The original string value.</param>
/// <param name="suffix">The suffix string.</param>
/// <returns>The new string.</returns>
internal static string Suffix(this string value, string suffix) =>
string.Concat(value, suffix);
/// <summary>
/// Escape the content to keep it raw in Markdown syntax.
/// </summary>
/// <param name="content">The content.</param>
/// <returns>The escaped content.</returns>
internal static string Escape(this string content) =>
content.Replace("`", @"\`", StringComparison.InvariantCulture);
/// <summary>
/// Generate an anchor for the <paramref name="href"/>.
/// </summary>
/// <param name="href">The href.</param>
/// <returns>The anchor for the <paramref name="href"/>.</returns>
internal static string ToAnchor(this string href) =>
$"<a name='{href}'></a>\n";
/// <summary>
/// Generate "to here" link for the <paramref name="href"/>.
/// </summary>
/// <param name="href">The href.</param>
/// <returns>The "to here" link for the <paramref name="href"/>.</returns>
internal static string ToHereLink(this string href) =>
$"[#](#{href} 'Go To Here')";
/// <summary>
/// Generate the reference link for the <paramref name="memberName"/>.
/// </summary>
/// <param name="memberName">The member name.</param>
/// <param name="useShortName">Indicate if use short type name.</param>
/// <returns>The generated reference link.</returns>
/// <example>
/// <para>For <c>T:Vsxmd.Units.MemberUnit</c>, convert it to <c>[MemberUnit](#T-Vsxmd.Units.MemberUnit)</c>.</para>
/// <para>For <c>T:System.ArgumentException</c>, convert it to <c>[ArgumentException](http://msdn/path/to/System.ArgumentException)</c>.</para>
/// </example>
internal static string ToReferenceLink(this string memberName, bool useShortName = false) =>
new MemberName(memberName).ToReferenceLink(useShortName);
/// <summary>
/// Wrap the <paramref name="code"/> into Markdown backtick safely.
/// <para>The backtick characters inside the <paramref name="code"/> reverse as it is.</para>
/// </summary>
/// <param name="code">The code span.</param>
/// <returns>The Markdown code span.</returns>
/// <remarks>Reference: http://meta.stackexchange.com/questions/55437/how-can-the-backtick-character-be-included-in-code .</remarks>
internal static string AsCode(this string code)
{
string backticks = "`";
while (code.Contains(backticks, StringComparison.InvariantCulture))
{
backticks += "`";
}
return code.StartsWith("`", StringComparison.Ordinal) || code.EndsWith("`", StringComparison.Ordinal)
? $"{backticks} {code} {backticks}"
: $"{backticks}{code}{backticks}";
}
/// <summary>
/// Gets the n-th last element from the <paramref name="source"/>.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">The source enumerable.</param>
/// <param name="index">The index for the n-th last.</param>
/// <returns>The element at the specified position in the <paramref name="source"/> sequence.</returns>
internal static TSource NthLast<TSource>(
this IEnumerable<TSource> source, int index) =>
source.Reverse().ElementAt(index - 1);
/// <summary>
/// Take all element except the last <paramref name="count"/>.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">The source enumerable.</param>
/// <param name="count">The number to except.</param>
/// <returns>The generated enumerable.</returns>
internal static IEnumerable<TSource> TakeAllButLast<TSource>(
this IEnumerable<TSource> source,
int count) =>
source.Reverse().Skip(count).Reverse();
/// <summary>
/// Convert the inline XML nodes to Markdown text.
/// For example, it works for <c>summary</c> and <c>returns</c> elements.
/// </summary>
/// <param name="element">The XML element.</param>
/// <returns>The generated Markdown content.</returns>
/// <example>
/// This method converts the following <c>summary</c> element.
/// <code>
/// <summary>The <paramref name="element" /> value is <value>null</value>, it throws <c>ArgumentException</c>. For more, see <see cref="ToMarkdownText(XElement)"/>.</summary>
/// </code>
/// To the below Markdown content.
/// <code>
/// The `element` value is `null`, it throws `ArgumentException`. For more, see `ToMarkdownText`.
/// </code>
/// </example>
internal static string ToMarkdownText(this XElement element) =>
element.Nodes()
.Select(ToMarkdownSpan)
.Aggregate(string.Empty, JoinMarkdownSpan)
.Trim();
private static string ToMarkdownSpan(XNode node)
{
var text = node as XText;
if (text != null)
{
return text.Value.Escape().TrimStart(' ').Replace(" ", string.Empty, StringComparison.InvariantCulture);
}
var child = node as XElement;
if (child != null)
{
switch (child.Name.ToString())
{
case "see":
return $"{child.ToSeeTagMarkdownSpan()}{child.NextNode.AsSpanMargin()}";
case "paramref":
case "typeparamref":
return $"{child.Attribute("name")?.Value?.AsCode()}{child.NextNode.AsSpanMargin()}";
case "c":
case "value":
return $"{child.Value.AsCode()}{child.NextNode.AsSpanMargin()}";
case "code":
var lang = child.Attribute("lang")?.Value ?? string.Empty;
string value = child.Nodes().First().ToString().Replace("\t", " ", StringComparison.InvariantCulture);
var indexOf = FindIndexOf(value);
var codeblockLines = value.Split(Environment.NewLine.ToCharArray())
.Where(t => t.Length > indexOf)
.Select(t => t.Substring(indexOf));
var codeblock = string.Join("\n", codeblockLines);
return $"\n\n```{lang}\n{codeblock}\n```\n\n";
case "example":
case "para":
return $"\n\n{child.ToMarkdownText()}\n\n";
default:
return string.Empty;
}
}
return string.Empty;
}
private static int FindIndexOf(string node)
{
List<int> result = new List<int>();
foreach (var item in node.Split(Environment.NewLine.ToCharArray())
.Where(t => t.Length > 0))
{
result.Add(0);
for (int i = 0; i < item.Length; i++)
{
if (item.ToCharArray()[i] != ' ')
{
break;
}
result[result.Count - 1] += 1;
}
}
return result.Min();
}
private static string JoinMarkdownSpan(string x, string y) =>
x.EndsWith("\n\n", StringComparison.Ordinal)
? $"{x}{y.TrimStart()}"
: y.StartsWith("\n\n", StringComparison.Ordinal)
? $"{x.TrimEnd()}{y}"
: $"{x}{y}";
private static string ToSeeTagMarkdownSpan(this XElement seeTag) =>
seeTag.Attribute("cref")?.Value?.ToReferenceLink(useShortName: true) ??
seeTag.Attribute("langword")?.Value?.AsCode();
private static string AsSpanMargin(this XNode node)
{
var text = node as XText;
if (text != null && text.Value.StartsWith(" ", StringComparison.Ordinal))
{
return " ";
}
return string.Empty;
}
}
}
| 43.016736 | 182 | 0.533217 | [
"MIT"
] | atifaziz/Vsxmd | Vsxmd/Units/Extensions.cs | 10,283 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.dcdn.Model.V20180115;
namespace Aliyun.Acs.dcdn.Transform.V20180115
{
public class DescribeDcdnTopDomainsByFlowResponseUnmarshaller
{
public static DescribeDcdnTopDomainsByFlowResponse Unmarshall(UnmarshallerContext context)
{
DescribeDcdnTopDomainsByFlowResponse describeDcdnTopDomainsByFlowResponse = new DescribeDcdnTopDomainsByFlowResponse();
describeDcdnTopDomainsByFlowResponse.HttpResponse = context.HttpResponse;
describeDcdnTopDomainsByFlowResponse.RequestId = context.StringValue("DescribeDcdnTopDomainsByFlow.RequestId");
describeDcdnTopDomainsByFlowResponse.StartTime = context.StringValue("DescribeDcdnTopDomainsByFlow.StartTime");
describeDcdnTopDomainsByFlowResponse.EndTime = context.StringValue("DescribeDcdnTopDomainsByFlow.EndTime");
describeDcdnTopDomainsByFlowResponse.DomainCount = context.LongValue("DescribeDcdnTopDomainsByFlow.DomainCount");
describeDcdnTopDomainsByFlowResponse.DomainOnlineCount = context.LongValue("DescribeDcdnTopDomainsByFlow.DomainOnlineCount");
List<DescribeDcdnTopDomainsByFlowResponse.DescribeDcdnTopDomainsByFlow_TopDomain> describeDcdnTopDomainsByFlowResponse_topDomains = new List<DescribeDcdnTopDomainsByFlowResponse.DescribeDcdnTopDomainsByFlow_TopDomain>();
for (int i = 0; i < context.Length("DescribeDcdnTopDomainsByFlow.TopDomains.Length"); i++) {
DescribeDcdnTopDomainsByFlowResponse.DescribeDcdnTopDomainsByFlow_TopDomain topDomain = new DescribeDcdnTopDomainsByFlowResponse.DescribeDcdnTopDomainsByFlow_TopDomain();
topDomain.DomainName = context.StringValue("DescribeDcdnTopDomainsByFlow.TopDomains["+ i +"].DomainName");
topDomain.Rank = context.LongValue("DescribeDcdnTopDomainsByFlow.TopDomains["+ i +"].Rank");
topDomain.TotalTraffic = context.StringValue("DescribeDcdnTopDomainsByFlow.TopDomains["+ i +"].TotalTraffic");
topDomain.TrafficPercent = context.StringValue("DescribeDcdnTopDomainsByFlow.TopDomains["+ i +"].TrafficPercent");
topDomain.MaxBps = context.LongValue("DescribeDcdnTopDomainsByFlow.TopDomains["+ i +"].MaxBps");
topDomain.MaxBpsTime = context.StringValue("DescribeDcdnTopDomainsByFlow.TopDomains["+ i +"].MaxBpsTime");
topDomain.TotalAccess = context.LongValue("DescribeDcdnTopDomainsByFlow.TopDomains["+ i +"].TotalAccess");
describeDcdnTopDomainsByFlowResponse_topDomains.Add(topDomain);
}
describeDcdnTopDomainsByFlowResponse.TopDomains = describeDcdnTopDomainsByFlowResponse_topDomains;
return describeDcdnTopDomainsByFlowResponse;
}
}
}
| 59.050847 | 224 | 0.802526 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-dcdn/Dcdn/Transform/V20180115/DescribeDcdnTopDomainsByFlowResponseUnmarshaller.cs | 3,484 | C# |
namespace Telerik.Core
{
/// <summary>
/// Specifies the direction of the animation.
/// </summary>
public enum SequentialMode
{
/// <summary>
/// The sequential animation starts from the last item and ends with the first item.
/// </summary>
LastToFirst,
/// <summary>
/// The sequential animation starts from the first item and ends with the last item.
/// </summary>
FirstToLast
}
} | 26.555556 | 92 | 0.575314 | [
"Apache-2.0"
] | ChristianGutman/UI-For-UWP | Controls/Core.UWP/Animation/SequentialMode.cs | 480 | 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 Xunit;
namespace System.Linq.Parallel.Tests
{
public class WhereTests
{
[Theory]
[MemberData("Ranges", (object)(new int[] { 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Where_Unordered(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, (count + 1) / 2);
foreach (int i in query.Where(x => x % 2 == 0))
{
Assert.Equal(0, i % 2);
seen.Add(i / 2);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 512 }), MemberType = typeof(UnorderedSources))]
public static void Where_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Where_Unordered(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1, 2, 16 }), MemberType = typeof(Sources))]
public static void Where(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = -2;
foreach (int i in query.Where(x => x % 2 == 0))
{
Assert.Equal(seen += 2, i);
}
Assert.Equal(count - (count - 1) % 2 - 1, seen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 512 }), MemberType = typeof(Sources))]
public static void Where_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Where(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Where_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, (count + 1) / 2);
Assert.All(query.Where(x => x % 2 == 0).ToList(), x => seen.Add(x / 2));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 512 }), MemberType = typeof(UnorderedSources))]
public static void Where_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Where_Unordered_NotPipelined(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1, 2, 16 }), MemberType = typeof(Sources))]
public static void Where_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = -2;
Assert.All(query.Where(x => x % 2 == 0).ToList(), x => Assert.Equal(seen += 2, x));
Assert.Equal(count - (count - 1) % 2 - 1, seen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 512 }), MemberType = typeof(Sources))]
public static void Where_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Where_NotPipelined(labeled, count);
}
// Uses an element's index to calculate an output value. If order preservation isn't
// working, this would PROBABLY fail. Unfortunately, this isn't deterministic. But choosing
// larger input sizes increases the probability that it will.
[Theory]
[MemberData("Ranges", (object)(new int[] { 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Where_Indexed_Unordered(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (int i in query.Where((x, index) => x == index))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 512 }), MemberType = typeof(UnorderedSources))]
public static void Where_Indexed_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Where_Indexed_Unordered(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1, 2, 16 }), MemberType = typeof(Sources))]
public static void Where_Indexed(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
foreach (int i in query.Where((x, index) => x == index))
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 512 }), MemberType = typeof(Sources))]
public static void Where_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Where_Indexed(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Where_Indexed_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(query.Where((x, index) => x == index).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 512 }), MemberType = typeof(UnorderedSources))]
public static void Where_Indexed_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Where_Indexed_Unordered_NotPipelined(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1, 2, 16 }), MemberType = typeof(Sources))]
public static void Where_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.Where((x, index) => x == index).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 512 }), MemberType = typeof(Sources))]
public static void Where_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Where_Indexed_NotPipelined(labeled, count);
}
[Fact]
public static void Where_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Where(x => x));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Where((x, index) => x));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().Where((Func<bool, bool>)null));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().Where((Func<bool, int, bool>)null));
}
}
}
| 42.274725 | 124 | 0.582792 | [
"MIT"
] | er0dr1guez/corefx | src/System.Linq.Parallel/tests/QueryOperators/WhereTests.cs | 7,694 | C# |
namespace SampleParser
{
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()
{
this.button1 = new System.Windows.Forms.Button();
this.TxtFileName = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.TxtContents = new System.Windows.Forms.TextBox();
this.btnParse = new System.Windows.Forms.Button();
this.dlgOpenFile = new System.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(425, 48);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "&Browse";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// TxtFileName
//
this.TxtFileName.Location = new System.Drawing.Point(109, 48);
this.TxtFileName.Name = "TxtFileName";
this.TxtFileName.ReadOnly = true;
this.TxtFileName.Size = new System.Drawing.Size(301, 22);
this.TxtFileName.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(63, 47);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(30, 17);
this.label1.TabIndex = 2;
this.label1.Text = "File";
//
// TxtContents
//
this.TxtContents.Location = new System.Drawing.Point(40, 95);
this.TxtContents.Multiline = true;
this.TxtContents.Name = "TxtContents";
this.TxtContents.ReadOnly = true;
this.TxtContents.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.TxtContents.Size = new System.Drawing.Size(613, 252);
this.TxtContents.TabIndex = 3;
//
// btnParse
//
this.btnParse.Location = new System.Drawing.Point(519, 48);
this.btnParse.Name = "btnParse";
this.btnParse.Size = new System.Drawing.Size(75, 23);
this.btnParse.TabIndex = 0;
this.btnParse.Text = "&Parse";
this.btnParse.UseVisualStyleBackColor = true;
this.btnParse.Click += new System.EventHandler(this.btnParse_Click);
//
// dlgOpenFile
//
this.dlgOpenFile.FileName = "PDFFile.pdf";
this.dlgOpenFile.Filter = "PDF Files|*.pdf|All Files|*.*";
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(667, 363);
this.Controls.Add(this.TxtContents);
this.Controls.Add(this.label1);
this.Controls.Add(this.TxtFileName);
this.Controls.Add(this.btnParse);
this.Controls.Add(this.button1);
this.Name = "MainForm";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox TxtFileName;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox TxtContents;
private System.Windows.Forms.Button btnParse;
private System.Windows.Forms.OpenFileDialog dlgOpenFile;
}
}
| 39.915966 | 108 | 0.547158 | [
"MIT"
] | PLDinesh/PDFsharp-samples | samples/SampleParser/MainForm.Designer.cs | 4,752 | C# |
// Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Threading;
namespace Hazelcast.Core
{
/// <summary>
/// Utilities for managing time-to-live.
/// </summary>
public static class LeaseTime
{
/// <summary>
/// A constants used to specify an infinite lease time.
/// </summary>
public static readonly TimeSpan InfiniteTimeSpan = Timeout.InfiniteTimeSpan;
/// <summary>
/// A constants used to specify a zero lease time (expire immediately).
/// </summary>
public static readonly TimeSpan Zero = TimeSpan.Zero;
}
}
| 33.305556 | 84 | 0.684737 | [
"Apache-2.0"
] | BigYellowHammer/hazelcast-csharp-client | src/Hazelcast.Net/Core/LeaseTime.cs | 1,201 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Diagnostics;
using System.IO;
namespace BLTools.Security.Authorization {
public abstract class TSecurityStorage {
#region Public properties
public string Name { get; set; }
public TSecurityUserCollection Users { get; set; }
public TSecurityGroupCollection Groups { get; set; }
#endregion Public properties
public TSecurityStorage() {}
public TSecurityStorage(TSecurityStorage storage) {
Name = storage.Name;
Users = new TSecurityUserCollection(storage.Users);
Groups = new TSecurityGroupCollection(storage.Groups);
}
public abstract void Save();
public abstract void Save(string name);
}
}
| 26 | 60 | 0.732051 | [
"MIT"
] | bollylu/BLTools | BLTools/BLTools.45/Security/Authorization/TSecurityStorage.cs | 782 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LevelManager : MonoBehaviour
{
// aqui estaran todos los prefabs de cada dibujo
public List<GameObject> tilesprefabs;
public List<Transform> posicionesdeloscubosenescena;
public GameObject empty;
// este se le asignara segun un random range, uno del os tilesprefabs
public GameObject cuboseleccionado;
public bool cambiacubo = true;
public Vector3 seccion;
public float limiteMovimientos;
public Text moveLimit;
//=========================================================
void Start ()
{
StartLevel ();
// ya que startlevel, se llamara tanto como al iniciar el juego... como al pasar al siguiente nivel,
// lo converti en un metodo, y lo llame desde un start
}
public void StartLevel ()
{
//antes intente crear esta variable en el game manager y llamarla desde esta... pero siempre sucedia algo que me impedia.. por lo que termine poniendolo asi
limiteMovimientos = ((((GameManager.Instance.nivelNum * 2) + 2) * 2) * ((GameManager.Instance.nivelNum * 2) + 2));
//si el numero de nivel es (1,2,3) los limites de movimientos son (32,72,128)...
// este al iniciar cada vez un nivel... mostrara al jugador cuantos movimientos maximos puede realizar para ganar.
moveLimit.text = "limite de movimientos " + limiteMovimientos.ToString ();
GameManager.Instance.StartCoroutine(GameManager.Instance. mostrarNextLevelSprite ());
//cada vez que inicie un nivel nuevo... se llamara la funcion de mostrar este sprite, informando que el siguiente nivel se acerca.
int boardSize = (GameManager.Instance. nivelNum * 2)+2;
//dependiendo del numero del nivel en que se esté... cambiara el tamaño del tablero, y este valor se guardará en la variable boardsize.
//como los tiles se empezaran a instanciar desde las posiciones 0 tanto en x y y... e iran aumentando... el tablero que estos formaran...
//será mas grande que los elementos decorativos en el escenario... por lo que tuve que convertirlos en hijos de un game object dueño de este script... y asi escalandolo y moviendolo... se ajustaran
// para que queden acomodados todos los tiles prefabs dentro del muro y las dos columnas decorativas
transform.localScale = new Vector3(boardSize,boardSize,boardSize);
transform.position = new Vector3 (GameManager.Instance.nivelNum+0.5f,GameManager.Instance.nivelNum+0.5f,0);
// aqui utilizando dos for, se instanciaran en orden en cada posicion... unos emptys, y estos se guardaran en una lista... que almacena sus respectivas posiciones del transform
// los emptys tienen un script que los destruye una vez el jugador empieza a seleccionar cubos... por lo que ya no necesitan ser destruidos despues.
for (int x = 0; x < boardSize; x++)
{
for (int y = 0; y < boardSize; y++)
{
seccion = new Vector3 (x, y, 0);
posicionesdeloscubosenescena.Add (Instantiate (empty,seccion,Quaternion.identity).transform);
}
}
// luego de que se instanciaron los emptys en todas las posiciones del tablero...
//se procede a instanciar los tiles en sus posiciones al azar...
Asignartag (boardSize);
}
//================================================================
public void Asignartag (int boardSize)
{
//este for se repetira (la mitad de la todtalidad de cubos en escena) de veces.
for (int i =0 ; i<(boardSize*(boardSize/2)); i++)
{
//en una variable j de... las posiciones disponibles para instanciar un cubo
// se ordena agarrar una posicion al azar y asignarla como argumento a la funcion agarrartransformalazar
// y luego se ordena remover esta de la lista de posiciones disponibles, para evitar instanciar un tile, en otro tile existente.
int j = UnityEngine.Random.Range (0, posicionesdeloscubosenescena.Count);
Agarrartransformalazar (j);
posicionesdeloscubosenescena.Remove (posicionesdeloscubosenescena[j]);
//como no podia reasignarle un valor a j... tuve que crear otra variable llamada j2
int j2 = UnityEngine.Random.Range (0, posicionesdeloscubosenescena.Count);
Agarrartransformalazar (j2);
posicionesdeloscubosenescena.Remove (posicionesdeloscubosenescena[j2]);
}
}
//esta funcion solamente instancia un tileprefab en la posicion del (empty almacenado en la listade posiciones disponibles)
//Y utilizando un if una variable tipo bool... el tile prefab cambia por un random range... cada dos veces que se llama
public void Agarrartransformalazar (int jota)
{
if (cambiacubo == true)
{
int x = UnityEngine.Random.Range (0, tilesprefabs.Count);
cuboseleccionado = tilesprefabs [x];
}
Instantiate (cuboseleccionado,(posicionesdeloscubosenescena[jota].position),Quaternion.identity);
cambiacubo = !cambiacubo;
}
}
| 40.982906 | 200 | 0.725965 | [
"MIT"
] | vocero1114/concentrese | Assets/scripts/LevelManager.cs | 4,802 | C# |
/*
* Copyright 2012-2019 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using NativeULong = System.UInt64;
// Note: Code in this file is generated automatically.
namespace Net.Pkcs11Interop.LowLevelAPI81
{
/// <summary>
/// Low level PKCS#11 wrapper
/// </summary>
public class Pkcs11Library : LowLevelPkcs11Library, IDisposable
{
/// <summary>
/// Flag indicating whether instance has been disposed
/// </summary>
protected bool _disposed = false;
/// <summary>
/// Handle to the PKCS#11 library
/// </summary>
protected IntPtr _libraryHandle = IntPtr.Zero;
/// <summary>
/// Delegates for PKCS#11 functions
/// </summary>
private Delegates _delegates = null;
/// <summary>
/// Loads PCKS#11 library
/// </summary>
/// <param name="libraryPath">Library name or path</param>
public Pkcs11Library(string libraryPath)
{
try
{
if (!string.IsNullOrEmpty(libraryPath))
_libraryHandle = UnmanagedLibrary.Load(libraryPath);
_delegates = new Delegates(_libraryHandle, true);
}
catch
{
Release();
throw;
}
}
/// <summary>
/// Loads PCKS#11 library
/// </summary>
/// <param name="libraryPath">Library name or path</param>
/// <param name="useGetFunctionList">Flag indicating whether cryptoki function pointers should be acquired via C_GetFunctionList (true) or via platform native function (false)</param>
public Pkcs11Library(string libraryPath, bool useGetFunctionList)
{
try
{
if (!string.IsNullOrEmpty(libraryPath))
_libraryHandle = UnmanagedLibrary.Load(libraryPath);
_delegates = new Delegates(_libraryHandle, useGetFunctionList);
}
catch
{
Release();
throw;
}
}
/// <summary>
/// Unloads PKCS#11 library. Called automaticaly when object is being disposed.
/// </summary>
protected void Release()
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
if (_libraryHandle != IntPtr.Zero)
{
UnmanagedLibrary.Unload(_libraryHandle);
_libraryHandle = IntPtr.Zero;
}
}
/// <summary>
/// Initializes the Cryptoki library
/// </summary>
/// <param name="initArgs">CK_C_INITIALIZE_ARGS structure containing information on how the library should deal with multi-threaded access or null if an application will not be accessing Cryptoki through multiple threads simultaneously</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CANT_LOCK, CKR_CRYPTOKI_ALREADY_INITIALIZED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_NEED_TO_CREATE_THREADS, CKR_OK</returns>
public CKR C_Initialize(CK_C_INITIALIZE_ARGS initArgs)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_Initialize(initArgs);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Called to indicate that an application is finished with the Cryptoki library. It should be the last Cryptoki call made by an application.
/// </summary>
/// <param name="reserved">Reserved for future versions. For this version, it should be set to null.</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK</returns>
public CKR C_Finalize(IntPtr reserved)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_Finalize(reserved);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Returns general information about Cryptoki
/// </summary>
/// <param name="info">Structure that receives the information</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK</returns>
public CKR C_GetInfo(ref CK_INFO info)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetInfo(ref info);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Returns a pointer to the Cryptoki library's list of function pointers
/// </summary>
/// <param name="functionList">Pointer to a value which will receive a pointer to the library's CK_FUNCTION_LIST structure</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK</returns>
public CKR C_GetFunctionList(out IntPtr functionList)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetFunctionList(out functionList);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Obtains a list of slots in the system
/// </summary>
/// <param name="tokenPresent">Indicates whether the list obtained includes only those slots with a token present (true) or all slots (false)</param>
/// <param name="slotList">
/// If set to null then the number of slots is returned in "count" parameter, without actually returning a list of slots.
/// If not set to null then "count" parameter must contain the lenght of slotList array and slot list is returned in "slotList" parameter.
/// </param>
/// <param name="count">Location that receives the number of slots</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK</returns>
public CKR C_GetSlotList(bool tokenPresent, NativeULong[] slotList, ref NativeULong count)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetSlotList(tokenPresent, slotList, ref count);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Obtains information about a particular slot in the system
/// </summary>
/// <param name="slotId">The ID of the slot</param>
/// <param name="info">Structure that receives the slot information</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_SLOT_ID_INVALID</returns>
public CKR C_GetSlotInfo(NativeULong slotId, ref CK_SLOT_INFO info)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetSlotInfo(slotId, ref info);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Obtains information about a particular token in the system
/// </summary>
/// <param name="slotId">The ID of the token's slot</param>
/// <param name="info">Structure that receives the token information</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED, CKR_ARGUMENTS_BAD</returns>
public CKR C_GetTokenInfo(NativeULong slotId, ref CK_TOKEN_INFO info)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetTokenInfo(slotId, ref info);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Obtains a list of mechanism types supported by a token
/// </summary>
/// <param name="slotId">The ID of the token's slot</param>
/// <param name="mechanismList">
/// If set to null then the number of mechanisms is returned in "count" parameter, without actually returning a list of mechanisms.
/// If not set to null then "count" parameter must contain the lenght of mechanismList array and mechanism list is returned in "mechanismList" parameter.
/// </param>
/// <param name="count">Location that receives the number of mechanisms</param>
/// <returns>CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED, CKR_ARGUMENTS_BAD</returns>
public CKR C_GetMechanismList(NativeULong slotId, CKM[] mechanismList, ref NativeULong count)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong[] nativeULongList = null;
if (mechanismList != null)
nativeULongList = new NativeULong[mechanismList.Length];
NativeULong rv = _delegates.C_GetMechanismList(slotId, nativeULongList, ref count);
if (mechanismList != null)
{
for (int i = 0; i < mechanismList.Length; i++)
mechanismList[i] = ConvertUtils.UInt64ToCKM(nativeULongList[i]);
}
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Obtains information about a particular mechanism possibly supported by a token
/// </summary>
/// <param name="slotId">The ID of the token's slot</param>
/// <param name="type">The type of mechanism</param>
/// <param name="info">Structure that receives the mechanism information</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_MECHANISM_INVALID, CKR_OK, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED, CKR_ARGUMENTS_BAD</returns>
public CKR C_GetMechanismInfo(NativeULong slotId, CKM type, ref CK_MECHANISM_INFO info)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetMechanismInfo(slotId, ConvertUtils.UInt64FromCKM(type), ref info);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Initializes a token
/// </summary>
/// <param name="slotId">The ID of the token's slot</param>
/// <param name="pin">SO's initial PIN or null to use protected authentication path (pinpad)</param>
/// <param name="pinLen">The length of the PIN in bytes</param>
/// <param name="label">32-byte long label of the token which must be padded with blank characters</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_PIN_INCORRECT, CKR_PIN_LOCKED, CKR_SESSION_EXISTS, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED, CKR_TOKEN_WRITE_PROTECTED, CKR_ARGUMENTS_BAD</returns>
public CKR C_InitToken(NativeULong slotId, byte[] pin, NativeULong pinLen, byte[] label)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_InitToken(slotId, pin, pinLen, label);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Initializes the normal user's PIN
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="pin">Normal user's PIN or null to use protected authentication path (pinpad)</param>
/// <param name="pinLen">The length of the PIN in bytes</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_PIN_INVALID, CKR_PIN_LEN_RANGE, CKR_SESSION_CLOSED, CKR_SESSION_READ_ONLY, CKR_SESSION_HANDLE_INVALID, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN, CKR_ARGUMENTS_BAD</returns>
public CKR C_InitPIN(NativeULong session, byte[] pin, NativeULong pinLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_InitPIN(session, pin, pinLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Modifies the PIN of the user that is currently logged in, or the CKU_USER PIN if the session is not logged in
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="oldPin">Old PIN or null to use protected authentication path (pinpad)</param>
/// <param name="oldPinLen">The length of the old PIN in bytes</param>
/// <param name="newPin">New PIN or null to use protected authentication path (pinpad)</param>
/// <param name="newPinLen">The length of the new PIN in bytes</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_PIN_INCORRECT, CKR_PIN_INVALID, CKR_PIN_LEN_RANGE, CKR_PIN_LOCKED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TOKEN_WRITE_PROTECTED, CKR_ARGUMENTS_BAD</returns>
public CKR C_SetPIN(NativeULong session, byte[] oldPin, NativeULong oldPinLen, byte[] newPin, NativeULong newPinLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_SetPIN(session, oldPin, oldPinLen, newPin, newPinLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Opens a session between an application and a token in a particular slot
/// </summary>
/// <param name="slotId">The ID of the token's slot</param>
/// <param name="flags">Flags indicating the type of session</param>
/// <param name="application">An application defined pointer to be passed to the notification callback</param>
/// <param name="notify">The address of the notification callback function</param>
/// <param name="session">Location that receives the handle for the new session</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_SESSION_COUNT, CKR_SESSION_PARALLEL_NOT_SUPPORTED, CKR_SESSION_READ_WRITE_SO_EXISTS, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED, CKR_TOKEN_WRITE_PROTECTED, CKR_ARGUMENTS_BAD</returns>
public CKR C_OpenSession(NativeULong slotId, NativeULong flags, IntPtr application, IntPtr notify, ref NativeULong session)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_OpenSession(slotId, flags, application, notify, ref session);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Closes a session between an application and a token
/// </summary>
/// <param name="session">The session's handle</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_CloseSession(NativeULong session)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_CloseSession(session);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Closes all sessions an application has with a token
/// </summary>
/// <param name="slotId">The ID of the token's slot</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT</returns>
public CKR C_CloseAllSessions(NativeULong slotId)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_CloseAllSessions(slotId);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Obtains information about a session
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="info">Structure that receives the session information</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_ARGUMENTS_BAD</returns>
public CKR C_GetSessionInfo(NativeULong session, ref CK_SESSION_INFO info)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetSessionInfo(session, ref info);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Obtains a copy of the cryptographic operations state of a session encoded as byte array
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="operationState">
/// If set to null then the length of state is returned in "operationStateLen" parameter, without actually returning a state.
/// If not set to null then "operationStateLen" parameter must contain the lenght of operationState array and state is returned in "operationState" parameter.
/// </param>
/// <param name="operationStateLen">Location that receives the length in bytes of the state</param>
/// <returns>CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_STATE_UNSAVEABLE, CKR_ARGUMENTS_BAD</returns>
public CKR C_GetOperationState(NativeULong session, byte[] operationState, ref NativeULong operationStateLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetOperationState(session, operationState, ref operationStateLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Restores the cryptographic operations state of a session from bytes obtained with C_GetOperationState
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="operationState">Saved session state</param>
/// <param name="operationStateLen">Length of saved session state</param>
/// <param name="encryptionKey">Handle to the key which will be used for an ongoing encryption or decryption operation in the restored session or CK_INVALID_HANDLE if not needed</param>
/// <param name="authenticationKey">Handle to the key which will be used for an ongoing operation in the restored session or CK_INVALID_HANDLE if not needed</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_CHANGED, CKR_KEY_NEEDED, CKR_KEY_NOT_NEEDED, CKR_OK, CKR_SAVED_STATE_INVALID, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_ARGUMENTS_BAD</returns>
public CKR C_SetOperationState(NativeULong session, byte[] operationState, NativeULong operationStateLen, NativeULong encryptionKey, NativeULong authenticationKey)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_SetOperationState(session, operationState, operationStateLen, encryptionKey, authenticationKey);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Logs a user into a token
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="userType">The user type</param>
/// <param name="pin">User's PIN or null to use protected authentication path (pinpad)</param>
/// <param name="pinLen">Length of user's PIN</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_PIN_INCORRECT, CKR_PIN_LOCKED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY_EXISTS, CKR_USER_ALREADY_LOGGED_IN, CKR_USER_ANOTHER_ALREADY_LOGGED_IN, CKR_USER_PIN_NOT_INITIALIZED, CKR_USER_TOO_MANY_TYPES, CKR_USER_TYPE_INVALID</returns>
public CKR C_Login(NativeULong session, CKU userType, byte[] pin, NativeULong pinLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_Login(session, ConvertUtils.UInt64FromCKU(userType), pin, pinLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Logs a user out from a token
/// </summary>
/// <param name="session">The session's handle</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_Logout(NativeULong session)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_Logout(session);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Creates a new object
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="template">Object's template</param>
/// <param name="count">The number of attributes in the template</param>
/// <param name="objectId">Location that receives the new object's handle</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_CURVE_NOT_SUPPORTED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_DOMAIN_PARAMS_INVALID, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_CreateObject(NativeULong session, CK_ATTRIBUTE[] template, NativeULong count, ref NativeULong objectId)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_CreateObject(session, template, count, ref objectId);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Copies an object, creating a new object for the copy
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="objectId">The object's handle</param>
/// <param name="template">Template for the new object</param>
/// <param name="count">The number of attributes in the template</param>
/// <param name="newObjectId">Location that receives the handle for the copy of the object</param>
/// <returns>CKR_ACTION_PROHIBITED, CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OBJECT_HANDLE_INVALID, CKR_OK, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_CopyObject(NativeULong session, NativeULong objectId, CK_ATTRIBUTE[] template, NativeULong count, ref NativeULong newObjectId)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_CopyObject(session, objectId, template, count, ref newObjectId);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Destroys an object
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="objectId">The object's handle</param>
/// <returns>CKR_ACTION_PROHIBITED, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OBJECT_HANDLE_INVALID, CKR_OK, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TOKEN_WRITE_PROTECTED</returns>
public CKR C_DestroyObject(NativeULong session, NativeULong objectId)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DestroyObject(session, objectId);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Gets the size of an object in bytes
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="objectId">The object's handle</param>
/// <param name="size">Location that receives the size in bytes of the object</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_INFORMATION_SENSITIVE, CKR_OBJECT_HANDLE_INVALID, CKR_OK, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_GetObjectSize(NativeULong session, NativeULong objectId, ref NativeULong size)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetObjectSize(session, objectId, ref size);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Obtains the value of one or more attributes of an object
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="objectId">The object's handle</param>
/// <param name="template">Template that specifies which attribute values are to be obtained, and receives the attribute values</param>
/// <param name="count">The number of attributes in the template</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_SENSITIVE, CKR_ATTRIBUTE_TYPE_INVALID, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OBJECT_HANDLE_INVALID, CKR_OK, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_GetAttributeValue(NativeULong session, NativeULong objectId, CK_ATTRIBUTE[] template, NativeULong count)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetAttributeValue(session, objectId, template, count);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Modifies the value of one or more attributes of an object
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="objectId">The object's handle</param>
/// <param name="template">Template that specifies which attribute values are to be modified and their new values</param>
/// <param name="count">The number of attributes in the template</param>
/// <returns>CKR_ACTION_PROHIBITED, CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OBJECT_HANDLE_INVALID, CKR_OK, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_SetAttributeValue(NativeULong session, NativeULong objectId, CK_ATTRIBUTE[] template, NativeULong count)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_SetAttributeValue(session, objectId, template, count);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Initializes a search for token and session objects that match a template
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="template">Search template that specifies the attribute values to match</param>
/// <param name="count">The number of attributes in the search template</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_FindObjectsInit(NativeULong session, CK_ATTRIBUTE[] template, NativeULong count)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_FindObjectsInit(session, template, count);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues a search for token and session objects that match a template, obtaining additional object handles
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="objectId">Location that receives the list (array) of additional object handles</param>
/// <param name="maxObjectCount">The maximum number of object handles to be returned</param>
/// <param name="objectCount">Location that receives the actual number of object handles returned</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_FindObjects(NativeULong session, NativeULong[] objectId, NativeULong maxObjectCount, ref NativeULong objectCount)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_FindObjects(session, objectId, maxObjectCount, ref objectCount);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Terminates a search for token and session objects
/// </summary>
/// <param name="session">The session's handle</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_FindObjectsFinal(NativeULong session)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_FindObjectsFinal(session);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Initializes an encryption operation
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">The encryption mechanism</param>
/// <param name="key">The handle of the encryption key</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_EncryptInit(NativeULong session, ref CK_MECHANISM mechanism, NativeULong key)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_EncryptInit(session, ref mechanism, key);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Encrypts single-part data
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="data">Data to be encrypted</param>
/// <param name="dataLen">Length of data in bytes</param>
/// <param name="encryptedData">
/// If set to null then the length of encrypted data is returned in "encryptedDataLen" parameter, without actually returning encrypted data.
/// If not set to null then "encryptedDataLen" parameter must contain the lenght of encryptedData array and encrypted data is returned in "encryptedData" parameter.
/// </param>
/// <param name="encryptedDataLen">Location that holds the length in bytes of the encrypted data</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_Encrypt(NativeULong session, byte[] data, NativeULong dataLen, byte[] encryptedData, ref NativeULong encryptedDataLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_Encrypt(session, data, dataLen, encryptedData, ref encryptedDataLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues a multi-part encryption operation, processing another data part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="part">The data part to be encrypted</param>
/// <param name="partLen">Length of data part in bytes</param>
/// <param name="encryptedPart">
/// If set to null then the length of encrypted data part is returned in "encryptedPartLen" parameter, without actually returning encrypted data part.
/// If not set to null then "encryptedPartLen" parameter must contain the lenght of encryptedPart array and encrypted data part is returned in "encryptedPart" parameter.
/// </param>
/// <param name="encryptedPartLen">Location that holds the length in bytes of the encrypted data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_EncryptUpdate(NativeULong session, byte[] part, NativeULong partLen, byte[] encryptedPart, ref NativeULong encryptedPartLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_EncryptUpdate(session, part, partLen, encryptedPart, ref encryptedPartLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Finishes a multi-part encryption operation
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="lastEncryptedPart">
/// If set to null then the length of last encrypted data part is returned in "lastEncryptedPartLen" parameter, without actually returning last encrypted data part.
/// If not set to null then "lastEncryptedPartLen" parameter must contain the lenght of lastEncryptedPart array and last encrypted data part is returned in "lastEncryptedPart" parameter.
/// </param>
/// <param name="lastEncryptedPartLen">Location that holds the length of the last encrypted data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_EncryptFinal(NativeULong session, byte[] lastEncryptedPart, ref NativeULong lastEncryptedPartLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Initializes a decryption operation
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">The decryption mechanism</param>
/// <param name="key">The handle of the decryption key</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_DecryptInit(NativeULong session, ref CK_MECHANISM mechanism, NativeULong key)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DecryptInit(session, ref mechanism, key);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Decrypts encrypted data in a single part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="encryptedData">Encrypted data</param>
/// <param name="encryptedDataLen">The length of the encrypted data</param>
/// <param name="data">
/// If set to null then the length of decrypted data is returned in "dataLen" parameter, without actually returning decrypted data.
/// If not set to null then "dataLen" parameter must contain the lenght of data array and decrypted data is returned in "data" parameter.
/// </param>
/// <param name="dataLen">Location that holds the length of the decrypted data</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_Decrypt(NativeULong session, byte[] encryptedData, NativeULong encryptedDataLen, byte[] data, ref NativeULong dataLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_Decrypt(session, encryptedData, encryptedDataLen, data, ref dataLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues a multi-part decryption operation, processing another encrypted data part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="encryptedPart">Encrypted data part</param>
/// <param name="encryptedPartLen">Length of the encrypted data part</param>
/// <param name="part">
/// If set to null then the length of decrypted data part is returned in "partLen" parameter, without actually returning decrypted data part.
/// If not set to null then "partLen" parameter must contain the lenght of part array and decrypted data part is returned in "part" parameter.
/// </param>
/// <param name="partLen">Location that holds the length of the decrypted data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_DecryptUpdate(NativeULong session, byte[] encryptedPart, NativeULong encryptedPartLen, byte[] part, ref NativeULong partLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DecryptUpdate(session, encryptedPart, encryptedPartLen, part, ref partLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Finishes a multi-part decryption operation
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="lastPart">
/// If set to null then the length of last decrypted data part is returned in "lastPartLen" parameter, without actually returning last decrypted data part.
/// If not set to null then "lastPartLen" parameter must contain the lenght of lastPart array and last decrypted data part is returned in "lastPart" parameter.
/// </param>
/// <param name="lastPartLen">Location that holds the length of the last decrypted data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_DecryptFinal(NativeULong session, byte[] lastPart, ref NativeULong lastPartLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DecryptFinal(session, lastPart, ref lastPartLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Initializes a message-digesting operation
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">The digesting mechanism</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_DigestInit(NativeULong session, ref CK_MECHANISM mechanism)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DigestInit(session, ref mechanism);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Digests data in a single part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="data">Data to be digested</param>
/// <param name="dataLen">The length of the data to be digested</param>
/// <param name="digest">
/// If set to null then the length of digest is returned in "digestLen" parameter, without actually returning digest.
/// If not set to null then "digestLen" parameter must contain the lenght of digest array and digest is returned in "digest" parameter.
/// </param>
/// <param name="digestLen">Location that holds the length of the message digest</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_Digest(NativeULong session, byte[] data, NativeULong dataLen, byte[] digest, ref NativeULong digestLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_Digest(session, data, dataLen, digest, ref digestLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues a multi-part message-digesting operation, processing another data part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="part">Data part</param>
/// <param name="partLen">The length of the data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_DigestUpdate(NativeULong session, byte[] part, NativeULong partLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DigestUpdate(session, part, partLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues a multi-part message-digesting operation by digesting the value of a secret key
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="key">The handle of the secret key to be digested</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_HANDLE_INVALID, CKR_KEY_INDIGESTIBLE, CKR_KEY_SIZE_RANGE, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_DigestKey(NativeULong session, NativeULong key)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DigestKey(session, key);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Finishes a multi-part message-digesting operation, returning the message digest
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="digest">
/// If set to null then the length of digest is returned in "digestLen" parameter, without actually returning digest.
/// If not set to null then "digestLen" parameter must contain the lenght of digest array and digest is returned in "digest" parameter.
/// </param>
/// <param name="digestLen">Location that holds the length of the message digest</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_DigestFinal(NativeULong session, byte[] digest, ref NativeULong digestLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DigestFinal(session, digest, ref digestLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Initializes a signature operation, where the signature is an appendix to the data
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">Signature mechanism</param>
/// <param name="key">Handle of the signature key</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED,CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_SignInit(NativeULong session, ref CK_MECHANISM mechanism, NativeULong key)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_SignInit(session, ref mechanism, key);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Signs data in a single part, where the signature is an appendix to the data
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="data">Data to be signed</param>
/// <param name="dataLen">The length of the data</param>
/// <param name="signature">
/// If set to null then the length of signature is returned in "signatureLen" parameter, without actually returning signature.
/// If not set to null then "signatureLen" parameter must contain the lenght of signature array and signature is returned in "signature" parameter.
/// </param>
/// <param name="signatureLen">Location that holds the length of the signature</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN, CKR_FUNCTION_REJECTED</returns>
public CKR C_Sign(NativeULong session, byte[] data, NativeULong dataLen, byte[] signature, ref NativeULong signatureLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_Sign(session, data, dataLen, signature, ref signatureLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues a multi-part signature operation, processing another data part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="part">Data part</param>
/// <param name="partLen">The length of the data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_SignUpdate(NativeULong session, byte[] part, NativeULong partLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_SignUpdate(session, part, partLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Finishes a multi-part signature operation, returning the signature
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="signature">
/// If set to null then the length of signature is returned in "signatureLen" parameter, without actually returning signature.
/// If not set to null then "signatureLen" parameter must contain the lenght of signature array and signature is returned in "signature" parameter.
/// </param>
/// <param name="signatureLen">Location that holds the length of the signature</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN, CKR_FUNCTION_REJECTED</returns>
public CKR C_SignFinal(NativeULong session, byte[] signature, ref NativeULong signatureLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_SignFinal(session, signature, ref signatureLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Initializes a signature operation, where the data can be recovered from the signature
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">Signature mechanism</param>
/// <param name="key">Handle of the signature key</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_SignRecoverInit(NativeULong session, ref CK_MECHANISM mechanism, NativeULong key)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_SignRecoverInit(session, ref mechanism, key);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Signs data in a single operation, where the data can be recovered from the signature
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="data">Data to be signed</param>
/// <param name="dataLen">The length of data to be signed</param>
/// <param name="signature">
/// If set to null then the length of signature is returned in "signatureLen" parameter, without actually returning signature.
/// If not set to null then "signatureLen" parameter must contain the lenght of signature array and signature is returned in "signature" parameter.
/// </param>
/// <param name="signatureLen">Location that holds the length of the signature</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_SignRecover(NativeULong session, byte[] data, NativeULong dataLen, byte[] signature, ref NativeULong signatureLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_SignRecover(session, data, dataLen, signature, ref signatureLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Initializes a verification operation, where the signature is an appendix to the data
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">The verification mechanism</param>
/// <param name="key">The handle of the verification key</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_VerifyInit(NativeULong session, ref CK_MECHANISM mechanism, NativeULong key)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_VerifyInit(session, ref mechanism, key);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Verifies a signature in a single-part operation, where the signature is an appendix to the data
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="data">Data that were signed</param>
/// <param name="dataLen">The length of the data</param>
/// <param name="signature">Signature of data</param>
/// <param name="signatureLen">The length of signature</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SIGNATURE_INVALID, CKR_SIGNATURE_LEN_RANGE</returns>
public CKR C_Verify(NativeULong session, byte[] data, NativeULong dataLen, byte[] signature, NativeULong signatureLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_Verify(session, data, dataLen, signature, signatureLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues a multi-part verification operation, processing another data part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="part">Data part</param>
/// <param name="partLen">The length of the data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_VerifyUpdate(NativeULong session, byte[] part, NativeULong partLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_VerifyUpdate(session, part, partLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Finishes a multi-part verification operation, checking the signature
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="signature">Signature</param>
/// <param name="signatureLen">The length of signature</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SIGNATURE_INVALID, CKR_SIGNATURE_LEN_RANGE</returns>
public CKR C_VerifyFinal(NativeULong session, byte[] signature, NativeULong signatureLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_VerifyFinal(session, signature, signatureLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Initializes a signature verification operation, where the data is recovered from the signature
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">Verification mechanism</param>
/// <param name="key">The handle of the verification key</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_VerifyRecoverInit(NativeULong session, ref CK_MECHANISM mechanism, NativeULong key)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_VerifyRecoverInit(session, ref mechanism, key);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Verifies a signature in a single-part operation, where the data is recovered from the signature
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="signature">Signature</param>
/// <param name="signatureLen">The length of signature</param>
/// <param name="data">
/// If set to null then the length of recovered data is returned in "dataLen" parameter, without actually returning recovered data.
/// If not set to null then "dataLen" parameter must contain the lenght of data array and recovered data is returned in "data" parameter.
/// </param>
/// <param name="dataLen">Location that holds the length of the decrypted data</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SIGNATURE_LEN_RANGE, CKR_SIGNATURE_INVALID</returns>
public CKR C_VerifyRecover(NativeULong session, byte[] signature, NativeULong signatureLen, byte[] data, ref NativeULong dataLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_VerifyRecover(session, signature, signatureLen, data, ref dataLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues multi-part digest and encryption operations, processing another data part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="part">The data part to be digested and encrypted</param>
/// <param name="partLen">Length of data part in bytes</param>
/// <param name="encryptedPart">
/// If set to null then the length of encrypted data part is returned in "encryptedPartLen" parameter, without actually returning encrypted data part.
/// If not set to null then "encryptedPartLen" parameter must contain the lenght of encryptedPart array and encrypted data part is returned in "encryptedPart" parameter.
/// </param>
/// <param name="encryptedPartLen">Location that holds the length in bytes of the encrypted data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_DigestEncryptUpdate(NativeULong session, byte[] part, NativeULong partLen, byte[] encryptedPart, ref NativeULong encryptedPartLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DigestEncryptUpdate(session, part, partLen, encryptedPart, ref encryptedPartLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues a multi-part combined decryption and digest operation, processing another data part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="encryptedPart">Encrypted data part</param>
/// <param name="encryptedPartLen">Length of the encrypted data part</param>
/// <param name="part">
/// If set to null then the length of decrypted data part is returned in "partLen" parameter, without actually returning decrypted data part.
/// If not set to null then "partLen" parameter must contain the lenght of part array and decrypted data part is returned in "part" parameter.
/// </param>
/// <param name="partLen">Location that holds the length of the decrypted data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_DecryptDigestUpdate(NativeULong session, byte[] encryptedPart, NativeULong encryptedPartLen, byte[] part, ref NativeULong partLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DecryptDigestUpdate(session, encryptedPart, encryptedPartLen, part, ref partLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues a multi-part combined signature and encryption operation, processing another data part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="part">The data part to be signed and encrypted</param>
/// <param name="partLen">Length of data part in bytes</param>
/// <param name="encryptedPart">
/// If set to null then the length of encrypted data part is returned in "encryptedPartLen" parameter, without actually returning encrypted data part.
/// If not set to null then "encryptedPartLen" parameter must contain the lenght of encryptedPart array and encrypted data part is returned in "encryptedPart" parameter.
/// </param>
/// <param name="encryptedPartLen">Location that holds the length in bytes of the encrypted data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_SignEncryptUpdate(NativeULong session, byte[] part, NativeULong partLen, byte[] encryptedPart, ref NativeULong encryptedPartLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_SignEncryptUpdate(session, part, partLen, encryptedPart, ref encryptedPartLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Continues a multi-part combined decryption and verification operation, processing another data part
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="encryptedPart">Encrypted data part</param>
/// <param name="encryptedPartLen">Length of the encrypted data part</param>
/// <param name="part">
/// If set to null then the length of decrypted data part is returned in "partLen" parameter, without actually returning decrypted data part.
/// If not set to null then "partLen" parameter must contain the lenght of part array and decrypted data part is returned in "part" parameter.
/// </param>
/// <param name="partLen">Location that holds the length of the decrypted data part</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID</returns>
public CKR C_DecryptVerifyUpdate(NativeULong session, byte[] encryptedPart, NativeULong encryptedPartLen, byte[] part, ref NativeULong partLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DecryptVerifyUpdate(session, encryptedPart, encryptedPartLen, part, ref partLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Generates a secret key or set of domain parameters, creating a new object
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">Key generation mechanism</param>
/// <param name="template">The template for the new key or set of domain parameters</param>
/// <param name="count">The number of attributes in the template</param>
/// <param name="key">Location that receives the handle of the new key or set of domain parameters</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_CURVE_NOT_SUPPORTED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_GenerateKey(NativeULong session, ref CK_MECHANISM mechanism, CK_ATTRIBUTE[] template, NativeULong count, ref NativeULong key)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GenerateKey(session, ref mechanism, template, count, ref key);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Generates a public/private key pair, creating new key objects
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">Key generation mechanism</param>
/// <param name="publicKeyTemplate">The template for the public key</param>
/// <param name="publicKeyAttributeCount">The number of attributes in the public-key template</param>
/// <param name="privateKeyTemplate">The template for the private key</param>
/// <param name="privateKeyAttributeCount">The number of attributes in the private-key template</param>
/// <param name="publicKey">Location that receives the handle of the new public key</param>
/// <param name="privateKey">Location that receives the handle of the new private key</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_CURVE_NOT_SUPPORTED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_DOMAIN_PARAMS_INVALID, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_GenerateKeyPair(NativeULong session, ref CK_MECHANISM mechanism, CK_ATTRIBUTE[] publicKeyTemplate, NativeULong publicKeyAttributeCount, CK_ATTRIBUTE[] privateKeyTemplate, NativeULong privateKeyAttributeCount, ref NativeULong publicKey, ref NativeULong privateKey)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GenerateKeyPair(session, ref mechanism, publicKeyTemplate, publicKeyAttributeCount, privateKeyTemplate, privateKeyAttributeCount, ref publicKey, ref privateKey);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Wraps (i.e., encrypts) a private or secret key
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">Wrapping mechanism</param>
/// <param name="wrappingKey">The handle of the wrapping key</param>
/// <param name="key">The handle of the key to be wrapped</param>
/// <param name="wrappedKey">
/// If set to null then the length of wrapped key is returned in "wrappedKeyLen" parameter, without actually returning wrapped key.
/// If not set to null then "wrappedKeyLen" parameter must contain the lenght of wrappedKey array and wrapped key is returned in "wrappedKey" parameter.
/// </param>
/// <param name="wrappedKeyLen">Location that receives the length of the wrapped key</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_HANDLE_INVALID, CKR_KEY_NOT_WRAPPABLE, CKR_KEY_SIZE_RANGE, CKR_KEY_UNEXTRACTABLE, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN, CKR_WRAPPING_KEY_HANDLE_INVALID, CKR_WRAPPING_KEY_SIZE_RANGE, CKR_WRAPPING_KEY_TYPE_INCONSISTENT</returns>
public CKR C_WrapKey(NativeULong session, ref CK_MECHANISM mechanism, NativeULong wrappingKey, NativeULong key, byte[] wrappedKey, ref NativeULong wrappedKeyLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_WrapKey(session, ref mechanism, wrappingKey, key, wrappedKey, ref wrappedKeyLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Unwraps (i.e. decrypts) a wrapped key, creating a new private key or secret key object
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">Unwrapping mechanism</param>
/// <param name="unwrappingKey">The handle of the unwrapping key</param>
/// <param name="wrappedKey">Wrapped key</param>
/// <param name="wrappedKeyLen">The length of the wrapped key</param>
/// <param name="template">The template for the new key</param>
/// <param name="attributeCount">The number of attributes in the template</param>
/// <param name="key">Location that receives the handle of the unwrapped key</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_CURVE_NOT_SUPPORTED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_DOMAIN_PARAMS_INVALID, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_UNWRAPPING_KEY_HANDLE_INVALID, CKR_UNWRAPPING_KEY_SIZE_RANGE, CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT, CKR_USER_NOT_LOGGED_IN, CKR_WRAPPED_KEY_INVALID, CKR_WRAPPED_KEY_LEN_RANGE</returns>
public CKR C_UnwrapKey(NativeULong session, ref CK_MECHANISM mechanism, NativeULong unwrappingKey, byte[] wrappedKey, NativeULong wrappedKeyLen, CK_ATTRIBUTE[] template, NativeULong attributeCount, ref NativeULong key)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_UnwrapKey(session, ref mechanism, unwrappingKey, wrappedKey, wrappedKeyLen, template, attributeCount, ref key);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Derives a key from a base key, creating a new key object
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="mechanism">Key derivation mechanism</param>
/// <param name="baseKey">The handle of the base key</param>
/// <param name="template">The template for the new key</param>
/// <param name="attributeCount">The number of attributes in the template</param>
/// <param name="key">Location that receives the handle of the derived key</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_CURVE_NOT_SUPPORTED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_DOMAIN_PARAMS_INVALID, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_DeriveKey(NativeULong session, ref CK_MECHANISM mechanism, NativeULong baseKey, CK_ATTRIBUTE[] template, NativeULong attributeCount, ref NativeULong key)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_DeriveKey(session, ref mechanism, baseKey, template, attributeCount, ref key);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Mixes additional seed material into the token's random number generator
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="seed">The seed material</param>
/// <param name="seedLen">The length of the seed material</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_ACTIVE, CKR_RANDOM_SEED_NOT_SUPPORTED, CKR_RANDOM_NO_RNG, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_SeedRandom(NativeULong session, byte[] seed, NativeULong seedLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_SeedRandom(session, seed, seedLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Generates random or pseudo-random data
/// </summary>
/// <param name="session">The session's handle</param>
/// <param name="randomData">Location that receives the random data</param>
/// <param name="randomLen">The length in bytes of the random or pseudo-random data to be generated</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_ACTIVE, CKR_RANDOM_NO_RNG, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN</returns>
public CKR C_GenerateRandom(NativeULong session, byte[] randomData, NativeULong randomLen)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GenerateRandom(session, randomData, randomLen);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Legacy function which should simply return the value CKR_FUNCTION_NOT_PARALLEL
/// </summary>
/// <param name="session">The session's handle</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_FUNCTION_FAILED, CKR_FUNCTION_NOT_PARALLEL, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_CLOSED</returns>
public CKR C_GetFunctionStatus(NativeULong session)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_GetFunctionStatus(session);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Legacy function which should simply return the value CKR_FUNCTION_NOT_PARALLEL
/// </summary>
/// <param name="session">The session's handle</param>
/// <returns>CKR_CRYPTOKI_NOT_INITIALIZED, CKR_FUNCTION_FAILED, CKR_FUNCTION_NOT_PARALLEL, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_CLOSED</returns>
public CKR C_CancelFunction(NativeULong session)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_CancelFunction(session);
return ConvertUtils.UInt64ToCKR(rv);
}
/// <summary>
/// Waits for a slot event, such as token insertion or token removal, to occur
/// </summary>
/// <param name="flags">Determines whether or not the C_WaitForSlotEvent call blocks (i.e., waits for a slot event to occur)</param>
/// <param name="slot">Location which will receive the ID of the slot that the event occurred in</param>
/// <param name="reserved">Reserved for future versions (should be null)</param>
/// <returns>CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_NO_EVENT, CKR_OK</returns>
public CKR C_WaitForSlotEvent(NativeULong flags, ref NativeULong slot, IntPtr reserved)
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
NativeULong rv = _delegates.C_WaitForSlotEvent(flags, ref slot, reserved);
return ConvertUtils.UInt64ToCKR(rv);
}
#region IDisposable
/// <summary>
/// Disposes object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes object
/// </summary>
/// <param name="disposing">Flag indicating whether managed resources should be disposed</param>
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// Dispose managed objects
}
// Dispose unmanaged objects
Release();
_disposed = true;
}
}
/// <summary>
/// Class destructor that disposes object if caller forgot to do so
/// </summary>
~Pkcs11Library()
{
Dispose(false);
}
#endregion
}
}
| 65.961165 | 800 | 0.702973 | [
"Apache-2.0"
] | uae1972/Pkcs11Interop | src/Pkcs11Interop/LowLevelAPI81/Pkcs11Library.cs | 88,324 | C# |
//==============================================================================
// Copyright (c) 2017-2021 Fiats Inc. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt in the solution folder for
// full license information.
// https://www.fiats.asia/
// Fiats Inc. Nakano, Tokyo, Japan
//
using System.Threading;
using System.Threading.Tasks;
namespace BitFlyerDotNet.LightningApi
{
public partial class BitFlyerClient
{
/// <summary>
/// Get API Key Permissions
/// <see href="https://scrapbox.io/BitFlyerDotNet/GetPermissions">Online help</see>
/// </summary>
/// <returns></returns>
public Task<BitFlyerResponse<string[]>> GetPermissionsAsync(CancellationToken ct)
=> GetPrivateAsync<string[]>(nameof(GetPermissions), string.Empty, ct);
public BitFlyerResponse<string[]> GetPermissions() => GetPermissionsAsync(CancellationToken.None).Result;
}
}
| 36.407407 | 114 | 0.612411 | [
"MIT"
] | fiatsasia/BitFlyerDotNet | BitFlyerDotNet.LightningApi/Private/GetPermissions.cs | 985 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// Scrolls the item menu - why is this not part of the PopulateContent.cs script? No idea.
public class ScrollController : MonoBehaviour
{
public Canvas canvas;
public PopulateContent tab;
private long tabChangeTime = 0;
void Start()
{
}
void Update()
{
// Scroll with up/down on the left dpad
if(canvas != null && canvas.enabled && Mathf.Abs(OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick)[1]) > Mathf.Abs(OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick)[0]))
{
if (System.DateTime.Now.Ticks - tabChangeTime > 2000000)
{
tabChangeTime = System.DateTime.Now.Ticks;
tab.Clear();
tab.IncrementRow(OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick)[1] > 0);
tab.Populate();
}
}
// Change "tabs" with left dpad
if (canvas != null && canvas.enabled && Mathf.Abs(OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick)[0]) > Mathf.Abs(OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick)[1]))
{
if (System.DateTime.Now.Ticks - tabChangeTime > 2000000)
{
tabChangeTime = System.DateTime.Now.Ticks;
tab.Clear();
tab.IncrementIndex(OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick)[0] > 0);
tab.Populate();
}
}
}
}
| 30.816327 | 174 | 0.596026 | [
"MIT"
] | kevin-bruhwiler/Kowloon-Unity-Client | Assets/Oculus/VR/Scripts/ScrollController.cs | 1,512 | C# |
using System.Collections.Generic;
using System.Web.Mvc;
using ChartJS.NET.Charts.Line;
namespace ChartJS.NET.Sample.Controllers
{
public class LineChartController : Controller
{
public ActionResult Index()
{
//var LineChart = new LineChart();
//LineChart.Data.Datasets = new List<LineDataSet>
//{
// new LineDataSet
// {
// Label = "First Dataset",
// FillColor = "rgba(220, 220, 220, 0.5)",
// StrokeColor = "rgba(220, 220, 220, 0.8)",
// PointColor = "rgba(220, 220, 220, 0.75)",
// PointStrokeColor = "#fff",
// PointHighlightFill = "#fff",
// PointHighlightStroke = "rgba(220,220,220,1)",
// Data = new double[] {65, 59, 80, 81, 56, 55, 40}
// },
// new LineDataSet
// {
// Label = "Second Dataset",
// FillColor = "rgba(151,187,205,0.2)",
// StrokeColor = "rgba(151,187,205,1)",
// PointColor = "rgba(151,187,205,1)",
// PointStrokeColor = "#fff",
// PointHighlightFill = "#fff",
// PointHighlightStroke = "rgba(151,187,205,1)",
// Data = new double[] {28, 48, 40, 19, 86, 27, 90}
// }
//};
//LineChart.Data.Labels = new List<string>
//{
// "January",
// "February",
// "March",
// "April",
// "May",
// "June",
// "July"
//};
var lineChart = new LineChart();
lineChart.Data.Datasets = new List<LineDataSet>(){
new LineDataSet(){
Data = new double[] { 405, 405, 405, 405, 405, 405, 405, 405 },
Label = "Daily Goal in Minutes",
FillColor = "rgba(255,255,255,1)"
},
new LineDataSet(){
Data = new double[] { 50, 100, 150, 200, 250, 300, 350, 405 },
Label = "Hourly Goal in Minutes",
FillColor = "rgba(151,187,205,0.2)",
StrokeColor = "rgba(151,187,205,1)",
PointColor = "rgba(151,187,205,1)",
PointStrokeColor = "#fff",
PointHighlightFill = "#fff",
PointHighlightStroke = "rgba(151,187,205,1)"
},
new LineDataSet(){
Data = new double[] { 35, 135, 175, 185, 270, 325, 365, 450 },
Label = "Actual Work in Minutes",
FillColor = "rgba(220,220,220,0.2)",
StrokeColor = "rgba(220,220,220,1)",
PointColor = "rgba(220,220,220,1)",
PointStrokeColor = "#fff",
PointHighlightFill = "#fff",
PointHighlightStroke = "rgba(220,220,220,1)"
}
};
lineChart.Data.Labels = new List<string>()
{
"1st hour",
"2nd hour",
"3rd hour",
"4th hour",
"5th hour",
"6th hour",
"7th hour",
"8th hour"
};
lineChart.ChartConfig.DatasetFill = false;
lineChart.CanvasProperties.CanvasId = "line-chart-time";
lineChart.CanvasProperties.CssClass = "chart bar-chart";
return View(lineChart);
}
}
} | 37.33 | 83 | 0.415751 | [
"MIT"
] | nikspatel007/ChartJS.NET | ChartJSNet.Sample/Controllers/LineChartController.cs | 3,735 | C# |
using Paspan.Tests.Calc;
namespace Parlot.Tests.Calc
{
/*
* Grammar:
* expression => factor ( ( "-" | "+" ) factor )* ;
* factor => unary ( ( "/" | "*" ) unary )* ;
* unary => ( "-" ) unary
* | primary ;
* primary => NUMBER
* | "(" expression ")" ;
*/
/// <summary>
/// This version of the Parser creates and intermediate AST.
/// </summary>
public class ParlotParser
{
private Scanner _scanner;
public Expression Parse(string text)
{
_scanner = new Scanner(text);
return ParseExpression();
}
private Expression ParseExpression()
{
var expression = ParseFactor();
while (true)
{
_scanner.SkipWhiteSpace();
if (_scanner.ReadChar('+'))
{
_scanner.SkipWhiteSpace();
expression = new Addition(expression, ParseFactor());
}
else if (_scanner.ReadChar('-'))
{
_scanner.SkipWhiteSpace();
expression = new Subtraction(expression, ParseFactor());
}
else
{
break;
}
}
return expression;
}
private Expression ParseFactor()
{
var expression = ParseUnaryExpression();
while (true)
{
_scanner.SkipWhiteSpace();
if (_scanner.ReadChar('*'))
{
_scanner.SkipWhiteSpace();
expression = new Multiplication(expression, ParseUnaryExpression());
}
else if (_scanner.ReadChar('/'))
{
_scanner.SkipWhiteSpace();
expression = new Division(expression, ParseUnaryExpression());
}
else
{
break;
}
}
return expression;
}
/*
unary = ( "-" ) unary
| primary ;
*/
private Expression ParseUnaryExpression()
{
_scanner.SkipWhiteSpace();
if (_scanner.ReadChar('-'))
{
var inner = ParseUnaryExpression();
if (inner == null)
{
throw new ParseException("Expected expression after '-'", _scanner.Cursor.Position);
}
return new NegateExpression(inner);
}
return ParsePrimaryExpression();
}
/*
primary = NUMBER
| "(" expression ")" ;
*/
private Expression ParsePrimaryExpression()
{
_scanner.SkipWhiteSpace();
if (_scanner.ReadDecimal(out var number))
{
#if NETCOREAPP2_1
return new Number(decimal.Parse(number.GetText()));
#else
return new Number(decimal.Parse(number.Span));
#endif
}
if (_scanner.ReadChar('('))
{
var expression = ParseExpression();
if (!_scanner.ReadChar(')'))
{
throw new ParseException("Expected ')'", _scanner.Cursor.Position);
}
return expression;
}
throw new ParseException("Expected primary expression", _scanner.Cursor.Position);
}
}
}
| 25.186207 | 104 | 0.432092 | [
"BSD-3-Clause"
] | ToCSharp/paspan | test/Paspan.Benchmarks/Parlot/ParlotParser.cs | 3,652 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ERC721OwnerOfExample : MonoBehaviour
{
async void Start()
{
string chain = "binance";
string network = "mainnet";
string contract = "0x1dDB2C0897daF18632662E71fdD2dbDC0eB3a9Ec";
string tokenId = "100300140897";
string ownerOf = await ERC721.OwnerOf(chain, network, contract, tokenId);
print(ownerOf);
}
}
| 25.5 | 81 | 0.684096 | [
"MIT"
] | vocariz/nftunityplayground | NFTUnityPlayground/Assets/Web3Unity/Scripts/Prefabs/ERC721/ERC721OwnerOfExample.cs | 459 | C# |
// MIT License
//
// Copyright (c) 2016 Kyle Kingsbury
//
// 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.
namespace Sitecore.ContentSearch.Fluent.Results
{
public class SearchResultsWithFacets<T> where T : SearchResultItem
{
/// <summary>
///
/// </summary>
public virtual SearchResults<T> SearchResults { get; }
/// <summary>
///
/// </summary>
public virtual SearchFacetResults SearchFacetResults { get; }
public SearchResultsWithFacets(SearchResults<T> searchResults, SearchFacetResults searchFacetResults)
{
this.SearchResults = searchResults;
this.SearchFacetResults = searchFacetResults;
}
}
} | 41.809524 | 109 | 0.710706 | [
"MIT"
] | KKings/Sitecore.ContentSearch.Fluent | src/Sitecore.ContentSearch.Fluent/Results/SearchResultsWithFacets.cs | 1,758 | 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) 2020 Michael Möller <mmoeller@openhardwaremonitor.org>
*/
using System;
using System.Drawing;
namespace OpenHardwareMonitor.GUI {
public static class DpiHelper {
public const double LogicalDpi = 96.0;
private static double deviceDpi;
public static double DeviceDpi {
get {
if (deviceDpi == 0.0) {
try {
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) {
deviceDpi = g.DpiX;
}
} catch { }
if (deviceDpi == 0.0)
deviceDpi = LogicalDpi;
}
return deviceDpi;
}
}
private static double logicalToDeviceUnitsScalingFactor;
public static double LogicalToDeviceUnitsScalingFactor {
get {
if (logicalToDeviceUnitsScalingFactor == 0.0) {
logicalToDeviceUnitsScalingFactor = DeviceDpi / LogicalDpi;
}
return logicalToDeviceUnitsScalingFactor;
}
}
public static int LogicalToDeviceUnits(int value) {
return (int)Math.Round(LogicalToDeviceUnitsScalingFactor * (double)value);
}
public static Size LogicalToDeviceUnits(Size logicalSize) {
return new Size(LogicalToDeviceUnits(logicalSize.Width),
LogicalToDeviceUnits(logicalSize.Height));
}
}
}
| 27.163636 | 80 | 0.651941 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Cereal-Killa/openhardwaremonitor | OpenHardwareMonitor/GUI/DpiHelper.cs | 1,497 | C# |
#pragma checksum "C:\Users\Deivide\Documents\CursoC#\Lanches\Views\Shared\_Carousel.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1b7b3d074225cef7c45836a06629500a0dc90d04"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__Carousel), @"mvc.1.0.view", @"/Views/Shared/_Carousel.cshtml")]
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;
#nullable restore
#line 1 "C:\Users\Deivide\Documents\CursoC#\Lanches\Views\_ViewImports.cshtml"
using Lanches.ViewModels;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\Deivide\Documents\CursoC#\Lanches\Views\_ViewImports.cshtml"
using Lanches;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\Deivide\Documents\CursoC#\Lanches\Views\_ViewImports.cshtml"
using Lanches.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"1b7b3d074225cef7c45836a06629500a0dc90d04", @"/Views/Shared/_Carousel.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"97fa3ea970f1c9af8d6c97aa0c31f5cb6f8c356b", @"/Views/_ViewImports.cshtml")]
public class Views_Shared__Carousel : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/images/carousel11.jpg"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("d-block w-100"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("alt", new global::Microsoft.AspNetCore.Html.HtmlString("Lanche"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/images/carousel12.jpg"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/images/carousel13.jpg"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/images/carousel14.jpg"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral(@"
<div id=""carouselLanches"" class=""carousel slide marginTop1"" data-ride=""carousel"">
<ol class=""carousel-indicators"">
<li data-target=""#carouselLanches"" data-slide-to=""0"" class=""active""></li>
<li data-target=""#carouselLanches"" data-slide-to=""1""></li>
<li data-target=""#carouselLanches"" data-slide-to=""2""></li>
<li data-target=""#carouselLanches"" data-slide-to=""3""></li>
</ol>
<div class=""carousel-inner"">
<div class=""carousel-item active"">
");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "1b7b3d074225cef7c45836a06629500a0dc90d045933", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"carousel-item\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "1b7b3d074225cef7c45836a06629500a0dc90d047201", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"carousel-item\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "1b7b3d074225cef7c45836a06629500a0dc90d048469", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"carousel-item\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "1b7b3d074225cef7c45836a06629500a0dc90d049737", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(@"
</div>
</div>
<a class=""left carousel-control"" href=""#carouselLanches"" data-slide=""prev"">
<span class=""glyphicon glyphicon-chevron-left""></span>
</a>
<a class=""right carousel-control"" href=""#carouselLanches"" data-slide=""next"">
<span class=""glyphicon glyphicon-chevron-right""></span>
</a>
</div>
");
}
#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<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 71.005882 | 359 | 0.743186 | [
"MIT"
] | DeivideSilva/Asp.NetCore | Lanches/obj/Debug/netcoreapp3.1/Razor/Views/Shared/_Carousel.cshtml.g.cs | 12,071 | C# |
#if UNITY_EDITOR || RUNTIME_CSG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace Sabresaurus.SabreCSG
{
/// <summary>
/// A multi-purpose popup window used by the 2D Shape Editor.
/// </summary>
/// <seealso cref="UnityEditor.PopupWindowContent"/>
public class ShapeEditorWindowPopup : PopupWindowContent
{
public enum PopupMode
{
BezierDetailLevel,
GlobalPivotPosition,
CreatePolygon,
RevolveShape,
ExtrudeShape,
ExtrudePoint,
ExtrudeBevel,
}
private PopupMode popupMode;
public int bezierDetailLevel_Detail = 3;
public float extrudeDepth = 1.0f;
public float extrudeClipDepth = 0.5f;
public Vector2 extrudeScale = Vector2.one;
public int revolve360 = 8;
public int revolveSteps = 4;
public bool revolveSpiralSloped = false;
public Vector2Int GlobalPivotPosition_Position;
public bool convexBrushes = true;
private Action<ShapeEditorWindowPopup> onApply;
public ShapeEditorWindowPopup(PopupMode popupMode, ShapeEditor.Project project, Action<ShapeEditorWindowPopup> onApply) : base()
{
this.popupMode = popupMode;
// read the extrude settings from the project.
extrudeDepth = project.extrudeDepth;
extrudeClipDepth = project.extrudeClipDepth;
extrudeScale = project.extrudeScale;
revolve360 = project.revolve360;
revolveSteps = project.revolveSteps;
revolveSpiralSloped = project.revolveSpiralSloped;
convexBrushes = project.convexBrushes;
GlobalPivotPosition_Position = project.globalPivot.position;
this.onApply = (self) =>
{
// store the extrude settings in the project.
switch (popupMode)
{
case PopupMode.CreatePolygon:
project.extrudeScale = extrudeScale;
project.convexBrushes = convexBrushes;
break;
case PopupMode.RevolveShape:
project.extrudeScale = extrudeScale;
project.convexBrushes = convexBrushes;
project.revolve360 = revolve360;
project.revolveSteps = revolveSteps;
project.revolveSpiralSloped = revolveSpiralSloped;
break;
case PopupMode.ExtrudeShape:
project.extrudeScale = extrudeScale;
project.convexBrushes = convexBrushes;
project.extrudeDepth = extrudeDepth;
break;
case PopupMode.ExtrudePoint:
project.extrudeScale = extrudeScale;
project.convexBrushes = convexBrushes;
project.extrudeDepth = extrudeDepth;
break;
case PopupMode.ExtrudeBevel:
project.extrudeScale = extrudeScale;
project.convexBrushes = convexBrushes;
project.extrudeDepth = extrudeDepth;
project.extrudeClipDepth = extrudeClipDepth;
break;
}
onApply(self);
editorWindow.Close();
EditorWindow.FocusWindowIfItsOpen<ShapeEditor.ShapeEditorWindow>();
};
}
public override Vector2 GetWindowSize()
{
// + 18 for every element
switch (popupMode)
{
case PopupMode.BezierDetailLevel:
return new Vector2(205, 140);
case PopupMode.GlobalPivotPosition:
return new Vector2(300, 68);
case PopupMode.CreatePolygon:
return new Vector2(300, 50 + 36);
case PopupMode.RevolveShape:
return new Vector2(300, 104 + 36);
case PopupMode.ExtrudeShape:
return new Vector2(300, 68 + 36);
case PopupMode.ExtrudePoint:
return new Vector2(300, 68 + 36);
case PopupMode.ExtrudeBevel:
return new Vector2(300, 86 + 36);
default:
return new Vector2(300, 150);
}
}
public override void OnGUI(Rect rect)
{
bool hasScale = true;
bool hasConvexBrushes = true;
string accept = "";
switch (popupMode)
{
case PopupMode.BezierDetailLevel:
GUILayout.Label("Bezier Detail Level", EditorStyles.boldLabel);
hasScale = false;
hasConvexBrushes = false;
accept = "Apply";
GUILayout.BeginHorizontal(EditorStyles.toolbar);
if (GUILayout.Button("1", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 1; onApply(this); }
if (GUILayout.Button("2", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 2; onApply(this); }
if (GUILayout.Button("3", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 3; onApply(this); }
if (GUILayout.Button("4", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 4; onApply(this); }
if (GUILayout.Button("5", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 5; onApply(this); }
if (GUILayout.Button("6", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 6; onApply(this); }
if (GUILayout.Button("7", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 7; onApply(this); }
if (GUILayout.Button("8", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 8; onApply(this); }
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal(EditorStyles.toolbar);
if (GUILayout.Button("9", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 9; onApply(this); }
if (GUILayout.Button("10", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 10; onApply(this); }
if (GUILayout.Button("11", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 11; onApply(this); }
if (GUILayout.Button("12", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 12; onApply(this); }
if (GUILayout.Button("13", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 13; onApply(this); }
if (GUILayout.Button("14", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 14; onApply(this); }
if (GUILayout.Button("15", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 15; onApply(this); }
if (GUILayout.Button("16", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 16; onApply(this); }
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal(EditorStyles.toolbar);
if (GUILayout.Button("17", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 17; onApply(this); }
if (GUILayout.Button("18", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 18; onApply(this); }
if (GUILayout.Button("19", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 19; onApply(this); }
if (GUILayout.Button("20", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 20; onApply(this); }
if (GUILayout.Button("21", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 21; onApply(this); }
if (GUILayout.Button("22", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 22; onApply(this); }
if (GUILayout.Button("23", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 23; onApply(this); }
if (GUILayout.Button("24", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 24; onApply(this); }
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal(EditorStyles.toolbar);
if (GUILayout.Button("25", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 25; onApply(this); }
if (GUILayout.Button("26", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 26; onApply(this); }
if (GUILayout.Button("27", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 27; onApply(this); }
if (GUILayout.Button("28", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 28; onApply(this); }
if (GUILayout.Button("29", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 29; onApply(this); }
if (GUILayout.Button("30", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 30; onApply(this); }
if (GUILayout.Button("31", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 31; onApply(this); }
if (GUILayout.Button("32", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 32; onApply(this); }
GUILayout.EndHorizontal();
bezierDetailLevel_Detail = EditorGUILayout.IntField("Detail", bezierDetailLevel_Detail);
if (bezierDetailLevel_Detail < 1) bezierDetailLevel_Detail = 1;
if (bezierDetailLevel_Detail > 999) bezierDetailLevel_Detail = 999;
break;
case PopupMode.GlobalPivotPosition:
GUILayout.Label("Global Pivot Position", EditorStyles.boldLabel);
hasScale = false;
hasConvexBrushes = false;
accept = "Set Position";
#if !UNITY_2017_2_OR_NEWER
EditorGUIUtility.wideMode = true;
GlobalPivotPosition_Position = Vector2Int.FloorToInt(EditorGUILayout.Vector2Field("Position", GlobalPivotPosition_Position));
EditorGUIUtility.wideMode = false;
#else
EditorGUIUtility.wideMode = true;
GlobalPivotPosition_Position = EditorGUILayout.Vector2IntField("Position", GlobalPivotPosition_Position);
EditorGUIUtility.wideMode = false;
#endif
break;
case PopupMode.CreatePolygon:
GUILayout.Label("Create Polygon", EditorStyles.boldLabel);
accept = "Create";
break;
case PopupMode.RevolveShape:
GUILayout.Label("Revolve Shape", EditorStyles.boldLabel);
accept = "Revolve";
revolve360 = EditorGUILayout.IntField("Per 360", revolve360);
if (revolve360 < 3) revolve360 = 3;
revolveSteps = EditorGUILayout.IntField("Steps", revolveSteps);
if (revolveSteps < 1) revolveSteps = 1;
revolveSpiralSloped = EditorGUILayout.Toggle("Sloped Spiral", revolveSpiralSloped);
// steps can't be more than 360.
if (revolveSteps > revolve360) revolveSteps = revolve360;
break;
case PopupMode.ExtrudeShape:
GUILayout.Label("Extrude Shape", EditorStyles.boldLabel);
accept = "Extrude";
extrudeDepth = EditorGUILayout.FloatField("Depth", extrudeDepth);
if (extrudeDepth < 0.01f) extrudeDepth = 0.01f;
break;
case PopupMode.ExtrudePoint:
GUILayout.Label("Extrude Point", EditorStyles.boldLabel);
accept = "Extrude";
extrudeDepth = EditorGUILayout.FloatField("Depth", extrudeDepth);
if (extrudeDepth < 0.01f) extrudeDepth = 0.01f;
break;
case PopupMode.ExtrudeBevel:
GUILayout.Label("Extrude Bevel", EditorStyles.boldLabel);
accept = "Extrude";
extrudeDepth = EditorGUILayout.FloatField("Depth", extrudeDepth);
if (extrudeDepth < 0.01f) extrudeDepth = 0.01f;
extrudeClipDepth = EditorGUILayout.FloatField("Clip Depth", extrudeClipDepth);
if (extrudeClipDepth < 0.01f) extrudeClipDepth = 0.01f;
if (extrudeClipDepth > extrudeDepth) extrudeClipDepth = extrudeDepth;
break;
}
if (hasConvexBrushes)
{
convexBrushes = EditorGUILayout.Toggle("Convex Brushes", convexBrushes);
}
if (hasScale)
{
EditorGUIUtility.wideMode = true;
extrudeScale = EditorGUILayout.Vector2Field("Scale", extrudeScale);
EditorGUIUtility.wideMode = false;
if (extrudeScale.x < 0.01f) extrudeScale.x = 0.01f;
if (extrudeScale.y < 0.01f) extrudeScale.y = 0.01f;
}
if (GUILayout.Button(accept))
{
onApply(this);
}
}
}
}
#endif | 53.825623 | 173 | 0.592661 | [
"MIT"
] | IxxyXR/AndyB-VR-Workshop | Assets/3rdParty/SabreCSG/Scripts/Brushes/CompoundBrushes/Editor/ShapeEditorWindowPopup.cs | 15,127 | 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.Oci.Core.Inputs
{
public sealed class IpsecConnectionTunnelManagementBgpSessionInfoArgs : Pulumi.ResourceArgs
{
/// <summary>
/// the state of the BGP.
/// </summary>
[Input("bgpState")]
public Input<string>? BgpState { get; set; }
/// <summary>
/// If the tunnel's `routing` attribute is set to `BGP` (see [IPSecConnectionTunnel](https://docs.cloud.oracle.com/iaas/api/#/en/iaas/20160918/IPSecConnectionTunnel/)), this ASN is required and used for the tunnel's BGP session. This is the ASN of the network on the CPE end of the BGP session. Can be a 2-byte or 4-byte ASN. Uses "asplain" format.
/// </summary>
[Input("customerBgpAsn")]
public Input<string>? CustomerBgpAsn { get; set; }
/// <summary>
/// The IP address for the CPE end of the inside tunnel interface.
/// </summary>
[Input("customerInterfaceIp")]
public Input<string>? CustomerInterfaceIp { get; set; }
/// <summary>
/// This is the value of the Oracle Bgp ASN in asplain format, as a string. Example: 1587232876 (4 byte ASN) or 12345 (2 byte ASN)
/// </summary>
[Input("oracleBgpAsn")]
public Input<string>? OracleBgpAsn { get; set; }
/// <summary>
/// The IP address for the Oracle end of the inside tunnel interface.
/// </summary>
[Input("oracleInterfaceIp")]
public Input<string>? OracleInterfaceIp { get; set; }
public IpsecConnectionTunnelManagementBgpSessionInfoArgs()
{
}
}
}
| 38.52 | 356 | 0.638629 | [
"ECL-2.0",
"Apache-2.0"
] | EladGabay/pulumi-oci | sdk/dotnet/Core/Inputs/IpsecConnectionTunnelManagementBgpSessionInfoArgs.cs | 1,926 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.ComponentModel;
using SoonLearning.Assessment.Player.Data;
using SoonLearning.Assessment.Data;
using System.Reflection;
namespace SoonLearning.Math_Fast.SYSS300.S1Z0WY4_77
{
public class S1Z0WY4_77DataCreator : DataCreator
{
private static S1Z0WY4_77DataCreator creator;
public static S1Z0WY4_77DataCreator Instance
{
get
{
if (creator == null)
creator = new S1Z0WY4_77DataCreator();
return creator;
}
}
private List<int> questionValueList = new List<int>();
private int currentIndex = 2;
public struct valuesStruct
{
public decimal[] valuesRef; //基准值
public decimal[] values; //所有加数的值
public decimal[] valueList1; //各个加数的值
public decimal[] valueList2; //对应的互补数
public decimal[] errors; //各个加数跟基准数的差
public int[] signs; //正负号标志,0为减号,1为加号,2为×号,3为÷号
public int number; //加数的个数
public decimal answer; //所有加数的和,即答案
public int[] complementPos; //互为补数对的原下标
public int[] complementList1Pos; //互为补数对的原下标
public int[] complementList2Pos; //互为补数对的原下标
public decimal valueStart; //第一个加数
public decimal valueOffset; //等差值
public decimal valueMedian; //中间值
public decimal valueLast; //最后一个加数
public decimal A; //被减数A
public decimal A1; //被减数A除了最高位的其余部分
public decimal B; //减数B
public decimal B1; //减数B除了最高位的其余部分
public int nBitsA; //A的位数n
public valuesStruct(int valueSize)
{
valuesRef = new decimal[valueSize];
values = new decimal[valueSize];
valueList1 = new decimal[valueSize];
valueList2 = new decimal[valueSize];
errors = new decimal[valueSize];
signs = new int[valueSize];
complementPos = new int[valueSize];
complementList1Pos = new int[valueSize];
complementList2Pos = new int[valueSize];
number = 5;
answer = 0;
valueStart = 1;
valueOffset = 1;
valueMedian = 5;
valueLast = 10;
A = A1 = B = B1 = 0;
nBitsA = 2;
}
}
public struct valuesCompare
{
public decimal valueRef; //基准值
public decimal[] valuesGT; //大于基准值
public decimal numGT; //大于基准值的个数
public decimal[] valuesLT; //小于基准值
public decimal numLT; //小于基准值的个数
public decimal[] valuesEQ; //等于基准值
public decimal numEQ; //等于基准值的个数
public valuesCompare(int GTSize, int LTSize, int EQSize)
{
valueRef = 50;
valuesGT = new decimal[GTSize];
valuesLT = new decimal[LTSize];
valuesEQ = new decimal[EQSize];
numGT = 0;
numLT = 0;
numEQ = 0;
}
}
protected override void PrepareSectionInfoCollection()
{
this.exerciseTitle = "首1中0尾异法(四)练习";
this.examTitle = "首1中0尾异法(四)测验";
this.flowDocumentFile = "SoonLearning.Math_Fast.SYSS300.S1Z0WY4_77.S1Z0WY4_77_Document.xaml";
this.sectionInfoCollection.Add(new SectionValueRangeInfo(QuestionType.MultiChoice,
"单选题:",
"(下面每道题都只有一个选项是正确的)",
5,
100,
10000));
this.sectionInfoCollection.Add(new SectionValueRangeInfo(QuestionType.FillInBlank,
"填空题:",
"(在空格中填入符合条件的数)",
5,
100,
10000));
}
protected override void AppendQuestion(SectionBaseInfo info, Section section)
{
switch (info.QuestionType)
{
case QuestionType.MultiChoice:
this.CreateMCQuestion(info, section);
break;
case QuestionType.FillInBlank:
this.CreateFIBQuestion(info, section);
break;
}
}
private void GetRandomValues(SectionBaseInfo info, ref valuesStruct valueABC)
{
int minValue = 10;
int maxValue = 100;
if (info is SectionValueRangeInfo)
{
SectionValueRangeInfo rangeInfo = info as SectionValueRangeInfo;
minValue = decimal.ToInt32(rangeInfo.MinValue);
maxValue = decimal.ToInt32(rangeInfo.MaxValue);
}
//if (minValue < 1000)
{
minValue = 100;
}
//if (maxValue < 10000)
{
maxValue = 10000;
}
Random rand = new Random((int)DateTime.Now.Ticks);
valueABC.number = 2;
valueABC.answer = 0;
decimal A, B;
int bitNum = rand.Next(3, 5); //一百零几或一千零几
int a = rand.Next(1, 10);
int b = rand.Next(1, 10);
if (bitNum == 3) //一百零几
{
A = 100 + a;
B = 100 + b;
}
else
{
A = 1000 + a;
B = 1000 + b;
}
//int posRand = rand.Next(0, 2);
//if (posRand == 0)
//{
// A = 10 * a + b;
// B = 10 * c + d;
//}
//else
//{
// B = 10 * a + b;
// A = 10 * c + d;
//}
valueABC.values[0] = A;
valueABC.values[1] = B;
valueABC.answer = A * B;
}
private String SolveSteps(valuesStruct valueMC)
{
string calSteps = "";
//题干
calSteps += valueMC.values[0].ToString();
calSteps += "×";
calSteps += valueMC.values[1].ToString();
//解题步骤
int A = decimal.ToInt32(valueMC.values[0]);
int B = decimal.ToInt32(valueMC.values[1]);
//if (valueMC.values[0] < valueMC.values[1])
//{
// A = decimal.ToInt32(valueMC.values[1]);
// B = decimal.ToInt32(valueMC.values[0]);
//}
int a = A % 10;
int b = B % 10;
decimal answer = 0;
int baseNum = 100;
if (A >= 1000 && B >= 1000)
{
baseNum = 1000;
}
//第一步
calSteps += "=被数加乘个(";
calSteps += A.ToString();
calSteps += "+";
calSteps += b.ToString();
calSteps += ")×";
calSteps += baseNum.ToString();
//calSteps += a.ToString();
//calSteps += "×";
//calSteps += b.ToString();
//第二步
int Ba = baseNum * (A + b);
int ab = a * b;
calSteps += "加上末位与末位的乘积";
calSteps += a.ToString();
calSteps += "×";
calSteps += b.ToString();
//第三步
//calSteps += "=";
//calSteps += a10.ToString();
//calSteps += "×";
//calSteps += a10.ToString();
//calSteps += "-";
//calSteps += b.ToString();
//calSteps += "×";
//calSteps += b.ToString();
//calSteps += "-";
//calSteps += A.ToString();
//int a_a_100 = a10 * a10;
//calSteps += "=";
//calSteps += a_a_100.ToString();
//calSteps += "-";
//calSteps += b_b.ToString();
//calSteps += "-";
//calSteps += A.ToString();
// int a_b_2 = a_a_100 - b_b;
//第四步
int tmp0 = 0;
int tmp1 = Ba;
int tmp2 = ab;
//
answer = tmp0 + tmp1 + tmp2;
if (answer != valueMC.answer)
{
calSteps += "Error!";
}
calSteps += "=";
calSteps += valueMC.answer.ToString();
calSteps += ",是正确答案。";
return calSteps;
}
private String QuestionText(valuesStruct valueMC)
{
string questionText = "";
questionText += valueMC.values[0].ToString();
questionText += "×";
questionText += valueMC.values[1].ToString();
questionText += "=";
return questionText;
}
private MCQuestion CreateMCQuestion(SectionBaseInfo info, Section section)
{
valuesStruct valueMC = new valuesStruct(20); //题干展示的值
//随即获得数值
this.GetRandomValues(info, ref valueMC);
questionValueList.Add((decimal.ToInt32(valueMC.values[0])));
//生产题干文本
string questionText = QuestionText(valueMC);
MCQuestion mcQuestion = ObjectCreator.CreateMCQuestion((content) =>
{
content.Content = questionText;
content.ContentType = ContentType.Text;
return;
},
() =>
{
List<QuestionOption> optionList = new List<QuestionOption>();
int valueLst = (decimal.ToInt32(valueMC.answer)) - 30, valueMst = (decimal.ToInt32(valueMC.answer)) + 30;
if (valueLst - 30 <= 1)
{
valueLst = 1;
}
foreach (QuestionOption option in ObjectCreator.CreateDecimalOptions(
4, valueLst, valueMst, false, (c => (c == decimal.ToInt32(valueMC.answer))), decimal.ToInt32(valueMC.answer)))
optionList.Add(option);
return optionList;
}
);
StringBuilder strBuilder = new StringBuilder();
//解题步骤
string Steps = SolveSteps(valueMC);
strBuilder.AppendLine(Steps);
mcQuestion.Solution.Content = strBuilder.ToString();
section.QuestionCollection.Add(mcQuestion);
return mcQuestion;
}
private void CreateFIBQuestion(SectionBaseInfo info, Section section)
{
valuesStruct valueMC = new valuesStruct(20); //题干展示的值
//随即获得数值
this.GetRandomValues(info, ref valueMC);
//生产题干文本
string questionText = QuestionText(valueMC);
FIBQuestion fibQuestion = new FIBQuestion();
fibQuestion.Content.Content = questionText;
fibQuestion.Content.ContentType = ContentType.Text;
section.QuestionCollection.Add(fibQuestion);
QuestionBlank blank = new QuestionBlank();
QuestionContent blankContent = new QuestionContent();
blankContent.Content = valueMC.answer.ToString();
blankContent.ContentType = ContentType.Text;
blank.ReferenceAnswerList.Add(blankContent);
fibQuestion.QuestionBlankCollection.Add(blank);
fibQuestion.Content.Content += blank.PlaceHolder;
StringBuilder strBuilder = new StringBuilder();
//解题步骤
string Steps = SolveSteps(valueMC);
strBuilder.AppendLine(Steps);
fibQuestion.Solution.Content = strBuilder.ToString();
}
private string CreateSolution(int divValue)
{
if (divValue == 2)
{
return "";
}
return string.Empty;
}
public S1Z0WY4_77DataCreator()
{
}
}
}
| 30.805627 | 138 | 0.483188 | [
"MIT"
] | LigangSun/AppCenter | source/Apps/Math_Fast_SYSS300/71_80/SoonLearning.Math_Fast.SYSS300.S1Z0WY4_77/S1Z0WY4_77_DataCreator.cs | 12,736 | 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.Linq.Expressions;
using JetBrains.Annotations;
using Remotion.Linq;
using Remotion.Linq.Clauses;
using Remotion.Linq.Clauses.ResultOperators;
using Remotion.Linq.Clauses.StreamedData;
namespace Microsoft.EntityFrameworkCore.Query.ResultOperators.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class TrackingResultOperator : SequenceTypePreservingResultOperatorBase, IQueryAnnotation
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public TrackingResultOperator(bool tracking)
{
IsTracking = tracking;
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual IQuerySource QuerySource { get; [NotNull] set; }
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual QueryModel QueryModel { get; [NotNull] set; }
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual bool IsTracking { get; }
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override string ToString() => IsTracking ? "AsTracking()" : "AsNoTracking()";
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override ResultOperatorBase Clone([NotNull] CloneContext cloneContext)
=> new TrackingResultOperator(IsTracking);
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override void TransformExpressions([NotNull] Func<Expression, Expression> transformation)
{
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override StreamedSequence ExecuteInMemory<T>([NotNull] StreamedSequence input) => input;
}
}
| 47.226667 | 111 | 0.659514 | [
"Apache-2.0"
] | joshcomley/EntityFramework-archive | src/Microsoft.EntityFrameworkCore/Query/ResultOperators/Internal/TrackingResultOperator.cs | 3,542 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Guppy.Extensions.System
{
public static class SingleExtensions
{
/// <summary>
/// Save division that will return the <paramref name="fallback"/>
/// value if <paramref name="denominator"/> is equal to 0.
/// If <paramref name="fallback"/> is null, then <paramref name="numerator"/>
/// will be returned instead.
/// </summary>
/// <param name="numerator"></param>
/// <param name="denominator"></param>
/// <param name="fallback"></param>
/// <returns></returns>
static public Single SafeDivision(this Single numerator, Single denominator, Single? fallback = null)
{
return (denominator == 0) ? numerator : numerator / denominator;
}
}
}
| 33.84 | 109 | 0.602837 | [
"MIT"
] | rettoph/Guppy | src/Guppy/Extensions/System/SingleExtensions.cs | 848 | C# |
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
namespace PM_Studio
{
public class SecurityManger
{
/// <summary>
/// Combines byte arrays into one array
/// </summary>
/// <param name="byteArrays">the arrays to be combined</param>
/// <returns></returns>
public byte[] CombineByteArrays(params byte[][] byteArrays)
{
//Create an empty List of bytes to store the bytes of all arays
List<byte> CombinedBytes = new List<byte>();
//Loop on each byte array
foreach(byte[] array in byteArrays)
{
//Loop on each byte in that array
foreach(byte bytenumber in array)
{
//Add that byte to the bytes list
CombinedBytes.Add(bytenumber);
}
}
//return the List as a byte array
return CombinedBytes.ToArray();
}
/// <summary>
/// Splits a given byte array into subarrays by using given Split numbers
/// </summary>
/// <param name="array">the array which will be splitted into subarrays</param>
/// <param name="SplitNumbers">The Indexes which we will create a new subarray from them
/// for example if the given array was { 255, 64, 25, 79, 18, 10, 90, 121, 34, 56, 97, 56, 76 },
/// and the given split numbers were 3,4,3
/// the first sub array generated will contain the first 3 bytes in the array,
/// and the second subarray will contain the next 4 numbers
/// and the third subarray will contain the next 3 numbers, and so on.</param>
/// <returns></returns>
public List<byte[]> SplitByteArray(byte[] array, params int[] SplitNumbers)
{
//Create a CurrentArrayIndex variable which holds the current index of the array
int CurrentArrayIndex = 0;
//Create an empty List which will hold the resulted subarrays
List<byte[]> byteArrays = new List<byte[]>();
//Loop on each SplitNumber given
foreach(int SplitNumber in SplitNumbers)
{
//Create an array which will hold a subarray of the given array
byte[] subArray = new byte[SplitNumber];
//Loop inside the main array
for (int i = 0; i < SplitNumber; i++)
{
//Add the items which corrspondes to the current index in the array to the subarray
subArray[i] = array[CurrentArrayIndex];
//Increase the CurrentArrayIndex variable by 1 to corrospond to the next value in the array
CurrentArrayIndex++;
}
//Add the resulted subarray into the ByteArrayList
byteArrays.Add(subArray);
}
//Return the Resulted ByteArrayList
return byteArrays;
}
public byte[] GenerateRandomNumber(int length)
{
//Create a RNGCryptoServiceProvider to generate the Random Number
using (RNGCryptoServiceProvider randomNumberGenerator = new RNGCryptoServiceProvider())
{
//Create an empty byte array to store the RandomNumber
byte[] randomNumber = new byte[length];
//Fill that array with some random values and return it
randomNumberGenerator.GetBytes(randomNumber);
return randomNumber;
}
}
/// <summary>
/// Encrypts a file in a given path using the AES-GCM encrption
/// </summary>
/// <param name="filePath">The file to be encrypted</param>
/// <returns></returns>
public (byte[] cipherText, byte[] tag) EncryptFile(string filePath)
{
//Generate a 32 byte array to create the encryption key
byte[] Key = GenerateRandomNumber(32);
//Generate a 12 byte array nonce that will to create the IV of the encryption
byte[] nonce = GenerateRandomNumber(12);
//Generate a 16 byte array to recive the generated authentication tag
byte[] tag = new byte[16];
//Get the length of the data inside the required file as a byte array and create an empty byte array with that length
//(as the encrypted data will have the same bytes length as the original data), this array will store the encrypted text
byte[] chipherText = new byte[File.ReadAllBytes(filePath).Length];
//Intialize the AES GCM encryption class and encrypt the data in the file and store it in the cipherText variable
AesGcm aes = new AesGcm(Key);
aes.Encrypt(nonce, File.ReadAllBytes(filePath), chipherText, tag);
//Combine the Key, nonce, tag, and the cipherText in one byte array(to make restoring them for the decryption easier)
//and store that array as a Base64 string in the required file
File.WriteAllText(filePath, Convert.ToBase64String(CombineByteArrays(Key, nonce, tag, chipherText)));
return (chipherText, tag);
}
/// <summary>
/// Decrypts a encrypted with AES-GCM in a given path
/// </summary>
/// <param name="filePath">the file to be decrypted</param>
public void DecryptFile(string filePath)
{
//Convert the file text into a byte array which contains all the data of the previous encryption
byte[] FullData = Convert.FromBase64String(File.ReadAllText(filePath));
//Create a List of byte arrays which holds each byte array stored in the encryption
//The first 32 bytes is the key, the next 12 bytes is the nonce, the next 16 bytes is the tag, and the remaining bytes are the original content
//(the byte array length - 60 is simply the whole byte array without the length of the first 3 arrays)
List<byte[]> DataList = SplitByteArray(FullData, 32, 12, 16, FullData.Length - 60);
//Get the Key, nonce, tag, and cipherText from the DataList
byte[] Key = DataList[0];
byte[] nonce = DataList[1];
byte[] tag = DataList[2];
byte[] cipherText = DataList[3];
//Create an Empty byte array which will store the resulted decrypted text with the same length of the encrypted one
byte[] PlainText = new byte[cipherText.Length];
//Intialize the AES GCM encryption class and decrypt the data in the file and store it in the PlainText variable
AesGcm aes = new AesGcm(Key);
aes.Decrypt(nonce, cipherText, tag, PlainText);
//Store the resulted decrypted array in the file
File.WriteAllBytes(filePath, PlainText);
}
}
}
| 47.238411 | 156 | 0.58727 | [
"MIT"
] | ZyadHamed/PM_Studio | PM_Studio/PM_Studio_Core/DataAccessLayer/SecurityManger.cs | 7,135 | C# |
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
using ClearCanvas.Common;
using ClearCanvas.Dicom;
using ClearCanvas.Dicom.Utilities.Command;
using ClearCanvas.Enterprise.Core;
using ClearCanvas.ImageServer.Common.Command;
using ClearCanvas.ImageServer.Model;
using ClearCanvas.ImageServer.Model.EntityBrokers;
namespace ClearCanvas.ImageServer.Core
{
/// <summary>
/// Update the <see cref="StudyStorage"/> and <see cref="FilesystemStudyStorage"/> tables according to
/// a new Transfersyntax the Study is encoded as.
/// </summary>
/// <remarks>
/// <para>
/// This method checks the status and transfer syntax set in the current <see cref="StudyStorageLocation"/>
/// instance passed to the constructor and compares it to the <see cref="DicomFile"/> passed to the constructor.
/// If they vary, it will then update the database and update the structure with the new values. If they're
/// the same, a database update is bypassed.
/// </para>
/// <para>
/// For efficiency sake, this assumes that the same <see cref="StudyStorageLocation"/> instance is used for
/// consecutive calls to this <see cref="ServerDatabaseCommand"/> object.
/// </para>
/// </remarks>
public class UpdateStudyStatusCommand : ServerDatabaseCommand
{
private readonly StudyStorageLocation _location;
private readonly DicomFile _file;
public UpdateStudyStatusCommand(StudyStorageLocation location, DicomFile file)
: base("Update StudyStorage and FilesystemStudyStorage")
{
_location = location;
_file = file;
}
protected override void OnExecute(CommandProcessor theProcessor, IUpdateContext updateContext)
{
// Check if the File is the same syntax as the
TransferSyntax fileSyntax = _file.TransferSyntax;
TransferSyntax dbSyntax = TransferSyntax.GetTransferSyntax(_location.TransferSyntaxUid);
// Check if the syntaxes match the location
if ((!fileSyntax.Encapsulated && !dbSyntax.Encapsulated)
|| (fileSyntax.LosslessCompressed && dbSyntax.LosslessCompressed)
|| (fileSyntax.LossyCompressed && dbSyntax.LossyCompressed))
{
// no changes necessary, just return;
return;
}
// Select the Server Transfer Syntax
var syntaxCriteria = new ServerTransferSyntaxSelectCriteria();
var syntaxBroker = updateContext.GetBroker<IServerTransferSyntaxEntityBroker>();
syntaxCriteria.Uid.EqualTo(fileSyntax.UidString);
ServerTransferSyntax serverSyntax = syntaxBroker.FindOne(syntaxCriteria);
if (serverSyntax == null)
{
Platform.Log(LogLevel.Error, "Unable to load ServerTransferSyntax for {0}. Unable to update study status.", fileSyntax.Name);
return;
}
// Get the FilesystemStudyStorage update broker ready
var filesystemStudyStorageEntityBroker = updateContext.GetBroker<IFilesystemStudyStorageEntityBroker>();
var filesystemStorageUpdate = new FilesystemStudyStorageUpdateColumns();
var filesystemStorageCritiera = new FilesystemStudyStorageSelectCriteria();
filesystemStorageUpdate.ServerTransferSyntaxKey = serverSyntax.Key;
filesystemStorageCritiera.StudyStorageKey.EqualTo(_location.Key);
// Get the StudyStorage update broker ready
var studyStorageBroker =
updateContext.GetBroker<IStudyStorageEntityBroker>();
var studyStorageUpdate = new StudyStorageUpdateColumns();
StudyStatusEnum statusEnum = _location.StudyStatusEnum;
if (fileSyntax.LossyCompressed)
studyStorageUpdate.StudyStatusEnum = statusEnum = StudyStatusEnum.OnlineLossy;
else if (fileSyntax.LosslessCompressed)
studyStorageUpdate.StudyStatusEnum = statusEnum = StudyStatusEnum.OnlineLossless;
studyStorageUpdate.LastAccessedTime = Platform.Time;
if (!filesystemStudyStorageEntityBroker.Update(filesystemStorageCritiera, filesystemStorageUpdate))
{
Platform.Log(LogLevel.Error, "Unable to update FilesystemQueue row: Study {0}, Server Entity {1}",
_location.StudyInstanceUid, _location.ServerPartitionKey);
}
else if (!studyStorageBroker.Update(_location.GetKey(), studyStorageUpdate))
{
Platform.Log(LogLevel.Error, "Unable to update StudyStorage row: Study {0}, Server Entity {1}",
_location.StudyInstanceUid, _location.ServerPartitionKey);
}
else
{
// Update the location, so the next time we come in here, we don't try and update the database
// for another sop in the study.
_location.StudyStatusEnum = statusEnum;
_location.TransferSyntaxUid = fileSyntax.UidString;
_location.ServerTransferSyntaxKey = serverSyntax.Key;
}
}
}
}
| 40.789916 | 131 | 0.743923 | [
"Apache-2.0"
] | SNBnani/Xian | ImageServer/Core/UpdateStudyStatusCommand.cs | 4,854 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
namespace Acr.ComponentModel
{
public class NotifyPropertyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
=> this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected virtual void OnPropertyChanged<T>(Expression<Func<T>> expression)
{
var member = expression.Body as MemberExpression;
if (member == null)
throw new ArgumentException("Expression is not a MemberExpression");
this.OnPropertyChanged(member.Member.Name);
}
protected virtual bool SetProperty<T>(ref T property, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(property, value))
return false;
property = value;
this.OnPropertyChanged(propertyName);
return true;
}
}
}
| 30.125 | 117 | 0.673029 | [
"MIT"
] | aritchie/extensions | Acr/ComponentModel/NotifyPropertyChanged.cs | 1,207 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace XRTK.Interfaces.TeleportSystem
{
public interface IMixedRealityTeleportHotSpot
{
/// <summary>
/// The position the teleport will end at.
/// </summary>
Vector3 Position { get; }
/// <summary>
/// The normal of the teleport raycast.
/// </summary>
Vector3 Normal { get; }
/// <summary>
/// Is the teleport target active?
/// </summary>
bool IsActive { get; }
/// <summary>
/// Should the target orientation be overridden?
/// </summary>
bool OverrideTargetOrientation { get; }
/// <summary>
/// Should the destination orientation be overridden?
/// Useful when you want to orient the user in a specific direction when they teleport to this position.
/// <remarks>
/// Override orientation is the transform forward of the GameObject this component is attached to.
/// </remarks>
/// </summary>
float TargetOrientation { get; }
/// <summary>
/// Returns the <see cref="GameObject"/> reference for this teleport target.
/// </summary>
GameObject GameObjectReference { get; }
}
} | 31.840909 | 112 | 0.59743 | [
"MIT"
] | hridpath/XRTK-Core | XRTK-Core/Assets/XRTK/Interfaces/TeleportSystem/IMixedRealityTeleportHotSpot.cs | 1,403 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.fund.jointaccount.fund.btoc.transfer
/// </summary>
public class AlipayFundJointaccountFundBtocTransferRequest : IAopRequest<AlipayFundJointaccountFundBtocTransferResponse>
{
/// <summary>
/// 单笔转账
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.fund.jointaccount.fund.btoc.transfer";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if(this.udfParams == null)
{
this.udfParams = new Dictionary<string, string>();
}
this.udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
if(udfParams != null)
{
parameters.AddAll(this.udfParams);
}
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 26.080645 | 125 | 0.568336 | [
"Apache-2.0"
] | alipay/alipay-sdk-net | AlipaySDKNet.Standard/Request/AlipayFundJointaccountFundBtocTransferRequest.cs | 3,242 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace v0622
{
static class Program
{
/// <summary>
/// アプリケーションのメイン エントリ ポイントです。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 21.217391 | 65 | 0.602459 | [
"MIT"
] | gameispien/v0622 | v0622/Program.cs | 536 | C# |
using System;
using Rolang.Expressions;
using Rolang.Statements;
namespace Rolang.Functions
{
public class PrintFunction : IStatement
{
private readonly Parser _parser;
public PrintFunction(Parser parser)
{
_parser = parser;
}
public void Execute()
{
Console.WriteLine(new VariableExpression(_parser, "$1", 0).Compute().ToString());
}
}
} | 20.666667 | 93 | 0.603687 | [
"MIT"
] | RolanUnix/Rolang | src/Functions/PrintFunction.cs | 436 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.