content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Globalization;
using InterFAX.Api.Dtos;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace InterFAX.Api
{
/// <summary>
/// Options which can be provided when submitting a fax.
/// </summary>
public class SendOptions : IOptions
{
/// <summary>
/// A single fax number, e.g: +1-212-3456789.
/// </summary>
public string FaxNumber { get; set; }
/// <summary>
/// A name or other reference. The entered string will appear:
/// (1) for reference in the outbound queue;
/// (2) in the outbound fax header, if headers are configured; and
/// (3) in subsequent queries of the fax object.
/// </summary>
public string Contact { get; set; }
/// <summary>
/// Time to schedule the transmission.
/// </summary>
public DateTime? PostponeTime { get; set; }
/// <summary>
/// Number of transmission attempts to perform, in case of fax transmission failure.
/// </summary>
public int? RetriesToPerform { get; set; }
/// <summary>
/// Sender CSID. (defaults is taken from control panel settings)
/// </summary>
public string Csid { get; set; }
/// <summary>
/// The fax header text to insert at the top of the page.
/// Enter a string template to send a fax with a dynamically-populated header.
/// e.g. "To: {To} From: {From} Pages: {TotalPages}"
/// </summary>
public string PageHeader { get; set; }
/// <summary>
/// Provide your internal ID to a document.
/// This parameter can be obtained by status query, but is not included in the transmitted fax message.
/// </summary>
public string Reference { get; set; }
/// <summary>
/// E-mail address to which feedback messages will be sent.
/// </summary>
public string ReplyAddress { get; set; }
/// <summary>
/// a4, letter, legal, or b4.
/// </summary>
public PageSize? PageSize { get; set; }
/// <summary>
/// Scaling enlarges or reduces an image file to the given page size.
/// </summary>
public bool? ShouldScale { get; set; }
/// <summary>
/// portrait or landscape.
/// </summary>
public PageOrientation? PageOrientation { get; set; }
/// <summary>
/// standard or fine. Documents rendered as fine may be more readable but take longer to transmit (and may therefore be more costly).
/// </summary>
public PageResolution? PageResolution { get; set; }
/// <summary>
/// greyscale or bw.
/// Determines the rendering mode.
/// bw is recommended for textual, black & white documents, while greyscale is better for greyscale text and for images.
/// </summary>
public PageRendering? PageRendering { get; set; }
public Dictionary<string, string> ToDictionary()
{
var options = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(FaxNumber)) options.Add("faxNumber", FaxNumber);
if (!string.IsNullOrEmpty(Contact)) options.Add("contact", Contact);
if (PostponeTime.HasValue) options.Add("postponeTime", PostponeTime.Value.ToString("s") + "Z");
if (RetriesToPerform != null) options.Add("retriesToPerform", RetriesToPerform.ToString());
if (!string.IsNullOrEmpty(Csid)) options.Add("csid", Csid);
if (!string.IsNullOrEmpty(PageHeader)) options.Add("pageHeader", PageHeader);
if (!string.IsNullOrEmpty(Reference)) options.Add("reference", Reference);
if (!string.IsNullOrEmpty(ReplyAddress)) options.Add("replyAddress", ReplyAddress);
if (PageSize.HasValue) options.Add("pageSize", PageSize.ToCamelCase());
if (ShouldScale.HasValue) options.Add("fitToPage", ShouldScale.Value? "scale" : "noscale");
if (PageOrientation.HasValue) options.Add("pageOrientation", PageOrientation.ToCamelCase());
if (PageResolution.HasValue) options.Add("resolution", PageResolution.ToCamelCase());
if (PageRendering.HasValue) options.Add("rendering", PageRendering.ToCamelCase());
return options;
}
}
} | 41.448598 | 141 | 0.602931 | [
"MIT"
] | IsiraUdaththa/interfax-dotnet | InterFAX.Api/SendOptions.cs | 4,435 | 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.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.TestCommon;
using Moq;
namespace Microsoft.Web.Helpers.Test
{
public class VideoTest
{
private VirtualPathUtilityWrapper _pathUtility = new VirtualPathUtilityWrapper();
[Fact]
public void FlashCannotOverrideHtmlAttributes()
{
Assert.ThrowsArgument(
() =>
{
Video.Flash(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.swf",
htmlAttributes: new { cLASSid = "CanNotOverride" }
);
},
"htmlAttributes",
"Property \"cLASSid\" cannot be set through this argument."
);
}
[Fact]
public void FlashDefaults()
{
string html = Video
.Flash(GetContext(), _pathUtility, "http://foo.bar.com/foo.swf")
.ToString()
.Replace("\r\n", "");
Assert.StartsWith(
"<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" "
+ "codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab\" type=\"application/x-oleobject\" >",
html
);
Assert.Contains("<param name=\"movie\" value=\"http://foo.bar.com/foo.swf\" />", html);
Assert.Contains(
"<embed src=\"http://foo.bar.com/foo.swf\" type=\"application/x-shockwave-flash\" />",
html
);
Assert.EndsWith("</object>", html);
}
[Fact]
public void FlashThrowsWhenPathIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(
() =>
{
Video.Flash(GetContext(), _pathUtility, String.Empty);
},
"path"
);
}
[Fact]
public void FlashThrowsWhenPathIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(
() =>
{
Video.Flash(GetContext(), _pathUtility, null);
},
"path"
);
}
[Fact]
public void FlashWithExposedOptions()
{
string html = Video
.Flash(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.swf",
width: "100px",
height: "100px",
play: false,
loop: false,
menu: false,
backgroundColor: "#000",
quality: "Q",
scale: "S",
windowMode: "WM",
baseUrl: "http://foo.bar.com/",
version: "1.0.0.0",
htmlAttributes: new { id = "fl" },
embedName: "efl"
)
.ToString()
.Replace("\r\n", "");
Assert.StartsWith(
"<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" "
+ "codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=1,0,0,0\" "
+ "height=\"100px\" id=\"fl\" type=\"application/x-oleobject\" width=\"100px\" >",
html
);
Assert.Contains("<param name=\"play\" value=\"False\" />", html);
Assert.Contains("<param name=\"loop\" value=\"False\" />", html);
Assert.Contains("<param name=\"menu\" value=\"False\" />", html);
Assert.Contains("<param name=\"bgColor\" value=\"#000\" />", html);
Assert.Contains("<param name=\"quality\" value=\"Q\" />", html);
Assert.Contains("<param name=\"scale\" value=\"S\" />", html);
Assert.Contains("<param name=\"wmode\" value=\"WM\" />", html);
Assert.Contains("<param name=\"base\" value=\"http://foo.bar.com/\" />", html);
var embed = new Regex("<embed.*/>").Match(html);
Assert.True(embed.Success);
Assert.StartsWith(
"<embed src=\"http://foo.bar.com/foo.swf\" width=\"100px\" height=\"100px\" name=\"efl\" type=\"application/x-shockwave-flash\" ",
embed.Value
);
Assert.Contains("play=\"False\"", embed.Value);
Assert.Contains("loop=\"False\"", embed.Value);
Assert.Contains("menu=\"False\"", embed.Value);
Assert.Contains("bgColor=\"#000\"", embed.Value);
Assert.Contains("quality=\"Q\"", embed.Value);
Assert.Contains("scale=\"S\"", embed.Value);
Assert.Contains("wmode=\"WM\"", embed.Value);
Assert.Contains("base=\"http://foo.bar.com/\"", embed.Value);
}
[Fact]
public void FlashWithUnexposedOptions()
{
string html = Video
.Flash(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.swf",
options: new { X = "Y", Z = 123 }
)
.ToString()
.Replace("\r\n", "");
Assert.Contains("<param name=\"X\" value=\"Y\" />", html);
Assert.Contains("<param name=\"Z\" value=\"123\" />", html);
// note - can't guarantee order of optional params:
Assert.True(
html.Contains(
"<embed src=\"http://foo.bar.com/foo.swf\" type=\"application/x-shockwave-flash\" X=\"Y\" Z=\"123\" />"
)
|| html.Contains(
"<embed src=\"http://foo.bar.com/foo.swf\" type=\"application/x-shockwave-flash\" Z=\"123\" X=\"Y\" />"
)
);
}
[Fact]
public void MediaPlayerCannotOverrideHtmlAttributes()
{
Assert.ThrowsArgument(
() =>
{
Video.MediaPlayer(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.wmv",
htmlAttributes: new { cODEbase = "CanNotOverride" }
);
},
"htmlAttributes",
"Property \"cODEbase\" cannot be set through this argument."
);
}
[Fact]
public void MediaPlayerDefaults()
{
string html = Video
.MediaPlayer(GetContext(), _pathUtility, "http://foo.bar.com/foo.wmv")
.ToString()
.Replace("\r\n", "");
Assert.StartsWith(
"<object classid=\"clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6\" >",
html
);
Assert.Contains("<param name=\"URL\" value=\"http://foo.bar.com/foo.wmv\" />", html);
Assert.Contains(
"<embed src=\"http://foo.bar.com/foo.wmv\" type=\"application/x-mplayer2\" />",
html
);
Assert.EndsWith("</object>", html);
}
[Fact]
public void MediaPlayerThrowsWhenPathIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(
() =>
{
Video.MediaPlayer(GetContext(), _pathUtility, String.Empty);
},
"path"
);
}
[Fact]
public void MediaPlayerThrowsWhenPathIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(
() =>
{
Video.MediaPlayer(GetContext(), _pathUtility, null);
},
"path"
);
}
[Fact]
public void MediaPlayerWithExposedOptions()
{
string html = Video
.MediaPlayer(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.wmv",
width: "100px",
height: "100px",
autoStart: false,
playCount: 2,
uiMode: "UIMODE",
stretchToFit: true,
enableContextMenu: false,
mute: true,
volume: 1,
baseUrl: "http://foo.bar.com/",
htmlAttributes: new { id = "mp" },
embedName: "emp"
)
.ToString()
.Replace("\r\n", "");
Assert.StartsWith(
"<object classid=\"clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6\" height=\"100px\" id=\"mp\" width=\"100px\" >",
html
);
Assert.Contains("<param name=\"URL\" value=\"http://foo.bar.com/foo.wmv\" />", html);
Assert.Contains("<param name=\"autoStart\" value=\"False\" />", html);
Assert.Contains("<param name=\"playCount\" value=\"2\" />", html);
Assert.Contains("<param name=\"uiMode\" value=\"UIMODE\" />", html);
Assert.Contains("<param name=\"stretchToFit\" value=\"True\" />", html);
Assert.Contains("<param name=\"enableContextMenu\" value=\"False\" />", html);
Assert.Contains("<param name=\"mute\" value=\"True\" />", html);
Assert.Contains("<param name=\"volume\" value=\"1\" />", html);
Assert.Contains("<param name=\"baseURL\" value=\"http://foo.bar.com/\" />", html);
var embed = new Regex("<embed.*/>").Match(html);
Assert.True(embed.Success);
Assert.StartsWith(
"<embed src=\"http://foo.bar.com/foo.wmv\" width=\"100px\" height=\"100px\" name=\"emp\" type=\"application/x-mplayer2\" ",
embed.Value
);
Assert.Contains("autoStart=\"False\"", embed.Value);
Assert.Contains("playCount=\"2\"", embed.Value);
Assert.Contains("uiMode=\"UIMODE\"", embed.Value);
Assert.Contains("stretchToFit=\"True\"", embed.Value);
Assert.Contains("enableContextMenu=\"False\"", embed.Value);
Assert.Contains("mute=\"True\"", embed.Value);
Assert.Contains("volume=\"1\"", embed.Value);
Assert.Contains("baseURL=\"http://foo.bar.com/\"", embed.Value);
}
[Fact]
public void MediaPlayerWithUnexposedOptions()
{
string html = Video
.MediaPlayer(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.wmv",
options: new { X = "Y", Z = 123 }
)
.ToString()
.Replace("\r\n", "");
Assert.Contains("<param name=\"X\" value=\"Y\" />", html);
Assert.Contains("<param name=\"Z\" value=\"123\" />", html);
Assert.True(
html.Contains(
"<embed src=\"http://foo.bar.com/foo.wmv\" type=\"application/x-mplayer2\" X=\"Y\" Z=\"123\" />"
)
|| html.Contains(
"<embed src=\"http://foo.bar.com/foo.wmv\" type=\"application/x-mplayer2\" Z=\"123\" X=\"Y\" />"
)
);
}
[Fact]
public void SilverlightCannotOverrideHtmlAttributes()
{
Assert.ThrowsArgument(
() =>
{
Video.Silverlight(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.xap",
"100px",
"100px",
htmlAttributes: new { WIDTH = "CanNotOverride" }
);
},
"htmlAttributes",
"Property \"WIDTH\" cannot be set through this argument."
);
}
[Fact]
public void SilverlightDefaults()
{
string html = Video
.Silverlight(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.xap",
"100px",
"100px"
)
.ToString()
.Replace("\r\n", "");
Assert.StartsWith(
"<object data=\"data:application/x-silverlight-2,\" height=\"100px\" type=\"application/x-silverlight-2\" "
+ "width=\"100px\" >",
html
);
Assert.Contains("<param name=\"source\" value=\"http://foo.bar.com/foo.xap\" />", html);
Assert.Contains(
"<a href=\"http://go.microsoft.com/fwlink/?LinkID=149156\" style=\"text-decoration:none\">"
+ "<img src=\"http://go.microsoft.com/fwlink?LinkId=108181\" alt=\"Get Microsoft Silverlight\" "
+ "style=\"border-style:none\"/></a>",
html
);
Assert.EndsWith("</object>", html);
}
[Fact]
public void SilverlightThrowsWhenPathIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(
() =>
{
Video.Silverlight(GetContext(), _pathUtility, String.Empty, "100px", "100px");
},
"path"
);
}
[Fact]
public void SilverlightThrowsWhenPathIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(
() =>
{
Video.Silverlight(GetContext(), _pathUtility, null, "100px", "100px");
},
"path"
);
}
[Fact]
public void SilverlightThrowsWhenHeightIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(
() =>
{
Video.Silverlight(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.xap",
"100px",
String.Empty
);
},
"height"
);
}
[Fact]
public void SilverlightThrowsWhenHeightIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(
() =>
{
Video.Silverlight(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.xap",
"100px",
null
);
},
"height"
);
}
[Fact]
public void SilverlightThrowsWhenWidthIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(
() =>
{
Video.Silverlight(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.xap",
String.Empty,
"100px"
);
},
"width"
);
}
[Fact]
public void SilverlightThrowsWhenWidthIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(
() =>
{
Video.Silverlight(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.xap",
null,
"100px"
);
},
"width"
);
}
[Fact]
public void SilverlightWithExposedOptions()
{
string html = Video
.Silverlight(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.xap",
width: "85%",
height: "85%",
backgroundColor: "red",
initParameters: "X=Y",
minimumVersion: "1.0.0.0",
autoUpgrade: false,
htmlAttributes: new { id = "sl" }
)
.ToString()
.Replace("\r\n", "");
Assert.StartsWith(
"<object data=\"data:application/x-silverlight-2,\" height=\"85%\" id=\"sl\" "
+ "type=\"application/x-silverlight-2\" width=\"85%\" >",
html
);
Assert.Contains("<param name=\"background\" value=\"red\" />", html);
Assert.Contains("<param name=\"initparams\" value=\"X=Y\" />", html);
Assert.Contains("<param name=\"minruntimeversion\" value=\"1.0.0.0\" />", html);
Assert.Contains("<param name=\"autoUpgrade\" value=\"False\" />", html);
var embed = new Regex("<embed.*/>").Match(html);
Assert.False(embed.Success);
}
[Fact]
public void SilverlightWithUnexposedOptions()
{
string html = Video
.Silverlight(
GetContext(),
_pathUtility,
"http://foo.bar.com/foo.xap",
width: "50px",
height: "50px",
options: new { X = "Y", Z = 123 }
)
.ToString()
.Replace("\r\n", "");
Assert.Contains("<param name=\"X\" value=\"Y\" />", html);
Assert.Contains("<param name=\"Z\" value=\"123\" />", html);
}
[Fact]
public void ValidatePathResolvesExistingLocalPath()
{
string path = Assembly.GetExecutingAssembly().Location;
Mock<VirtualPathUtilityBase> pathUtility = new Mock<VirtualPathUtilityBase>();
pathUtility.Setup(p => p.Combine(It.IsAny<string>(), It.IsAny<string>())).Returns(path);
pathUtility.Setup(p => p.ToAbsolute(It.IsAny<string>())).Returns(path);
Mock<HttpServerUtilityBase> serverMock = new Mock<HttpServerUtilityBase>();
serverMock.Setup(s => s.MapPath(It.IsAny<string>())).Returns(path);
HttpContextBase context = GetContext(serverMock.Object);
string html = Video.Flash(context, pathUtility.Object, "foo.bar").ToString();
Assert.StartsWith("<object", html);
Assert.Contains(HttpUtility.HtmlAttributeEncode(HttpUtility.UrlPathEncode(path)), html);
}
[Fact]
public void ValidatePathThrowsForNonExistingLocalPath()
{
string path = "c:\\does\\not\\exist.swf";
Mock<VirtualPathUtilityBase> pathUtility = new Mock<VirtualPathUtilityBase>();
pathUtility.Setup(p => p.Combine(It.IsAny<string>(), It.IsAny<string>())).Returns(path);
pathUtility.Setup(p => p.ToAbsolute(It.IsAny<string>())).Returns(path);
Mock<HttpServerUtilityBase> serverMock = new Mock<HttpServerUtilityBase>();
serverMock.Setup(s => s.MapPath(It.IsAny<string>())).Returns(path);
HttpContextBase context = GetContext(serverMock.Object);
Assert.Throws<InvalidOperationException>(
() =>
{
Video.Flash(context, pathUtility.Object, "exist.swf");
},
"The media file \"exist.swf\" does not exist."
);
}
private static HttpContextBase GetContext(HttpServerUtilityBase serverUtility = null)
{
// simple mocked context - won't reference as long as path starts with 'http'
Mock<HttpRequestBase> requestMock = new Mock<HttpRequestBase>();
Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();
contextMock.Setup(context => context.Request).Returns(requestMock.Object);
contextMock.Setup(context => context.Server).Returns(serverUtility);
return contextMock.Object;
}
}
}
| 37.916821 | 146 | 0.452104 | [
"Apache-2.0"
] | belav/AspNetWebStack | test/Microsoft.Web.Helpers.Test/VideoTest.cs | 20,515 | 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 application-autoscaling-2016-02-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.Runtime;
using Amazon.ApplicationAutoScaling.Model;
namespace Amazon.ApplicationAutoScaling
{
/// <summary>
/// Interface for accessing ApplicationAutoScaling
///
/// With Application Auto Scaling, you can configure automatic scaling for the following
/// resources:
///
/// <ul> <li>
/// <para>
/// Amazon AppStream 2.0 fleets
/// </para>
/// </li> <li>
/// <para>
/// Amazon Aurora Replicas
/// </para>
/// </li> <li>
/// <para>
/// Amazon Comprehend document classification and entity recognizer endpoints
/// </para>
/// </li> <li>
/// <para>
/// Amazon DynamoDB tables and global secondary indexes throughput capacity
/// </para>
/// </li> <li>
/// <para>
/// Amazon ECS services
/// </para>
/// </li> <li>
/// <para>
/// Amazon ElastiCache for Redis clusters (replication groups)
/// </para>
/// </li> <li>
/// <para>
/// Amazon EMR clusters
/// </para>
/// </li> <li>
/// <para>
/// Amazon Keyspaces (for Apache Cassandra) tables
/// </para>
/// </li> <li>
/// <para>
/// Lambda function provisioned concurrency
/// </para>
/// </li> <li>
/// <para>
/// Amazon Managed Streaming for Apache Kafka broker storage
/// </para>
/// </li> <li>
/// <para>
/// Amazon SageMaker endpoint variants
/// </para>
/// </li> <li>
/// <para>
/// Spot Fleet (Amazon EC2) requests
/// </para>
/// </li> <li>
/// <para>
/// Custom resources provided by your own applications or services
/// </para>
/// </li> </ul>
/// <para>
/// <b>API Summary</b>
/// </para>
///
/// <para>
/// The Application Auto Scaling service API includes three key sets of actions:
/// </para>
/// <ul> <li>
/// <para>
/// Register and manage scalable targets - Register Amazon Web Services or custom resources
/// as scalable targets (a resource that Application Auto Scaling can scale), set minimum
/// and maximum capacity limits, and retrieve information on existing scalable targets.
/// </para>
/// </li> <li>
/// <para>
/// Configure and manage automatic scaling - Define scaling policies to dynamically scale
/// your resources in response to CloudWatch alarms, schedule one-time or recurring scaling
/// actions, and retrieve your recent scaling activity history.
/// </para>
/// </li> <li>
/// <para>
/// Suspend and resume scaling - Temporarily suspend and later resume automatic scaling
/// by calling the <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_RegisterScalableTarget.html">RegisterScalableTarget</a>
/// API action for any Application Auto Scaling scalable target. You can suspend and resume
/// (individually or in combination) scale-out activities that are triggered by a scaling
/// policy, scale-in activities that are triggered by a scaling policy, and scheduled
/// scaling.
/// </para>
/// </li> </ul>
/// <para>
/// To learn more about Application Auto Scaling, including information about granting
/// IAM users required permissions for Application Auto Scaling actions, see the <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/what-is-application-auto-scaling.html">Application
/// Auto Scaling User Guide</a>.
/// </para>
/// </summary>
public partial interface IAmazonApplicationAutoScaling : IAmazonService, IDisposable
{
#if BCL45 || AWS_ASYNC_ENUMERABLES_API
/// <summary>
/// Paginators for the service
/// </summary>
IApplicationAutoScalingPaginatorFactory Paginators { get; }
#endif
#region DeleteScalingPolicy
/// <summary>
/// Deletes the specified scaling policy for an Application Auto Scaling scalable target.
///
///
/// <para>
/// Deleting a step scaling policy deletes the underlying alarm action, but does not delete
/// the CloudWatch alarm associated with the scaling policy, even if it no longer has
/// an associated action.
/// </para>
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html#delete-step-scaling-policy">Delete
/// a step scaling policy</a> and <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html#delete-target-tracking-policy">Delete
/// a target tracking scaling policy</a> in the <i>Application Auto Scaling User Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteScalingPolicy service method.</param>
///
/// <returns>The response from the DeleteScalingPolicy service method, as returned by ApplicationAutoScaling.</returns>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ConcurrentUpdateException">
/// Concurrent updates caused an exception, for example, if you request an update to an
/// Application Auto Scaling resource that already has a pending update.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InternalServiceException">
/// The service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ObjectNotFoundException">
/// The specified object could not be found. For any operation that depends on the existence
/// of a scalable target, this exception is thrown if the scalable target with the specified
/// service namespace, resource ID, and scalable dimension does not exist. For any operation
/// that deletes or deregisters a resource, this exception is thrown if the resource cannot
/// be found.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ValidationException">
/// An exception was thrown for a validation issue. Review the available parameters for
/// the API request.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeleteScalingPolicy">REST API Reference for DeleteScalingPolicy Operation</seealso>
DeleteScalingPolicyResponse DeleteScalingPolicy(DeleteScalingPolicyRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteScalingPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteScalingPolicy operation on AmazonApplicationAutoScalingClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteScalingPolicy
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeleteScalingPolicy">REST API Reference for DeleteScalingPolicy Operation</seealso>
IAsyncResult BeginDeleteScalingPolicy(DeleteScalingPolicyRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteScalingPolicy operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteScalingPolicy.</param>
///
/// <returns>Returns a DeleteScalingPolicyResult from ApplicationAutoScaling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeleteScalingPolicy">REST API Reference for DeleteScalingPolicy Operation</seealso>
DeleteScalingPolicyResponse EndDeleteScalingPolicy(IAsyncResult asyncResult);
#endregion
#region DeleteScheduledAction
/// <summary>
/// Deletes the specified scheduled action for an Application Auto Scaling scalable target.
///
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/scheduled-scaling-additional-cli-commands.html#delete-scheduled-action">Delete
/// a scheduled action</a> in the <i>Application Auto Scaling User Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteScheduledAction service method.</param>
///
/// <returns>The response from the DeleteScheduledAction service method, as returned by ApplicationAutoScaling.</returns>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ConcurrentUpdateException">
/// Concurrent updates caused an exception, for example, if you request an update to an
/// Application Auto Scaling resource that already has a pending update.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InternalServiceException">
/// The service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ObjectNotFoundException">
/// The specified object could not be found. For any operation that depends on the existence
/// of a scalable target, this exception is thrown if the scalable target with the specified
/// service namespace, resource ID, and scalable dimension does not exist. For any operation
/// that deletes or deregisters a resource, this exception is thrown if the resource cannot
/// be found.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ValidationException">
/// An exception was thrown for a validation issue. Review the available parameters for
/// the API request.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeleteScheduledAction">REST API Reference for DeleteScheduledAction Operation</seealso>
DeleteScheduledActionResponse DeleteScheduledAction(DeleteScheduledActionRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteScheduledAction operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteScheduledAction operation on AmazonApplicationAutoScalingClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteScheduledAction
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeleteScheduledAction">REST API Reference for DeleteScheduledAction Operation</seealso>
IAsyncResult BeginDeleteScheduledAction(DeleteScheduledActionRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteScheduledAction operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteScheduledAction.</param>
///
/// <returns>Returns a DeleteScheduledActionResult from ApplicationAutoScaling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeleteScheduledAction">REST API Reference for DeleteScheduledAction Operation</seealso>
DeleteScheduledActionResponse EndDeleteScheduledAction(IAsyncResult asyncResult);
#endregion
#region DeregisterScalableTarget
/// <summary>
/// Deregisters an Application Auto Scaling scalable target when you have finished using
/// it. To see which resources have been registered, use <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_DescribeScalableTargets.html">DescribeScalableTargets</a>.
///
///
/// <note>
/// <para>
/// Deregistering a scalable target deletes the scaling policies and the scheduled actions
/// that are associated with it.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeregisterScalableTarget service method.</param>
///
/// <returns>The response from the DeregisterScalableTarget service method, as returned by ApplicationAutoScaling.</returns>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ConcurrentUpdateException">
/// Concurrent updates caused an exception, for example, if you request an update to an
/// Application Auto Scaling resource that already has a pending update.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InternalServiceException">
/// The service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ObjectNotFoundException">
/// The specified object could not be found. For any operation that depends on the existence
/// of a scalable target, this exception is thrown if the scalable target with the specified
/// service namespace, resource ID, and scalable dimension does not exist. For any operation
/// that deletes or deregisters a resource, this exception is thrown if the resource cannot
/// be found.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ValidationException">
/// An exception was thrown for a validation issue. Review the available parameters for
/// the API request.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeregisterScalableTarget">REST API Reference for DeregisterScalableTarget Operation</seealso>
DeregisterScalableTargetResponse DeregisterScalableTarget(DeregisterScalableTargetRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeregisterScalableTarget operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeregisterScalableTarget operation on AmazonApplicationAutoScalingClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeregisterScalableTarget
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeregisterScalableTarget">REST API Reference for DeregisterScalableTarget Operation</seealso>
IAsyncResult BeginDeregisterScalableTarget(DeregisterScalableTargetRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeregisterScalableTarget operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeregisterScalableTarget.</param>
///
/// <returns>Returns a DeregisterScalableTargetResult from ApplicationAutoScaling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DeregisterScalableTarget">REST API Reference for DeregisterScalableTarget Operation</seealso>
DeregisterScalableTargetResponse EndDeregisterScalableTarget(IAsyncResult asyncResult);
#endregion
#region DescribeScalableTargets
/// <summary>
/// Gets information about the scalable targets in the specified namespace.
///
///
/// <para>
/// You can filter the results using <code>ResourceIds</code> and <code>ScalableDimension</code>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeScalableTargets service method.</param>
///
/// <returns>The response from the DescribeScalableTargets service method, as returned by ApplicationAutoScaling.</returns>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ConcurrentUpdateException">
/// Concurrent updates caused an exception, for example, if you request an update to an
/// Application Auto Scaling resource that already has a pending update.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InternalServiceException">
/// The service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InvalidNextTokenException">
/// The next token supplied was invalid.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ValidationException">
/// An exception was thrown for a validation issue. Review the available parameters for
/// the API request.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalableTargets">REST API Reference for DescribeScalableTargets Operation</seealso>
DescribeScalableTargetsResponse DescribeScalableTargets(DescribeScalableTargetsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeScalableTargets operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeScalableTargets operation on AmazonApplicationAutoScalingClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeScalableTargets
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalableTargets">REST API Reference for DescribeScalableTargets Operation</seealso>
IAsyncResult BeginDescribeScalableTargets(DescribeScalableTargetsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeScalableTargets operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeScalableTargets.</param>
///
/// <returns>Returns a DescribeScalableTargetsResult from ApplicationAutoScaling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalableTargets">REST API Reference for DescribeScalableTargets Operation</seealso>
DescribeScalableTargetsResponse EndDescribeScalableTargets(IAsyncResult asyncResult);
#endregion
#region DescribeScalingActivities
/// <summary>
/// Provides descriptive information about the scaling activities in the specified namespace
/// from the previous six weeks.
///
///
/// <para>
/// You can filter the results using <code>ResourceId</code> and <code>ScalableDimension</code>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeScalingActivities service method.</param>
///
/// <returns>The response from the DescribeScalingActivities service method, as returned by ApplicationAutoScaling.</returns>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ConcurrentUpdateException">
/// Concurrent updates caused an exception, for example, if you request an update to an
/// Application Auto Scaling resource that already has a pending update.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InternalServiceException">
/// The service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InvalidNextTokenException">
/// The next token supplied was invalid.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ValidationException">
/// An exception was thrown for a validation issue. Review the available parameters for
/// the API request.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalingActivities">REST API Reference for DescribeScalingActivities Operation</seealso>
DescribeScalingActivitiesResponse DescribeScalingActivities(DescribeScalingActivitiesRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeScalingActivities operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeScalingActivities operation on AmazonApplicationAutoScalingClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeScalingActivities
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalingActivities">REST API Reference for DescribeScalingActivities Operation</seealso>
IAsyncResult BeginDescribeScalingActivities(DescribeScalingActivitiesRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeScalingActivities operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeScalingActivities.</param>
///
/// <returns>Returns a DescribeScalingActivitiesResult from ApplicationAutoScaling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalingActivities">REST API Reference for DescribeScalingActivities Operation</seealso>
DescribeScalingActivitiesResponse EndDescribeScalingActivities(IAsyncResult asyncResult);
#endregion
#region DescribeScalingPolicies
/// <summary>
/// Describes the Application Auto Scaling scaling policies for the specified service
/// namespace.
///
///
/// <para>
/// You can filter the results using <code>ResourceId</code>, <code>ScalableDimension</code>,
/// and <code>PolicyNames</code>.
/// </para>
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html">Target
/// tracking scaling policies</a> and <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html">Step
/// scaling policies</a> in the <i>Application Auto Scaling User Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeScalingPolicies service method.</param>
///
/// <returns>The response from the DescribeScalingPolicies service method, as returned by ApplicationAutoScaling.</returns>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ConcurrentUpdateException">
/// Concurrent updates caused an exception, for example, if you request an update to an
/// Application Auto Scaling resource that already has a pending update.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.FailedResourceAccessException">
/// Failed access to resources caused an exception. This exception is thrown when Application
/// Auto Scaling is unable to retrieve the alarms associated with a scaling policy due
/// to a client error, for example, if the role ARN specified for a scalable target does
/// not have permission to call the CloudWatch <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarms.html">DescribeAlarms</a>
/// on your behalf.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InternalServiceException">
/// The service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InvalidNextTokenException">
/// The next token supplied was invalid.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ValidationException">
/// An exception was thrown for a validation issue. Review the available parameters for
/// the API request.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalingPolicies">REST API Reference for DescribeScalingPolicies Operation</seealso>
DescribeScalingPoliciesResponse DescribeScalingPolicies(DescribeScalingPoliciesRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeScalingPolicies operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeScalingPolicies operation on AmazonApplicationAutoScalingClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeScalingPolicies
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalingPolicies">REST API Reference for DescribeScalingPolicies Operation</seealso>
IAsyncResult BeginDescribeScalingPolicies(DescribeScalingPoliciesRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeScalingPolicies operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeScalingPolicies.</param>
///
/// <returns>Returns a DescribeScalingPoliciesResult from ApplicationAutoScaling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScalingPolicies">REST API Reference for DescribeScalingPolicies Operation</seealso>
DescribeScalingPoliciesResponse EndDescribeScalingPolicies(IAsyncResult asyncResult);
#endregion
#region DescribeScheduledActions
/// <summary>
/// Describes the Application Auto Scaling scheduled actions for the specified service
/// namespace.
///
///
/// <para>
/// You can filter the results using the <code>ResourceId</code>, <code>ScalableDimension</code>,
/// and <code>ScheduledActionNames</code> parameters.
/// </para>
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-scheduled-scaling.html">Scheduled
/// scaling</a> and <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/scheduled-scaling-additional-cli-commands.html">Managing
/// scheduled scaling</a> in the <i>Application Auto Scaling User Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeScheduledActions service method.</param>
///
/// <returns>The response from the DescribeScheduledActions service method, as returned by ApplicationAutoScaling.</returns>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ConcurrentUpdateException">
/// Concurrent updates caused an exception, for example, if you request an update to an
/// Application Auto Scaling resource that already has a pending update.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InternalServiceException">
/// The service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InvalidNextTokenException">
/// The next token supplied was invalid.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ValidationException">
/// An exception was thrown for a validation issue. Review the available parameters for
/// the API request.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScheduledActions">REST API Reference for DescribeScheduledActions Operation</seealso>
DescribeScheduledActionsResponse DescribeScheduledActions(DescribeScheduledActionsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeScheduledActions operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeScheduledActions operation on AmazonApplicationAutoScalingClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeScheduledActions
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScheduledActions">REST API Reference for DescribeScheduledActions Operation</seealso>
IAsyncResult BeginDescribeScheduledActions(DescribeScheduledActionsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeScheduledActions operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeScheduledActions.</param>
///
/// <returns>Returns a DescribeScheduledActionsResult from ApplicationAutoScaling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScheduledActions">REST API Reference for DescribeScheduledActions Operation</seealso>
DescribeScheduledActionsResponse EndDescribeScheduledActions(IAsyncResult asyncResult);
#endregion
#region PutScalingPolicy
/// <summary>
/// Creates or updates a scaling policy for an Application Auto Scaling scalable target.
///
///
/// <para>
/// Each scalable target is identified by a service namespace, resource ID, and scalable
/// dimension. A scaling policy applies to the scalable target identified by those three
/// attributes. You cannot create a scaling policy until you have registered the resource
/// as a scalable target.
/// </para>
///
/// <para>
/// Multiple scaling policies can be in force at the same time for the same scalable target.
/// You can have one or more target tracking scaling policies, one or more step scaling
/// policies, or both. However, there is a chance that multiple policies could conflict,
/// instructing the scalable target to scale out or in at the same time. Application Auto
/// Scaling gives precedence to the policy that provides the largest capacity for both
/// scale out and scale in. For example, if one policy increases capacity by 3, another
/// policy increases capacity by 200 percent, and the current capacity is 10, Application
/// Auto Scaling uses the policy with the highest calculated capacity (200% of 10 = 20)
/// and scales out to 30.
/// </para>
///
/// <para>
/// We recommend caution, however, when using target tracking scaling policies with step
/// scaling policies because conflicts between these policies can cause undesirable behavior.
/// For example, if the step scaling policy initiates a scale-in activity before the target
/// tracking policy is ready to scale in, the scale-in activity will not be blocked. After
/// the scale-in activity completes, the target tracking policy could instruct the scalable
/// target to scale out again.
/// </para>
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html">Target
/// tracking scaling policies</a> and <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html">Step
/// scaling policies</a> in the <i>Application Auto Scaling User Guide</i>.
/// </para>
/// <note>
/// <para>
/// If a scalable target is deregistered, the scalable target is no longer available to
/// execute scaling policies. Any scaling policies that were specified for the scalable
/// target are deleted.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutScalingPolicy service method.</param>
///
/// <returns>The response from the PutScalingPolicy service method, as returned by ApplicationAutoScaling.</returns>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ConcurrentUpdateException">
/// Concurrent updates caused an exception, for example, if you request an update to an
/// Application Auto Scaling resource that already has a pending update.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.FailedResourceAccessException">
/// Failed access to resources caused an exception. This exception is thrown when Application
/// Auto Scaling is unable to retrieve the alarms associated with a scaling policy due
/// to a client error, for example, if the role ARN specified for a scalable target does
/// not have permission to call the CloudWatch <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarms.html">DescribeAlarms</a>
/// on your behalf.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InternalServiceException">
/// The service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.LimitExceededException">
/// A per-account resource limit is exceeded. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-limits.html">Application
/// Auto Scaling service quotas</a>.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ObjectNotFoundException">
/// The specified object could not be found. For any operation that depends on the existence
/// of a scalable target, this exception is thrown if the scalable target with the specified
/// service namespace, resource ID, and scalable dimension does not exist. For any operation
/// that deletes or deregisters a resource, this exception is thrown if the resource cannot
/// be found.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ValidationException">
/// An exception was thrown for a validation issue. Review the available parameters for
/// the API request.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/PutScalingPolicy">REST API Reference for PutScalingPolicy Operation</seealso>
PutScalingPolicyResponse PutScalingPolicy(PutScalingPolicyRequest request);
/// <summary>
/// Initiates the asynchronous execution of the PutScalingPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutScalingPolicy operation on AmazonApplicationAutoScalingClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutScalingPolicy
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/PutScalingPolicy">REST API Reference for PutScalingPolicy Operation</seealso>
IAsyncResult BeginPutScalingPolicy(PutScalingPolicyRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the PutScalingPolicy operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutScalingPolicy.</param>
///
/// <returns>Returns a PutScalingPolicyResult from ApplicationAutoScaling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/PutScalingPolicy">REST API Reference for PutScalingPolicy Operation</seealso>
PutScalingPolicyResponse EndPutScalingPolicy(IAsyncResult asyncResult);
#endregion
#region PutScheduledAction
/// <summary>
/// Creates or updates a scheduled action for an Application Auto Scaling scalable target.
///
///
///
/// <para>
/// Each scalable target is identified by a service namespace, resource ID, and scalable
/// dimension. A scheduled action applies to the scalable target identified by those three
/// attributes. You cannot create a scheduled action until you have registered the resource
/// as a scalable target.
/// </para>
///
/// <para>
/// When start and end times are specified with a recurring schedule using a cron expression
/// or rates, they form the boundaries for when the recurring action starts and stops.
/// </para>
///
/// <para>
/// To update a scheduled action, specify the parameters that you want to change. If you
/// don't specify start and end times, the old values are deleted.
/// </para>
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-scheduled-scaling.html">Scheduled
/// scaling</a> in the <i>Application Auto Scaling User Guide</i>.
/// </para>
/// <note>
/// <para>
/// If a scalable target is deregistered, the scalable target is no longer available to
/// run scheduled actions. Any scheduled actions that were specified for the scalable
/// target are deleted.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutScheduledAction service method.</param>
///
/// <returns>The response from the PutScheduledAction service method, as returned by ApplicationAutoScaling.</returns>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ConcurrentUpdateException">
/// Concurrent updates caused an exception, for example, if you request an update to an
/// Application Auto Scaling resource that already has a pending update.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InternalServiceException">
/// The service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.LimitExceededException">
/// A per-account resource limit is exceeded. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-limits.html">Application
/// Auto Scaling service quotas</a>.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ObjectNotFoundException">
/// The specified object could not be found. For any operation that depends on the existence
/// of a scalable target, this exception is thrown if the scalable target with the specified
/// service namespace, resource ID, and scalable dimension does not exist. For any operation
/// that deletes or deregisters a resource, this exception is thrown if the resource cannot
/// be found.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ValidationException">
/// An exception was thrown for a validation issue. Review the available parameters for
/// the API request.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/PutScheduledAction">REST API Reference for PutScheduledAction Operation</seealso>
PutScheduledActionResponse PutScheduledAction(PutScheduledActionRequest request);
/// <summary>
/// Initiates the asynchronous execution of the PutScheduledAction operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutScheduledAction operation on AmazonApplicationAutoScalingClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutScheduledAction
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/PutScheduledAction">REST API Reference for PutScheduledAction Operation</seealso>
IAsyncResult BeginPutScheduledAction(PutScheduledActionRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the PutScheduledAction operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutScheduledAction.</param>
///
/// <returns>Returns a PutScheduledActionResult from ApplicationAutoScaling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/PutScheduledAction">REST API Reference for PutScheduledAction Operation</seealso>
PutScheduledActionResponse EndPutScheduledAction(IAsyncResult asyncResult);
#endregion
#region RegisterScalableTarget
/// <summary>
/// Registers or updates a scalable target.
///
///
/// <para>
/// A scalable target is a resource that Application Auto Scaling can scale out and scale
/// in. Scalable targets are uniquely identified by the combination of resource ID, scalable
/// dimension, and namespace.
/// </para>
///
/// <para>
/// When you register a new scalable target, you must specify values for minimum and maximum
/// capacity. Current capacity will be adjusted within the specified range when scaling
/// starts. Application Auto Scaling scaling policies will not scale capacity to values
/// that are outside of this range.
/// </para>
///
/// <para>
/// After you register a scalable target, you do not need to register it again to use
/// other Application Auto Scaling operations. To see which resources have been registered,
/// use <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_DescribeScalableTargets.html">DescribeScalableTargets</a>.
/// You can also view the scaling policies for a service namespace by using <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_DescribeScalableTargets.html">DescribeScalableTargets</a>.
/// If you no longer need a scalable target, you can deregister it by using <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/API_DeregisterScalableTarget.html">DeregisterScalableTarget</a>.
/// </para>
///
/// <para>
/// To update a scalable target, specify the parameters that you want to change. Include
/// the parameters that identify the scalable target: resource ID, scalable dimension,
/// and namespace. Any parameters that you don't specify are not changed by this update
/// request.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RegisterScalableTarget service method.</param>
///
/// <returns>The response from the RegisterScalableTarget service method, as returned by ApplicationAutoScaling.</returns>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ConcurrentUpdateException">
/// Concurrent updates caused an exception, for example, if you request an update to an
/// Application Auto Scaling resource that already has a pending update.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.InternalServiceException">
/// The service encountered an internal error.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.LimitExceededException">
/// A per-account resource limit is exceeded. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-limits.html">Application
/// Auto Scaling service quotas</a>.
/// </exception>
/// <exception cref="Amazon.ApplicationAutoScaling.Model.ValidationException">
/// An exception was thrown for a validation issue. Review the available parameters for
/// the API request.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/RegisterScalableTarget">REST API Reference for RegisterScalableTarget Operation</seealso>
RegisterScalableTargetResponse RegisterScalableTarget(RegisterScalableTargetRequest request);
/// <summary>
/// Initiates the asynchronous execution of the RegisterScalableTarget operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RegisterScalableTarget operation on AmazonApplicationAutoScalingClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRegisterScalableTarget
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/RegisterScalableTarget">REST API Reference for RegisterScalableTarget Operation</seealso>
IAsyncResult BeginRegisterScalableTarget(RegisterScalableTargetRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the RegisterScalableTarget operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRegisterScalableTarget.</param>
///
/// <returns>Returns a RegisterScalableTargetResult from ApplicationAutoScaling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/RegisterScalableTarget">REST API Reference for RegisterScalableTarget Operation</seealso>
RegisterScalableTargetResponse EndRegisterScalableTarget(IAsyncResult asyncResult);
#endregion
}
} | 59.625705 | 222 | 0.683747 | [
"Apache-2.0"
] | ebattalio/aws-sdk-net | sdk/src/Services/ApplicationAutoScaling/Generated/_bcl35/IAmazonApplicationAutoScaling.cs | 52,888 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
class TeamworkProjects
{
static void Main(string[] args)
{
int creatorsCount = int.Parse(Console.ReadLine());
var teams = new Dictionary<string, Team>();
for (int counter = 0; counter < creatorsCount; counter++)
{
string[] creatorArgs = Console.ReadLine()
.Split('-')
.ToArray();
string creatorName = creatorArgs[0];
string teamName = creatorArgs[1];
Team team = new Team(teamName, creatorName);
if (teams.ContainsKey(teamName))
{
Console.WriteLine($"Team {teamName} was already created!");
}
else if (teams.Any(x => x.Value.Creator == creatorName))
{
Console.WriteLine($"{creatorName} cannot create another team!");
}
else
{
teams.Add(teamName, team);
Console.WriteLine($"Team {teamName} has been created by {creatorName}!");
}
}
string input;
while ((input = Console.ReadLine()) != "end of assignment")
{
string[] memberArgs = input
.Split("->".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.ToArray();
string memberName = memberArgs[0];
string teamName = memberArgs[1];
if (teams.ContainsKey(teamName) == false)
{
Console.WriteLine($"Team {teamName} does not exist!");
}
else if (teams.Any(x => x.Value.Creator == memberName ||
x.Value.Members.Contains(memberName)))
{
Console.WriteLine($"Member {memberName} cannot join team {teamName}!");
}
else
{
teams[teamName].AddMember(memberName);
}
}
List<Team> validTeams = teams.Values.Where(x => x.Members.Count > 0).ToList();
List<Team> teamsToDisband = teams.Values.Where(x => x.Members.Count == 0).ToList();
foreach (var team in validTeams.OrderByDescending(x => x.Members.Count).ThenBy(x => x.Name))
{
Console.WriteLine(team.Name);
Console.WriteLine($"- {team.Creator}");
foreach (var member in team.Members.OrderBy(x => x))
{
Console.WriteLine($"-- {member}");
}
}
Console.WriteLine("Teams to disband:");
foreach (var team in teamsToDisband.OrderBy(x => x.Name))
{
Console.WriteLine(team.Name);
}
}
}
class Team
{
public Team(string name, string creator)
{
this.Name = name;
this.Creator = creator;
this.Members = new List<string>();
}
public string Name { get; }
public string Creator { get; }
public List<string> Members { get; }
public void AddMember(string memberName)
{
Members.Add(memberName);
}
} | 28.913462 | 100 | 0.533755 | [
"MIT"
] | VladimirKyuranov/Programming-Fundamentals | Exercises/Ex08-ObjectsAndClasses/09-TeamworkProjects/TeamworkProjects.cs | 3,009 | C# |
namespace Cosmos.I18N.Countries.Europe
{
/// <summary>
/// 瑞士(Swiss Confederation,欧洲,CH,CHE,756),瑞士联邦 <br />
/// Cosmos i18n code: i18n_country_ruishi <br />
/// Cosmos region code: 200017
/// </summary>
public static partial class Switzerland
{
// ReSharper disable once InconsistentNaming
private static readonly CountryInfo _country;
static Switzerland()
{
_country = new CountryInfo
{
Country = Country.Switzerland,
CountryCode = CountryCode.CH,
CountryType = CountryType.Country,
BelongsToCountry = Country.Switzerland,
M49Code = "756",
Cep1CrCode = 2_00_017,
Alpha2Code = "CH",
Alpha3Code = "CHE",
Name = "Swiss Confederation",
ShorterForm = "Switzerland",
ChineseName = "瑞士联邦",
ChineseShorterForm = "瑞士",
Continent = Continent.Europe,
I18NIdentityCode = I18N_IDENTITY_CODE,
GetRegionEnumValue = GetRegionEnumValue
};
}
/// <summary>
/// 瑞士(Swiss Confederation,欧洲,CH,CHE,756),瑞士联邦 <br />
/// Cosmos i18n code: i18n_country_ruishi <br />
/// Cosmos region code: 200017
/// </summary>
public static CountryInfo Instance => _country;
/// <summary>
/// i18n
/// </summary>
// ReSharper disable once InconsistentNaming
public const string I18N_IDENTITY_CODE = "i18n_country_ruishi";
/// <summary>
/// Get Cosmos Region Code (CEP-1/CRCode)
/// </summary>
public static long CosmosRegionCode => _country.Cep1CrCode;
/// <summary>
/// Get Cosmos Region Identity Code (CEP-1/IICode)
/// </summary>
public static string CosmosIdentityCode => _country.I18NIdentityCode;
/// <summary>
/// Get M49 code / ISO 3166-1 numeric
/// </summary>
public static string M49Code => _country.M49Code;
/// <summary>
/// Get Alpha2 code / ISO 3166-1 alpha-2
/// </summary>
public static string Alpha2Code => _country.Alpha2Code;
/// <summary>
/// Get Alpha3 code / ISO 3166-1 alpha-3
/// </summary>
public static string Alpha3Code => _country.Alpha3Code;
}
} | 33.438356 | 77 | 0.550594 | [
"Apache-2.0"
] | alexinea/I18N | src/Cosmos.I18N.Countries/Cosmos/I18N/Countries/Europe/Switzerland.cs | 2,513 | C# |
namespace AdventOfCSharp.Analyzers.Tests.PartSolverAttributes;
public abstract class PartSolverAttributeAnalyzerTests : BaseAoCSDiagnosticTests<PartSolverAttributeAnalyzer>
{
}
| 29.833333 | 109 | 0.882682 | [
"MIT"
] | AlFasGD/AdventOfCSharp | AdventOfCSharp.Analyzers.Tests/PartSolverAttributes/PartSolverAttributeAnalyzerTests.cs | 181 | C# |
namespace Demo.DTOs.Profiles
{
using System.Linq;
using AutoMapper;
using Models;
public class ProductProfile : Profile
{
public ProductProfile()
{
this.CreateMap<Product, ProductDto>()
.ForMember(dto => dto.InStorageCount,
opt => opt.MapFrom(src => src.Storages.Sum(p => p.Quantity)));
}
}
} | 21.833333 | 82 | 0.552163 | [
"MIT"
] | pirocorp/Databases-Advanced---Entity-Framework | 08. C# Auto Mapping Objects/Lab/Demo/Demo/DTOs/Profiles/ProductProfile.cs | 395 | 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.Tests
{
public class ConvertToCharTests : ConvertTestBase<Char>
{
[Fact]
public void FromByte()
{
Byte[] testValues = { Byte.MaxValue, Byte.MinValue };
Char[] expectedValues = { (Char)Byte.MaxValue, (Char)Byte.MinValue };
Verify(Convert.ToChar, testValues, expectedValues);
}
[Fact]
public void FromChar()
{
Object[] testValues = { Char.MaxValue, Char.MinValue, 'b' };
Char[] expectedValues = { Char.MaxValue, Char.MinValue, 'b' };
Verify<Object>(Convert.ToChar, testValues, expectedValues);
}
[Fact]
public void FromDecimal()
{
Object[] invalidValues = { 0m, Decimal.MinValue, Decimal.MaxValue };
VerifyFromObjectThrows<InvalidCastException>(Convert.ToChar, Convert.ToChar, invalidValues);
}
[Fact]
public void FromDouble()
{
Object[] invalidValues = { 0.0, Double.MinValue, Double.MaxValue };
VerifyFromObjectThrows<InvalidCastException>(Convert.ToChar, Convert.ToChar, invalidValues);
}
[Fact]
public void FromInt16()
{
Int16[] testValues = { Int16.MaxValue, 0 };
Char[] expectedValues = { (Char)Int16.MaxValue, '\0' };
Verify(Convert.ToChar, testValues, expectedValues);
Int16[] overflowValues = { Int16.MinValue, -1000 };
VerifyThrows<OverflowException, Int16>(Convert.ToChar, overflowValues);
}
[Fact]
public void FromInt32()
{
Int32[] testValues = { Char.MaxValue, Char.MinValue };
Char[] expectedValues = { Char.MaxValue, Char.MinValue };
Verify(Convert.ToChar, testValues, expectedValues);
Int32[] overflowValues = { Int32.MinValue, Int32.MaxValue, (Int32)UInt16.MaxValue + 1, -1000 };
VerifyThrows<OverflowException, Int32>(Convert.ToChar, overflowValues);
}
[Fact]
public void FromInt64()
{
Int64[] testValues = { 0, 98, UInt16.MaxValue };
Char[] expectedValues = { '\0', 'b', Char.MaxValue };
Verify(Convert.ToChar, testValues, expectedValues);
Int64[] overflowValues = { Int64.MinValue, Int64.MaxValue, -1 };
VerifyThrows<OverflowException, Int64>(Convert.ToChar, overflowValues);
}
[Fact]
public void FromObject()
{
Object[] testValues = { null };
Char[] expectedValues = { '\0' };
Verify(Convert.ToChar, testValues, expectedValues);
Object[] invalidValues = { new Object(), DateTime.Now };
VerifyThrows<InvalidCastException, Object>(Convert.ToChar, invalidValues);
}
[Fact]
public void FromSByte()
{
SByte[] testValues = { SByte.MaxValue, 0 };
Char[] expectedValues = { (Char)SByte.MaxValue, '\0' };
Verify(Convert.ToChar, testValues, expectedValues);
SByte[] overflowValues = { SByte.MinValue, -100, -1 };
VerifyThrows<OverflowException, SByte>(Convert.ToChar, overflowValues);
}
[Fact]
public void FromSingle()
{
Object[] invalidValues = { 0f, Single.MinValue, Single.MaxValue };
VerifyFromObjectThrows<InvalidCastException>(Convert.ToChar, Convert.ToChar, invalidValues);
}
[Fact]
public void FromString()
{
String[] testValues = { "a", "T", "z", "a" };
Char[] expectedValues = { 'a', 'T', 'z', 'a' };
VerifyFromString(Convert.ToChar, Convert.ToChar, testValues, expectedValues);
String[] formatExceptionValues = { String.Empty, "ab" };
VerifyFromStringThrows<FormatException>(Convert.ToChar, Convert.ToChar, formatExceptionValues);
VerifyFromStringThrows<ArgumentNullException>(Convert.ToChar, Convert.ToChar, new String[] { null });
}
[Fact]
public void FromUInt16()
{
UInt16[] testValues = { 0, 98, UInt16.MaxValue };
Char[] expectedValues = { '\0', 'b', Char.MaxValue };
Verify(Convert.ToChar, testValues, expectedValues);
}
[Fact]
public void FromUInt32()
{
UInt32[] testValues = { UInt16.MaxValue, 0 };
Char[] expectedValues = { (Char)UInt16.MaxValue, '\0' };
Verify(Convert.ToChar, testValues, expectedValues);
UInt32[] overflowValues = { UInt32.MaxValue };
VerifyThrows<OverflowException, UInt32>(Convert.ToChar, overflowValues);
}
[Fact]
public void FromUInt64()
{
UInt64[] testValues = { 0, 98, UInt16.MaxValue };
Char[] expectedValues = { '\0', 'b', Char.MaxValue };
Verify(Convert.ToChar, testValues, expectedValues);
UInt64[] overflowValues = { UInt64.MaxValue, (UInt64)UInt16.MaxValue + 1 };
VerifyThrows<OverflowException, UInt64>(Convert.ToChar, overflowValues);
}
}
}
| 36.924658 | 113 | 0.58171 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Runtime.Extensions/tests/System/Convert.ToChar.cs | 5,391 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.IO;
using Microsoft.SPOT.Platform.Test;
using System.IO;
namespace Microsoft.SPOT.Platform.Tests
{
public class Delete : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
try
{
IOTests.IntializeVolume();
Directory.CreateDirectory("CreateDirectory");
}
catch (Exception ex)
{
Log.Exception("Skipping: Unable to initialize file system", ex);
return InitializeResult.Skip;
}
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
#region Local vars
private const string DIR = @"DelDir";
private bool createFile = false;
#endregion Local vars
#region Helper functions
private bool TestDelete(string delete)
{
return TestDelete(delete, delete);
}
private bool TestDelete(string delete, bool recursive)
{
return TestDelete(delete, delete, recursive);
}
private bool TestDelete(string delete, string create)
{
Log.Comment("Delete dir: " + delete);
if (!CreateDir(create))
return false;
Directory.Delete(delete);
return VerifyDelete(delete);
}
private bool TestDelete(string delete, string create, bool recursive)
{
Log.Comment("Delete dir: " + delete);
if (!CreateDir(create))
return false;
try
{
Directory.Delete(delete, recursive);
}
catch (IOException ex)
{
if (recursive && IOTests.Volume.FileSystem == "WINFS")
{
Log.Exception("WINFS has bug where recurisve may fail if indexer or Virus has handle open. Wait and try again.");
for (int i = 0; i < 10; i++)
{
System.Threading.Thread.Sleep(1000);
try { Directory.Delete(DIR, true); }
catch { }
if (VerifyDelete(DIR))
{
return true;
}
}
}
throw ex;
}
return VerifyDelete(delete);
}
private bool VerifyDelete(string path)
{
if (Directory.Exists(path))
{
Log.Exception("Failed to Delete " + path);
return false;
}
return true;
}
private bool CreateDir(string path)
{
DirectoryInfo dir2 = Directory.CreateDirectory(path);
if (!Directory.Exists(path))
{
Log.Exception("Failed to Create " + dir2.FullName);
return false;
}
if (createFile)
{
using (FileStream fs = new FileStream(dir2.FullName + @"\temp.txt", FileMode.Create)) { }
if (!File.Exists(dir2.FullName + @"\temp.txt"))
{
Log.Exception("Failed to create file");
return false;
}
}
return true;
}
#endregion Helper functions
#region Test Cases
[TestMethod]
public MFTestResults DelCurrentDir()
{
MFTestResults result = MFTestResults.Pass;
try
{
try
{
//Currently this causes hang
Directory.Delete(".", false);
Log.Exception("Should not be able to delete current directory");
result = MFTestResults.Fail;
}
catch (IOException) {/* pass case */}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults DelNonExistent()
{
MFTestResults result = MFTestResults.Pass;
try
{
try
{
Directory.Delete("ThisDoesNotExist");
Log.Exception("Should not be able to delete nonexistent directory");
result = MFTestResults.Fail;
}
catch (IOException) {/* pass case */}
try
{
Directory.Delete("ThisDoesNotExist", false);
Log.Exception("Should not be able to delete nonexistent directory");
result = MFTestResults.Fail;
}
catch (IOException) {/* pass case */}
try
{
Directory.Delete("ThisDoesNotExist", true);
Log.Exception("Should not be able to delete nonexistent directory");
result = MFTestResults.Fail;
}
catch (IOException) {/* pass case */}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults DeleteDirNoSub()
{
MFTestResults result = MFTestResults.Pass;
createFile = false;
try
{
Log.Comment("Delete");
if (!TestDelete(DIR))
result = MFTestResults.Fail;
Log.Comment("Delete non-recursive");
if (!TestDelete(DIR, false))
result = MFTestResults.Fail;
Log.Comment("Delete recursive");
if (!TestDelete(DIR, true))
result = MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults DeleteDirSub()
{
MFTestResults result = MFTestResults.Pass;
createFile = false;
try
{
Log.Comment("Delete - should throw IOException");
try
{
TestDelete(DIR, DIR + @"\SubTest1");
Log.Comment("Expected IO Exception because of subdir");
result = MFTestResults.Fail;
}
catch (IOException) {/* pass case */}
Log.Comment("Delete non-recursive - should throw IOException");
try
{
TestDelete(DIR, DIR + @"\SubTest2", false);
Log.Comment("Expected IO Exception because of subdir");
result = MFTestResults.Fail;
}
catch (IOException) {/* pass case */}
Log.Comment("Delete recursive");
if (!TestDelete(DIR, DIR + @"\SubTest3", true))
result = MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults DeleteDirNoSubWithFile()
{
MFTestResults result = MFTestResults.Pass;
createFile = true;
try
{
try
{
Log.Comment("Delete");
TestDelete(DIR);
Log.Comment("Expected IO Exception because of subdir");
result = MFTestResults.Fail;
}
catch (IOException) {/* pass case */}
try
{
Log.Comment("Delete non-recursive");
TestDelete(DIR, false);
Log.Comment("Expected IO Exception because of subdir");
result = MFTestResults.Fail;
}
catch (IOException) {/* pass case */}
Log.Comment("Delete recursive");
if (!TestDelete(DIR, true))
result = MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults DeleteDirSubWithFiles()
{
MFTestResults result = MFTestResults.Pass;
createFile = true;
try
{
Log.Comment("Delete - should throw IOException");
try
{
TestDelete(DIR, DIR + @"\SubFileTest1");
Log.Comment("Expected IO Exception because of subdir");
result = MFTestResults.Fail;
}
catch (IOException) {/* pass case */}
Log.Comment("Delete non-recursive - should throw IOException");
try
{
TestDelete(DIR, DIR + @"\SubFileTest2", false);
Log.Comment("Expected IO Exception because of subdir");
result = MFTestResults.Fail;
}
catch (IOException) {/* pass case */}
Log.Comment("Delete recursive");
if (!TestDelete(DIR, DIR + @"\SubFileTest3", true))
result = MFTestResults.Fail;
Log.Comment("Delete deep recursive");
CreateDir(DIR + @"\SubFileTest4");
CreateDir(DIR + @"\SubFileTest4\Level1a");
CreateDir(DIR + @"\SubFileTest4\Level1b");
CreateDir(DIR + @"\SubFileTest4\Level1a\sub1\deep1");
if (!TestDelete(DIR, DIR + @"\SubFileTest4\Level1a\sub1\deep2", true))
result = MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults DeleteFileInUse()
{
MFTestResults result = MFTestResults.Pass;
createFile = false;
Log.Comment("Try to delete dir with file in use");
string dir = IOTests.Volume.RootDirectory + @"\DeleteFileInUse";
if (!CreateDir(dir))
result = MFTestResults.Fail;
FileStream fs = new FileStream(dir + @"\temp.txt", FileMode.Create);
try
{
Directory.Delete(dir, true);
Log.Exception("Expected IOException because file was in use");
}
catch (IOException) { /*pass case*/ }
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
result = MFTestResults.Fail;
}
Log.Comment("Close file and delete dir");
fs.Close();
try
{
Directory.Delete(dir, true);
if (!VerifyDelete(dir))
result = MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = MFTestResults.Fail;
}
return result;
}
// Need attribute support to finish
[TestMethod]
public MFTestResults DeleteReadOnlyDir()
{
MFTestResults result = MFTestResults.Pass;
createFile = false;
string dir = IOTests.Volume.RootDirectory + @"\DeleteReadOnlyDir";
DirectoryInfo dir2 = Directory.CreateDirectory(dir);
File.SetAttributes(dir, FileAttributes.ReadOnly);
try
{
try
{
Directory.Delete(dir);
Log.Exception("Shouldn't be able to delete ReadOnly directory");
result = MFTestResults.Fail;
}
catch (IOException) { /*pass case*/ }
try
{
Directory.Delete(dir, true);
Log.Exception("Shouldn't be able to delete ReadOnly directory");
result = MFTestResults.Fail;
}
catch (IOException) { /*pass case*/ }
try
{
Directory.Delete(dir, false);
Log.Exception("Shouldn't be able to delete ReadOnly directory");
result = MFTestResults.Fail;
}
catch (IOException) { /*pass case*/ }
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = MFTestResults.Fail;
}
finally
{
File.SetAttributes(dir, FileAttributes.Normal);
}
return result;
}
[TestMethod]
public MFTestResults DeleteHiddenDir()
{
MFTestResults result = MFTestResults.Pass;
createFile = false;
DirectoryInfo dir2;
try
{
string dirName = DIR + @"\HiddenDir1";
dir2 = Directory.CreateDirectory(dirName);
File.SetAttributes(dirName, FileAttributes.Hidden);
Directory.Delete(dirName);
if (!VerifyDelete(dirName))
result = MFTestResults.Fail;
dir2 = Directory.CreateDirectory(dirName);
File.SetAttributes(dirName, FileAttributes.Hidden);
Directory.Delete(dirName, true);
if (!VerifyDelete(dirName))
result = MFTestResults.Fail;
dir2 = Directory.CreateDirectory(dirName);
File.SetAttributes(dirName, FileAttributes.Hidden);
Directory.Delete(dirName, false);
if (!VerifyDelete(dirName))
result = MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = MFTestResults.Fail;
}
return result;
}
#endregion Test Cases
}
}
| 34.09607 | 200 | 0.451908 | [
"Apache-2.0"
] | Sirokujira/MicroFrameworkPK_v4_3 | Test/Platform/Tests/CLR/System/IO/Directory/Delete.cs | 15,616 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModelLayer.ViewModels
{
public class StoreViewModel
{
public Guid LocationId { get; set; } = Guid.NewGuid();
public string Location { get; set; }
public List <StoreViewModel> storesList { get; set; }
public List<InventoryViewModel> StoreInventories { get; set; }
}
}
| 21.095238 | 70 | 0.681716 | [
"MIT"
] | 12142020-dotnet-uta/P1_TravisMartin | ModelLayer/ViewModels/StoreViewModel.cs | 445 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DecalEmitter : MonoBehaviour {
public float lifeTime = 0;
public float lifeTimeRange = 0;
public Vector2 tiling = Vector2.one;
public Vector2 offset = Vector2.zero;
public Vector2 deltaOffset = Vector2.zero;
public bool randomOffset = false;
public Vector2 startScale = Vector2.one;
public Vector2 endScale = Vector2.one;
public float startRot = 0;
public float startRotRange = 0;
public float deltaRot = 0;
public float deltaTex = 0;
public bool randomTex = false;
public List<Color> colors = new List<Color>();
public List<float> alpha = new List<float>();
public List<Texture2D> texs = new List<Texture2D>();
public LayerMask affectedLayers = -1;
public int decalStock = 0;
public float deltaTime = 1;
public PoolManager pool = null;
public string decalName = "EmptyDecal";
float timer = 0;
public bool local = true;
// Use this for initialization
void Start () {
timer = deltaTime;
PoolManager.Add (decalName, Mathf.CeilToInt((float) 1 / deltaTime) + 1);
Debug.Log ("z");
}
// Update is called once per frame
void Update () {
Debug.Log ("n");
if (timer > 0) {
timer -= Time.deltaTime;
Debug.Log ("t " + timer);
} else {
Debug.Log ("m");
if (decalStock > 0){
Debug.Log ("x");
GameObject spawned = null;
DecalTry3 decal = null;
Debug.Log ("a");
if (pool){
spawned = PoolManager.Spawn(decalName);
}else{
spawned = (GameObject) GameObject.Instantiate(Resources.Load(decalName));
}
Debug.Log ("b");
decal = spawned.GetComponent<DecalTry3>();
decal.tiling = tiling;
decal.offset = offset;
decal.deltaOffset = deltaOffset;
decal.startScale = startScale;
decal.endScale = endScale;
decal.deltaRot = deltaRot;
decal.deltaTex = deltaTex;
decal.randomTex = randomTex;
if (texs.Count > 0){
decal.texs = texs;
}
if (colors.Count > 0){
decal.colors = colors;
}
if (alpha.Count > 0){
decal.alpha = alpha;
}
decal.affectedLayers = affectedLayers;
Debug.Log ("c");
decal.lifeTime = lifeTime + Random.Range(-lifeTimeRange, lifeTimeRange);
if (randomTex){
decal.curTex = Random.Range(0, texs.Count - 1);
}
if (randomOffset){
decal.offset += deltaOffset * Random.Range (0, 16);
}
spawned.transform.parent = transform;
spawned.transform.localPosition = Vector3.zero;
spawned.transform.localRotation = Quaternion.Euler(new Vector3(0, 0, startRot + Random.Range(-startRotRange, startRotRange)));
if (!local){
spawned.transform.parent = null;
}
decalStock -= 1;
if (deltaTime > 0){
while (timer <= 0){
timer += deltaTime;
}
}
}else{
Debug.Log ("f");
if(transform.childCount == 0){
Destroy(gameObject);
}
}
}
}
}
| 27.438095 | 130 | 0.652204 | [
"MIT"
] | R-N/NATPunchthrough-MobileGPUBasedVisibility-MovementSync-Test | Assets/Scripts/DecalEmitter.cs | 2,883 | C# |
namespace Raptor.Data.Models
{
public enum PostStatus
{
Draft = 1,
Published = 2,
Inherit = 3
}
public enum PostType
{
Post = 1,
Page = 2,
Revision = 3
}
public enum CustomerType
{
Individual = 1,
Company = 2
}
}
| 13.73913 | 29 | 0.46519 | [
"MIT"
] | humzakhan/RaptorCMS | Raptor.Lib/Raptor.Data/Models/Enums.cs | 318 | C# |
// ˅
using System;
using System.Collections.Generic;
using System.Text;
// ˄
namespace BehavioralPatterns.Iterator
{
public interface IAggregate
{
IIterator Iterator();
// ˅
// ˄
}
}
// ˅
// ˄
| 10.166667 | 37 | 0.540984 | [
"BSD-3-Clause",
"MIT"
] | ploukareas/Design-Patterns | C#/BehavioralPatterns/Iterator/IAggregate.cs | 250 | C# |
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using Json.More;
using Json.Schema;
namespace JsonPatch.Tests.Suite
{
[JsonConverter(typeof(JsonPatchTestJsonConverter))]
public class JsonPatchTest
{
public static readonly JsonSchema TestSchema = new JsonSchemaBuilder()
.Schema(MetaSchemas.Draft201909Id)
.Defs(
("operationType", new JsonSchemaBuilder().Enum(
"add".AsJsonElement(),
"remove".AsJsonElement(),
"replace".AsJsonElement(),
"move".AsJsonElement(),
"copy".AsJsonElement(),
"test".AsJsonElement()
)
)
)
.Type(SchemaValueType.Object)
.Properties(
("doc", true),
("expected", true),
("patch", new JsonSchemaBuilder()
.Type(SchemaValueType.Array)
.Items(new JsonSchemaBuilder()
.Type(SchemaValueType.Object)
.Properties(
("op", new JsonSchemaBuilder().Ref("#/$defs/operationType")),
("path", new JsonSchemaBuilder().Type(SchemaValueType.String)),
("from", new JsonSchemaBuilder().Type(SchemaValueType.String)),
("value", true)
)
.Required("op")
.OneOf(
new JsonSchemaBuilder()
.Properties(("op", new JsonSchemaBuilder().Const("add".AsJsonElement())))
.Required("path", "value"),
new JsonSchemaBuilder()
.Properties(("op", new JsonSchemaBuilder().Const("remove".AsJsonElement())))
.Required("path"),
new JsonSchemaBuilder()
.Properties(("op", new JsonSchemaBuilder().Const("replace".AsJsonElement())))
.Required("path", "value"),
new JsonSchemaBuilder()
.Properties(("op", new JsonSchemaBuilder().Const("move".AsJsonElement())))
.Required("path", "from"),
new JsonSchemaBuilder()
.Properties(("op", new JsonSchemaBuilder().Const("copy".AsJsonElement())))
.Required("path", "from"),
new JsonSchemaBuilder()
.Properties(("op", new JsonSchemaBuilder().Const("test".AsJsonElement())))
.Required("path", "value")
)
)
),
("comment", new JsonSchemaBuilder().Type(SchemaValueType.String)),
("error", new JsonSchemaBuilder().Type(SchemaValueType.String)),
("disabled", new JsonSchemaBuilder().Type(SchemaValueType.Boolean))
);
public JsonElement Doc { get; set; }
public JsonElement ExpectedValue { get; set; }
public string Error { get; set; }
public string Comment { get; set; }
public Json.Patch.JsonPatch Patch { get; set; }
public bool Disabled { get; set; }
public bool ExpectsError => Error != null;
public bool HasExpectedValue => ExpectedValue.ValueKind != JsonValueKind.Undefined;
}
public class JsonPatchTestJsonConverter : JsonConverter<JsonPatchTest>
{
private class Model
{
public JsonElement Doc { get; set; }
public JsonElement Expected { get; set; }
public string Error { get; set; }
public string Comment { get; set; }
public Json.Patch.JsonPatch Patch { get; set; }
public bool Disabled { get; set; }
}
public override JsonPatchTest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var element = JsonSerializer.Deserialize<JsonElement>(ref reader, options);
var results = JsonPatchTest.TestSchema.Validate(element, new ValidationOptions{OutputFormat = OutputFormat.Detailed});
if (results.IsValid)
{
var model = JsonSerializer.Deserialize<Model>(element.GetRawText(), options);
return new JsonPatchTest
{
Doc = model.Doc.ValueKind == JsonValueKind.Undefined ? default : model.Doc.Clone(),
ExpectedValue = model.Expected.ValueKind == JsonValueKind.Undefined ? default : model.Expected.Clone(),
Error = model.Error,
Comment = model.Comment,
Patch = model.Patch,
Disabled = model.Disabled
};
}
return null;
}
public override void Write(Utf8JsonWriter writer, JsonPatchTest value, JsonSerializerOptions options)
{
writer.WriteStartObject();
if (value.Doc.ValueKind != JsonValueKind.Undefined)
{
writer.WritePropertyName("doc");
value.Doc.WriteTo(writer);
}
if (value.ExpectedValue.ValueKind != JsonValueKind.Undefined)
{
writer.WritePropertyName("expected");
value.ExpectedValue.WriteTo(writer);
}
if (value.Error != null)
writer.WriteString("error", value.Error);
if (value.Comment != null)
writer.WriteString("comment", value.Comment);
if (value.Patch != null)
{
writer.WritePropertyName("patch");
JsonSerializer.Serialize(writer, value.Patch, options);
}
if (value.Disabled)
writer.WriteBoolean("disabled", value.Disabled);
writer.WriteEndObject();
}
}
} | 33.070922 | 121 | 0.670598 | [
"MIT"
] | JMPSequeira/json-everything | JsonPatch.Tests/Suite/JsonPatchTest.cs | 4,665 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace VideoRentalApp
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var setting= config.Formatters.JsonFormatter.SerializerSettings;
setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
setting.Formatting=Formatting.Indented;
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| 28.925926 | 84 | 0.650448 | [
"MIT"
] | SaeidAshian/video-rental-stor | VideoRentalApp/App_Start/WebApiConfig.cs | 783 | C# |
using CoronaTracker.Enums;
using CoronaTracker.Instances;
using CoronaTracker.SubForms;
using CoronaTracker.Timers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static CoronaTracker.Enums.EmployeePoseEnum;
namespace CoronaTracker.Utils
{
/// <summary>
/// Util class for program variables
/// </summary>
class ProgramVariables
{
// Instance for main program thread
public static MainProgramThread ProgramThread { get; set; }
// Instance for logged in employee fullname
public static String Fullname { get; set; }
// Instance for logged in employee profile picture url
public static String ProfileURL { get; set; }
// Instance for logged in employee pose
public static EmployeePose Pose { get; set; }
// Instance for logged in employee id
public static int ID { get; set; }
// Instance for this program version
public static String Version { get; set; }
// Instance for refresh database connection timer
public static RefreshConnectionTimer RefreshConnection { get; set; }
// Instance for send discord webhooks
public static DiscordWebhook Webhook { get; set; }
// Instance for cache
public static Dictionary<string, Form> FormCache { get; set; }
// Instance for Covid data cache
public static Dictionary<string, CovidInfo> CovidCache { get; set; }
}
}
| 35.113636 | 76 | 0.685437 | [
"MIT"
] | NiX3r/CoronaTracker | CoronaTracker/Utils/ProgramVariables.cs | 1,547 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace tabbedwithContentView.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomeTabbedPage : TabbedPage
{
public HomeTabbedPage()
{
InitializeComponent();
}
}
} | 20.65 | 53 | 0.709443 | [
"MIT"
] | Leand3k/simpleTabbedPage-usingContentView | tabbedwithContentView/tabbedwithContentView/Views/HomeTabbedPage.xaml.cs | 415 | C# |
namespace _05._Bit_Destroyer
{
using System;
public class BitDestroyer
{
public static void Main()
{
var pos = 6;
var number = 111;
var result = DestroyBitAt(number, pos);
Console.WriteLine(result);
}
private static int DestroyBitAt(int number, int pos)
{
var mask = ~(1 << pos); //Negating the mask mask = ~mask;
return number & mask; //Copying bites
}
}
} | 23.619048 | 69 | 0.516129 | [
"MIT"
] | pirocorp/CSharp-Fundamentals | 17. BITWISE OPERATIONS/Exercises/05. Bit Destroyer/BitDestroyer.cs | 498 | C# |
using System.IO;
namespace UnityVolumeRendering
{
public enum DatasetType
{
Unknown,
Raw,
DICOM
}
public class DatasetImporterUtility
{
public static DatasetType GetDatasetType(string filePath)
{
DatasetType datasetType;
// Check file extension
string extension = Path.GetExtension(filePath);
if (extension == ".dat" || extension == ".raw" || extension == ".vol")
datasetType = DatasetType.Raw;
else if (extension == ".ini")
{
filePath = filePath.Substring(0, filePath.LastIndexOf("."));
datasetType = DatasetType.Raw;
}
else if (extension == ".dicom" || extension == ".dcm")
datasetType = DatasetType.DICOM;
else
datasetType = DatasetType.Unknown;
return datasetType;
}
}
}
| 25.105263 | 82 | 0.525157 | [
"MIT"
] | PerloDaniele/UnityVolumeRendering | Assets/Scripts/Importing/DatasetImporterUtility.cs | 956 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Zbroj_razlika
{ //comment: dodali smo varijablu "a" izvan main-a... ona je sada vani i ne sudjeluje u izvrsavanju programa.
//kako je dodati u main? NEMOJMO TO RADITI, NE ZNAM KAKO IZVEST TJ dodamo nakon Maina slijedece:
// .... Program xx = new Program();
class Program
{
private int a = 5559;
static void Main(string[] args)
{
int a = 0, b = 0;
Console.WriteLine(@"Unesite 1. broj:\n.\no i\n\t\t ..\t. ");
a = int.Parse(Console.ReadLine());
Console.WriteLine("Unesite 2. broj: ");
b = int.Parse(Console.ReadLine());
Console.WriteLine("Zbroj je: {0}", a + b);
Console.WriteLine("Razlika je: {0}", a - b);
Console.WriteLine("Zbroj je: {0}, razlika je: {1}", a + b, a - b); //nula prva radnje, jedinica druga etc
Console.WriteLine("Umnožak je: {0}, kvocijent je: {1}", a * b, (decimal)a / (decimal)b); //moze i float!
Console.WriteLine("Pritisnite tipku za izlaz...");
Console.ReadLine();
}
}
}
| 30.65 | 117 | 0.573409 | [
"MIT"
] | staman1702/AlgebraCSharp2019-1 | ConsoleApp1/Zbroj_razlika/Program.cs | 1,229 | C# |
using Newtonsoft.Json;
namespace Digirati.IIIF.Serialisation
{
public class ToStringJsonConverter : WriteOnlyConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}
}
| 23.615385 | 98 | 0.684039 | [
"MIT"
] | Riksarkivet/iiif-model | Digirati.IIIF/Serialisation/ToStringJsonConverter.cs | 309 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SitecoreCognitiveServices.Foundation.MSSDK.Decision.Models.Personalizer
{
public class RankRequest
{
public List<object> contextFeatures { get; set; }
public List<RankableAction> actions { get; set; }
public List<string> excludedActions { get; set; }
public string eventId { get; set; }
public bool deferActivation { get; set; }
}
} | 30.0625 | 81 | 0.692308 | [
"MIT"
] | markstiles/SitecoreCognitiveServices.Core | src/Foundation/MSSDK/code/Decision/Models/Personalizer/RankRequest.cs | 483 | C# |
using Xunit;
// ReSharper disable once CheckNamespace
namespace NcnnDotNet.Tests.Layers
{
public class ConvolutionDepthWise
{
[Fact]
public void CreateAndDispose()
{
var layer = new NcnnDotNet.Layers.ConvolutionDepthWise();
layer.Dispose();
Assert.True(layer.IsDisposed);
}
}
} | 19.05 | 70 | 0.574803 | [
"MIT"
] | AvenSun/NcnnDotNet | tests/NcnnDotNet.Tests/Layer/Layers/ConvolutionDepthWise.cs | 381 | C# |
using System;
using System.Linq;
namespace _03.EnduranceRally
{
class EnduranceRally
{
static void Main(string[] args)
{
var drivers = Console.ReadLine()
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var zones = Console.ReadLine()
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(double.Parse)
.ToArray();
var checkpoints = Console.ReadLine()
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
foreach (var driver in drivers)
{
double driverFuel = (int)driver[0];
var zone = 0;
for (int i = 0; i < zones.Length; i++)
{
bool isFinished = true;
for (int j = 0; j < checkpoints.Length; j++)
{
if (i == checkpoints[j])
{
isFinished = false;
break;
}
}
if (isFinished)
{
driverFuel -= zones[i];
}
else
{
driverFuel += zones[i];
}
if (driverFuel > 0)
{
zone++;
}
else
{
Console.WriteLine($"{driver} - reached {zone}");
break;
}
}
if (driverFuel > 0)
{
Console.WriteLine($"{driver} - fuel left {driverFuel:f2}");
}
}
}
}
}
| 29.953846 | 79 | 0.344633 | [
"MIT"
] | vpaleshnikov/SoftUni-TechModule | ProgrammingFundamentals/ExamPreparation1/03.EnduranceRally/EnduranceRally.cs | 1,949 | C# |
namespace PetsLostAndFoundSystem.MVC.Models.Reports
{
public class CreateReportOutputModel
{
public CreateReportOutputModel(int reportId)
=> this.ReportId = reportId;
public int ReportId { get; }
}
}
| 22 | 52 | 0.665289 | [
"MIT"
] | Dimitvp/PetsLostAndFoundSystem | PetsLostAndFound/PetsLostAndFoundSystem.MVC/Models/Reports/CreateReportOutputModel.cs | 244 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookAtMouse : MonoBehaviour {
private const int ClampedRotationLimit = 3;
private const int UnClamlpedRotation = 99;
Vector3 cameraPoint;
float angle;
public bool ClampRotation = false;
// Use this for initialization
void Start () {
if(GameManager.instance.DebugMode)
{
if (!Camera.main.orthographic)
{
Debug.LogWarning("This script does not work in the current camera mode, change to ortographic.");
}
}
}
// Update is called once per frame
void Update () {
cameraPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
cameraPoint -= transform.position;
angle = Tools.VelocityToAngle(cameraPoint);
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0, 0, angle), ClampRotation ? ClampedRotationLimit : UnClamlpedRotation);
}
}
| 30.242424 | 166 | 0.681363 | [
"MIT"
] | HUTeachers/HU18 | HU18/Assets/Scripts/LookAtMouse.cs | 1,000 | C# |
using System;
using System.Globalization;
using System.Reflection;
using Jint.Native;
using Jint.Native.Function;
using System.Linq;
namespace Jint.Runtime.Interop
{
/// <summary>
/// Represents a FunctionInstance wrapper around a CLR method. This is used by user to pass
/// custom methods to the engine.
/// </summary>
public sealed class DelegateWrapper : FunctionInstance
{
private readonly Delegate _d;
private readonly bool _delegateContainsParamsArgument;
public DelegateWrapper(Engine engine, Delegate d)
: base(engine, "delegate", null, null, false)
{
_d = d;
Prototype = engine.Function.PrototypeObject;
var parameterInfos = _d.Method.GetParameters();
_delegateContainsParamsArgument = false;
foreach (var p in parameterInfos)
{
if (Attribute.IsDefined(p, typeof(ParamArrayAttribute)))
{
_delegateContainsParamsArgument = true;
break;
}
}
}
public override JsValue Call(JsValue thisObject, JsValue[] jsArguments)
{
var parameterInfos = _d.Method.GetParameters();
#if NETFRAMEWORK
if (parameterInfos.Length > 0 && parameterInfos[0].ParameterType == typeof(System.Runtime.CompilerServices.Closure))
{
var reducedLength = parameterInfos.Length - 1;
var reducedParameterInfos = new ParameterInfo[reducedLength];
Array.Copy(parameterInfos, 1, reducedParameterInfos, 0, reducedLength);
parameterInfos = reducedParameterInfos;
}
#endif
int delegateArgumentsCount = parameterInfos.Length;
int delegateNonParamsArgumentsCount = _delegateContainsParamsArgument ? delegateArgumentsCount - 1 : delegateArgumentsCount;
int jsArgumentsCount = jsArguments.Length;
int jsArgumentsWithoutParamsCount = Math.Min(jsArgumentsCount, delegateNonParamsArgumentsCount);
var parameters = new object[delegateArgumentsCount];
// convert non params parameter to expected types
for (var i = 0; i < jsArgumentsWithoutParamsCount; i++)
{
var parameterType = parameterInfos[i].ParameterType;
if (parameterType == typeof (JsValue))
{
parameters[i] = jsArguments[i];
}
else
{
parameters[i] = Engine.ClrTypeConverter.Convert(
jsArguments[i].ToObject(),
parameterType,
CultureInfo.InvariantCulture);
}
}
// assign null to parameters not provided
for (var i = jsArgumentsWithoutParamsCount; i < delegateNonParamsArgumentsCount; i++)
{
if (parameterInfos[i].ParameterType.IsValueType)
{
parameters[i] = Activator.CreateInstance(parameterInfos[i].ParameterType);
}
else
{
parameters[i] = null;
}
}
// assign params to array and converts each objet to expected type
if(_delegateContainsParamsArgument)
{
int paramsArgumentIndex = delegateArgumentsCount - 1;
int paramsCount = Math.Max(0, jsArgumentsCount - delegateNonParamsArgumentsCount);
object[] paramsParameter = new object[paramsCount];
var paramsParameterType = parameterInfos[paramsArgumentIndex].ParameterType.GetElementType();
for (var i = paramsArgumentIndex; i < jsArgumentsCount; i++)
{
var paramsIndex = i - paramsArgumentIndex;
if (paramsParameterType == typeof(JsValue))
{
paramsParameter[paramsIndex] = jsArguments[i];
}
else
{
paramsParameter[paramsIndex] = Engine.ClrTypeConverter.Convert(
jsArguments[i].ToObject(),
paramsParameterType,
CultureInfo.InvariantCulture);
}
}
parameters[paramsArgumentIndex] = paramsParameter;
}
try
{
return JsValue.FromObject(Engine, _d.DynamicInvoke(parameters));
}
catch (TargetInvocationException exception)
{
var meaningfulException = exception.InnerException ?? exception;
var handler = Engine.Options._ClrExceptionsHandler;
if (handler != null && handler(meaningfulException))
{
ExceptionHelper.ThrowError(_engine, meaningfulException.Message);
}
throw meaningfulException;
}
}
}
}
| 37.554745 | 136 | 0.55277 | [
"BSD-2-Clause"
] | Vinigas/jint | Jint/Runtime/Interop/DelegateWrapper.cs | 5,145 | C# |
using ApiaryMonitoringSystem.BLL.DTO;
using System.Collections.Generic;
namespace ApiaryMonitoringSystem.BLL.Interfaces
{
public interface IMonitoringService
{
ApiaryDTO GetApiary(int? id);
BeeHiveDTO GetBeeHive(int? id);
IEnumerable<BeeHiveDTO> GetBeeHives();
void Dispose();
}
} | 25.076923 | 47 | 0.705521 | [
"MIT"
] | maevemoontea/apiary-monitoring-system | ApiaryMonitoringSystem.BLL/Interfaces/IMonitoringService.cs | 328 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Formats.Red.Records.Enums;
namespace GameEstate.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CJournalCreatureGameplayHintGroup : CJournalContainer
{
public CJournalCreatureGameplayHintGroup(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CJournalCreatureGameplayHintGroup(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 33.565217 | 145 | 0.762953 | [
"MIT"
] | smorey2/GameEstate | src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CJournalCreatureGameplayHintGroup.cs | 772 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("Dato.Modelo")]
[assembly: AssemblyDescription("Demostracion para Reclutadores en CSharp")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dato.Modelo")]
[assembly: AssemblyCopyright("Adolfredo Belizario MIT Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("73794f41-518c-45dd-8664-0316411b3956")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de versión de compilación y de revisión
// mediante el asterisco ('*'), como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 44.189189 | 126 | 0.748012 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | adolfredo87/Sistema-Alquiler-de-VideoJuego | Alquileres/Dato/Dato.Modelo/Properties/AssemblyInfo.cs | 1,653 | C# |
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using DreadZitoTypes;
namespace DreadZitoTools
{
public static class Utils
{
/**
* GetPercentage - Devuelve el porcentage del numero seleccionado
* @num: numero
* @percent: string del porcentage, max 100%
* ---------------------
* Return: porcentaje en float o null si fallo
*/
public static dynamic GetPercentage(float num, string percent)
{
if (percent == "")
return 0;
if (percent[percent.Length - 1] != '%') {
Debug.LogError("GetPercentage: Usage <num> <string number + '%'> ~~~~~~~> example: GetPorcentage(10,\"50%\") = 5");
return null;
}
if (percent == "100%")
return num;
List<char> newStr = new List<char>();
newStr.AddRange(percent);
newStr.RemoveAt(newStr.Count - 1); // Quito el '%'
string strNum = "0." + new string(newStr.ToArray());
float perc = float.Parse(strNum, CultureInfo.InvariantCulture.NumberFormat);
return num * perc;
}
public static Vector3 Vector3Sqrt(Vector3 origin)
{
if (origin.x < 0)
origin.x = (Mathf.Sqrt(Mathf.Abs(origin.x))) * -1;
else
origin.x = Mathf.Sqrt(origin.x);
if (origin.y < 0)
origin.y = (Mathf.Sqrt(Mathf.Abs(origin.y))) * -1;
else
origin.y = Mathf.Sqrt(origin.y);
if (origin.z < 0)
origin.z = (Mathf.Sqrt(Mathf.Abs(origin.z))) * -1;
else
origin.z = Mathf.Sqrt(origin.z);
return origin;
}
/**
* ClearAllCoroutinesFromList - Detiene todas las corrutinas de una lista
* @list: la lista de corrutinas
* @inst: la instancia de MonoBehaviour que tiene esas corroutinas
* -----------------------------------
*/
public static void ClearAllCoroutinesFromList(DreList<Coroutine> list, MonoBehaviour inst)
{
foreach (var item in list) {
inst.StopCoroutine(item);
}
list.Clear();
}
public static void PrintList<T>(List<T> list)
{
foreach (var elem in list) {
Debug.Log(elem);
}
}
public static void PrintListOfLists<T>(List<List<T>> list)
{
foreach (var firstSet in list) {
Debug.Log(">Element==========================");
foreach (var elem in firstSet) {
Debug.Log(elem);
}
Debug.Log("===================================");
}
}
public static string GetLast(this string source, int numberOfChars)
{
if(numberOfChars >= source.Length)
return source;
return source.Substring(source.Length - numberOfChars);
}
}
class MonobehaviourLabRat : MonoBehaviour {}
}
| 31.74 | 131 | 0.488658 | [
"MIT"
] | RaimundoGallino/Pushed-01 | Assets/Resources/Scripts/MyLib/DreadZitoTools.cs | 3,174 | C# |
using UnityEngine;
using System.Collections;
/// <summary>
/// Contract for types that imply cloning.
/// </summary>
public interface ICloneable {
void SelfCleanUp();
//int getIndex(); //ICloneables hold their own index
}
| 19.416667 | 56 | 0.699571 | [
"MIT"
] | Kionius/DacronDuvet | Assets/Scripts/ICloneable.cs | 235 | C# |
//******************************************************************************************************
// PerformanceStatistics.cs - Gbtc
//
// Copyright © 2012, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 02/24/2012 - Stephen C. Wills
// Generated original version of source code.
// 12/20/2012 - Starlynn Danyelle Gilliam
// Modified Header.
//
//******************************************************************************************************
using GSF.Diagnostics;
using GSF.IO;
namespace GSF.TimeSeries.Statistics
{
internal static class PerformanceStatistics
{
// Run-time log used to calculate system run-time
internal static RunTimeLog SystemRunTimeLog;
#region [ CPU Usage ]
private static double GetSystemStatistic_CPUUsage(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.CPUUsage != null)
statistic = perfMon.CPUUsage.LastValue;
}
return statistic;
}
private static double GetSystemStatistic_AverageCPUUsage(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.CPUUsage != null)
statistic = perfMon.CPUUsage.AverageValue;
}
return statistic;
}
#endregion
#region [ Memory Usage ]
private static double GetSystemStatistic_MemoryUsage(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.MemoryUsage != null)
statistic = perfMon.MemoryUsage.LastValue;
}
return statistic;
}
private static double GetSystemStatistic_AverageMemoryUsage(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.MemoryUsage != null)
statistic = perfMon.MemoryUsage.AverageValue;
}
return statistic;
}
#endregion
#region [ Thread Count ]
private static double GetSystemStatistic_ThreadCount(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.ThreadCount != null)
statistic = perfMon.ThreadCount.LastValue;
}
return statistic;
}
private static double GetSystemStatistic_AverageThreadCount(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.ThreadCount != null)
statistic = perfMon.ThreadCount.AverageValue;
}
return statistic;
}
#endregion
#region [ Threading Contention Rate ]
private static double GetSystemStatistic_ThreadingContentionRate(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.ThreadingContentionRate != null)
statistic = perfMon.ThreadingContentionRate.LastValue;
}
return statistic;
}
private static double GetSystemStatistic_AverageThreadingContentionRate(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.ThreadingContentionRate != null)
statistic = perfMon.ThreadingContentionRate.AverageValue;
}
return statistic;
}
#endregion
#region [ IO Usage ]
private static double GetSystemStatistic_IOUsage(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.IOUsage != null)
statistic = perfMon.IOUsage.LastValue;
}
return statistic;
}
private static double GetSystemStatistic_AverageIOUsage(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.IOUsage != null)
statistic = perfMon.IOUsage.AverageValue;
}
return statistic;
}
#endregion
#region [ IP Data Send Rate ]
private static double GetSystemStatistic_IPDataSendRate(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.IPDataSendRate != null)
statistic = perfMon.IPDataSendRate.LastValue;
}
return statistic;
}
// Historical name - function may be used by older database configurations
private static double GetSystemStatistic_DatagramSendRate(object source, string arguments) => GetSystemStatistic_IPDataSendRate(source, arguments);
private static double GetSystemStatistic_AverageIPDataSendRate(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.IPDataSendRate != null)
statistic = perfMon.IPDataSendRate.AverageValue;
}
return statistic;
}
// Historical name - function may be used by older database configurations
private static double GetSystemStatistic_AverageDatagramSendRate(object source, string arguments) => GetSystemStatistic_AverageIPDataSendRate(source, arguments);
#endregion
#region [ IP Data Receive Rate ]
private static double GetSystemStatistic_IPDataReceiveRate(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.IPDataReceiveRate != null)
statistic = perfMon.IPDataReceiveRate.LastValue;
}
return statistic;
}
// Historical name - function may be used by older database configurations
private static double GetSystemStatistic_DatagramReceiveRate(object source, string arguments) => GetSystemStatistic_IPDataReceiveRate(source, arguments);
private static double GetSystemStatistic_AverageIPDataReceiveRate(object source, string arguments)
{
double statistic = double.NaN;
PerformanceMonitor perfMon = source as PerformanceMonitor;
if ((object)perfMon != null)
{
if ((object)perfMon.IPDataReceiveRate != null)
statistic = perfMon.IPDataReceiveRate.AverageValue;
}
return statistic;
}
// Historical name - function may be used by older database configurations
private static double GetSystemStatistic_AverageDatagramReceiveRate(object source, string arguments) => GetSystemStatistic_AverageIPDataReceiveRate(source, arguments);
#endregion
#region [ System Uptime ]
private static double GetSystemStatistic_UpTime(object source, string arguments)
{
double statistic = double.NaN;
if (!(SystemRunTimeLog?.IsDisposed ?? true))
statistic = SystemRunTimeLog.UpTime.TotalSeconds;
return statistic;
}
#endregion
}
}
| 34.236934 | 175 | 0.592611 | [
"MIT"
] | QuarkSoftware/gsf | Source/Libraries/GSF.TimeSeries/Statistics/PerformanceStatistics.cs | 9,829 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.AspNetCore.Hosting.Fakes;
public interface IFactoryService
{
IFakeService FakeService { get; }
int Value { get; }
}
| 23.666667 | 71 | 0.746479 | [
"MIT"
] | 3ejki/aspnetcore | src/Hosting/Hosting/test/Fakes/IFactoryService.cs | 284 | C# |
using System;
using BlueCats.Ble.Serial.BC0xx.Events.Base;
namespace BlueCats.Ble.Serial.BC0xx.Events {
public class DeviceEnteredEvent : EventPdu {
public byte[] BluetoothAddress { get; set; }
public sbyte RSSI { get; set; }
public override void ParsePayload() {
var payloadPos = 0;
if ( PayloadData?.Length >= Protocol.BLUETOOTH_ADDRESS_LEN ) {
BluetoothAddress = new byte[ Protocol.BLUETOOTH_ADDRESS_LEN ];
Buffer.BlockCopy( PayloadData, payloadPos, BluetoothAddress, 0, Protocol.BLUETOOTH_ADDRESS_LEN );
payloadPos += Protocol.BLUETOOTH_ADDRESS_LEN;
}
if ( PayloadData?.Length >= ( payloadPos + 1 ) ) {
RSSI = (sbyte) PayloadData[ payloadPos ];
payloadPos += 1;
}
}
}
} | 31.888889 | 113 | 0.593496 | [
"MIT"
] | bluecats/bluecats-csharp-ble-serial | BlueCats.Ble.Serial/BC0xx/Events/DeviceEnteredEvent.cs | 863 | C# |
using SisenseApiClient.Authenticators;
using SisenseApiClient.Services.ElastiCubes;
using SisenseApiClient.Tests.Authenticators;
using SisenseApiClient.Tests.Utils.HttpClient;
using SisenseApiClient.Utils.HttpClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace SisenseApiClient.Tests.Services.ElastiCubes.ElastiCubeServiceTests.v1_0
{
public class GetCustomTablesAsyncTests
{
[Fact]
public async Task WhenGettingCustomTables_ShouldReturnThemWithTheCorrectInformation()
{
// Arrange
IHttpClient httpClient = new FakeHttpClient(responseMessageToReturn: CreateResponse());
IAuthenticator authenticator = new FakeAuthenticator();
var service = new ElastiCubesService("", httpClient, authenticator);
// Act
var result = await service.GetCustomTablesAsync("localhost", "mycube");
// Assert
Assert.Equal(2, result.Count());
Assert.Equal("SELECT id, name \nFROM [users]", result.First().QueryString);
Assert.Equal("users", result.First().TableName);
}
private HttpResponseMessage CreateResponse()
{
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(
@"{
""tables"": [
{
""queryString"": ""SELECT id, name \nFROM [users]"",
""tableName"": ""users""
},
{
""queryString"": ""SELECT id, name, price, type \nFROM products\nWHERE id IN (2,7)"",
""tableName"": ""products""
}
]
}")
};
}
}
}
| 36.745455 | 121 | 0.531915 | [
"MIT"
] | scott-baxter/sisense-api-client-csharp | SisenseApiClient.Tests/Services/ElastiCubes/ElastiCubeServiceTests/v1.0/GetCustomTablesAsyncTests.cs | 2,023 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal partial class ExplicitInterfaceMemberCompletionProvider : CommonCompletionProvider
{
private const string InsertionTextOnOpenParen = nameof(InsertionTextOnOpenParen);
private static readonly SymbolDisplayFormat s_signatureDisplayFormat =
new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options)
{
return text[characterPosition] == '.';
}
public override async Task ProvideCompletionsAsync(CompletionContext context)
{
try
{
var document = context.Document;
var position = context.Position;
var options = context.Options;
var cancellationToken = context.CancellationToken;
var span = new TextSpan(position, length: 0);
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var syntaxTree = semanticModel.SyntaxTree;
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
if (syntaxFacts.IsInNonUserCode(syntaxTree, position, cancellationToken) ||
semanticFacts.IsPreProcessorDirectiveContext(semanticModel, position, cancellationToken))
{
return;
}
if (!syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken))
{
return;
}
var node = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
.GetPreviousTokenIfTouchingWord(position)
.Parent;
if (node.Kind() != SyntaxKind.ExplicitInterfaceSpecifier)
{
return;
}
// Bind the interface name which is to the left of the dot
var name = ((ExplicitInterfaceSpecifierSyntax)node).Name;
var symbol = semanticModel.GetSymbolInfo(name, cancellationToken).Symbol as ITypeSymbol;
if (symbol?.TypeKind != TypeKind.Interface)
{
return;
}
var members = symbol.GetMembers();
// We're going to create a entry for each one, including the signature
var namePosition = name.SpanStart;
var text = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
foreach (var member in members)
{
if (member.IsAccessor())
{
continue;
}
var displayText = member.ToMinimalDisplayString(
semanticModel, namePosition, s_signatureDisplayFormat);
var insertionText = displayText;
var item = SymbolCompletionItem.CreateWithSymbolId(
displayText,
insertionText: insertionText,
symbols: ImmutableArray.Create(member),
contextPosition: position,
rules: CompletionItemRules.Default);
item = item.AddProperty(InsertionTextOnOpenParen, member.Name);
context.AddItem(item);
}
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
{
// nop
}
}
protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
=> SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken);
public override Task<TextChange?> GetTextChangeAsync(
Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken)
{
if (ch == '(')
{
if (selectedItem.Properties.TryGetValue(InsertionTextOnOpenParen, out var insertionText))
{
return Task.FromResult<TextChange?>(new TextChange(selectedItem.Span, insertionText));
}
}
return Task.FromResult<TextChange?>(new TextChange(selectedItem.Span, selectedItem.DisplayText));
}
}
}
| 42.798561 | 161 | 0.614053 | [
"Apache-2.0"
] | Mongooz/roslyn | src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceMemberCompletionProvider.cs | 5,951 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConcurrentSharp.Tests
{
[TestClass]
public class AsyncThrottleTests
{
[TestMethod]
public async Task Throttle_ExecuteAllAsyncAction_Test()
{
var items = new List<int>(10);
items.Add(1);
items.Add(2);
items.Add(3);
items.Add(4);
items.Add(5);
items.Add(6);
items.Add(7);
items.Add(8);
items.Add(9);
items.Add(10);
int tasksExecuted = 0;
using (var t = new AsyncThrottle(4))
{
await t.ExecuteAllAsync(items, async (i) =>
{
await Task.Delay(100).ConfigureAwait(false);
System.Threading.Interlocked.Increment(ref tasksExecuted);
});
Assert.AreEqual(10, tasksExecuted);
}
}
[TestMethod]
public async Task Throttle_ExecuteAllAsyncFunc_Test()
{
var items = new List<int>(10);
items.Add(1);
items.Add(2);
items.Add(3);
items.Add(4);
items.Add(5);
items.Add(6);
items.Add(7);
items.Add(8);
items.Add(9);
items.Add(10);
using (var t = new AsyncThrottle(4))
{
var results = await t.ExecuteAllAsync<int, int>(items, async (i) =>
{
await Task.Delay(100).ConfigureAwait(false);
return ++i;
});
Assert.AreEqual(10, results.Count());
int oi = 1;
foreach (var i in results)
{
Assert.AreEqual(oi + 1, i.Result);
oi++;
}
}
}
}
} | 19.72 | 71 | 0.63286 | [
"MIT"
] | Yortw/ConcurrentSharp | src/ConcurrentSharp.Tests/AsyncThrottleTests.cs | 1,479 | C# |
/*********************************************
作者:曹旭升
QQ:279060597
访问博客了解详细介绍及更多内容:
http://blog.shengxunwei.com
**********************************************/
using System;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.Manageability.Properties;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability.Adm;
namespace Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.Manageability
{
public class CacheStorageDataManageabilityProvider
: ConfigurationElementManageabilityProviderBase<CacheStorageData>
{
public CacheStorageDataManageabilityProvider()
{
CacheStorageDataWmiMapper.RegisterWmiTypes();
}
protected override void AddAdministrativeTemplateDirectives(AdmContentBuilder contentBuilder,
CacheStorageData configurationObject,
IConfigurationSource configurationSource,
String elementPolicyKeyName)
{
AddElementAdministrativeTemplateParts(contentBuilder,
configurationObject,
configurationSource,
elementPolicyKeyName);
}
protected override void AddElementAdministrativeTemplateParts(AdmContentBuilder contentBuilder,
CacheStorageData configurationObject,
IConfigurationSource configurationSource,
String elementPolicyKeyName)
{
contentBuilder.AddTextPart(Resources.NullBackingStoreNoSettingsPartName);
}
protected override string ElementPolicyNameTemplate
{
get
{
return null;
}
}
protected override void OverrideWithGroupPolicies(CacheStorageData configurationObject, IRegistryKey policyKey)
{
}
protected override void GenerateWmiObjects(CacheStorageData configurationObject,
ICollection<ConfigurationSetting> wmiSettings)
{
CacheStorageDataWmiMapper.GenerateWmiObjects(configurationObject, wmiSettings);
}
}
}
| 36.803571 | 120 | 0.755459 | [
"MIT"
] | ckalvin-hub/Sheng.Winform.IDE | SourceCode/Source/EnterpriseLibrary/Caching/Configuration/Manageability/CacheStorageDataManageabilityProvider.cs | 2,109 | C# |
using System;
using System.IO;
using System.Net;
using EventStore.Common.Utils;
namespace EventStore.Transport.Http.Client
{
public class ClientOperationState
{
public readonly HttpWebRequest Request;
public readonly Action<HttpResponse> OnSuccess;
public readonly Action<Exception> OnError;
public HttpResponse Response { get; set; }
public Stream InputStream { get; set; }
public Stream OutputStream { get; set; }
public ClientOperationState(HttpWebRequest request, Action<HttpResponse> onSuccess, Action<Exception> onError)
{
Ensure.NotNull(request, "request");
Ensure.NotNull(onSuccess, "onSuccess");
Ensure.NotNull(onError, "onError");
Request = request;
OnSuccess = onSuccess;
OnError = onError;
}
public void DisposeIOStreams()
{
IOStreams.SafelyDispose(InputStream, OutputStream);
}
}
} | 28.342857 | 118 | 0.639113 | [
"Apache-2.0"
] | bartelink/EventStore | src/EventStore.Transport.Http/Client/ClientOperationState.cs | 992 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace Microsoft.Toolkit.Uwp.Helpers
{
#pragma warning disable CS1584 // XML comment has syntactically incorrect cref attribute
#pragma warning disable CS1658 // Warning is overriding an error
/// <summary>
/// Provides an enumerable way to look at query string parameters from a Uri
/// </summary>
/// <seealso cref="System.Collections.ObjectModel.Collection{System.Collections.Generic.KeyValuePair{string, string}}" />
public class QueryParameterCollection : Collection<KeyValuePair<string, string>>
#pragma warning restore CS1658 // Warning is overriding an error
#pragma warning restore CS1584 // XML comment has syntactically incorrect cref attribute
{
private static IList<KeyValuePair<string, string>> CreatePairsFromUri(string uri)
{
var queryStartPosition = uri?.IndexOf('?');
if (queryStartPosition.GetValueOrDefault(-1) != -1)
{ // Uri has a query string
var queryString = uri.Substring(queryStartPosition.Value + 1);
return queryString.Split('&')
.Select(param =>
{
var kvp = param.Split('=');
return new KeyValuePair<string, string>(System.Net.WebUtility.UrlDecode(kvp[0]), System.Net.WebUtility.UrlDecode(kvp[1]));
}).ToList();
}
else
{
return new List<KeyValuePair<string, string>>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="QueryParameterCollection"/> class.
/// </summary>
/// <param name="uri">The URI.</param>
public QueryParameterCollection(Uri uri)
: this(uri?.OriginalString)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="QueryParameterCollection"/> class.
/// </summary>
/// <param name="uri">The URI.</param>
public QueryParameterCollection(string uri)
: base(CreatePairsFromUri(uri))
{
}
}
}
| 40.133333 | 146 | 0.620432 | [
"MIT"
] | 47-studio-org/WindowsCommunityToolkit | Microsoft.Toolkit.Uwp/Helpers/DeepLinkParser/QueryParameterCollection.cs | 2,408 | C# |
using Mapster;
using Entity = Pims.Dal.Entities;
using Model = Pims.Api.Areas.Keycloak.Models.User;
namespace Pims.Api.Areas.Keycloak.Mapping.User
{
public class AccessRequestRoleMap : IRegister
{
public void Register(TypeAdapterConfig config)
{
config.NewConfig<Entity.AccessRequestRole, Model.AccessRequestRoleModel>()
.Map(dest => dest.Id, src => src.RoleId)
.Map(dest => dest.Name, src => src.Role == null ? null : src.Role.Name)
.Inherits<Entity.BaseAppEntity, Api.Models.BaseAppModel>();
config.NewConfig<Model.AccessRequestRoleModel, Entity.AccessRequestRole>()
.Map(dest => dest.RoleId, src => src.Id)
.Map(dest => dest.Role, src => new Entity.Role()
{
Id = src.Id,
Name = src.Name
})
.Inherits<Api.Models.BaseAppModel, Entity.BaseAppEntity>();
}
}
}
| 36.62963 | 87 | 0.574317 | [
"Apache-2.0"
] | stairaku/PSP | backend/api/Areas/Keycloak/Mapping/User/AccessRequestRoleMap.cs | 989 | C# |
namespace FestivalManager.Entities.Instruments
{
public class Guitar : Instrument
{
private const int GuitarRepairAmountConst = 60;
protected override int RepairAmount => GuitarRepairAmountConst;
}
}
| 21 | 71 | 0.714286 | [
"MIT"
] | DareDevil23/OOP-Advanced | Festival Manager/FestivalManager/Entities/Instruments/Guitar.cs | 233 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
namespace Thunkerator
{
// Parse type replacement section for normal types
// Parse type replacement section for return value types
public static class StringExtensions
{
public static string Canonicalize(this string current)
{
string untrimmed = "";
while (untrimmed != current)
{
untrimmed = current;
current = current.Replace(" *", "*");
current = current.Replace("* ", "*");
current = current.Replace(" ,", ",");
current = current.Replace(", ", ",");
current = current.Replace(" ", " ");
current = current.Replace("\t", " ");
}
return current.Trim();
}
}
class TypeReplacement
{
public TypeReplacement(string line)
{
string[] typenames = line.Split(',');
if ((typenames.Length < 1) || (typenames.Length > 3))
{
throw new Exception("Wrong number of type name entries");
}
ThunkTypeName = typenames[0].Canonicalize();
if (typenames.Length > 1 && !string.IsNullOrWhiteSpace(typenames[1]))
{
ManagedTypeName = typenames[1].Canonicalize();
}
else
{
ManagedTypeName = ThunkTypeName;
}
if (typenames.Length > 2)
{
NativeTypeName = typenames[2].Canonicalize();
}
else
{
NativeTypeName = ThunkTypeName;
}
}
public readonly string ThunkTypeName;
public readonly string NativeTypeName;
public readonly string ManagedTypeName;
}
class Parameter
{
public Parameter(string name, TypeReplacement type)
{
Type = type;
Name = name;
if (name.StartsWith("*"))
throw new Exception("Names not allowed to start with *");
}
public readonly string Name;
public readonly TypeReplacement Type;
}
class FunctionDecl
{
public FunctionDecl(string line, Dictionary<string, TypeReplacement> ThunkReturnTypes, Dictionary<string, TypeReplacement> ThunkTypes)
{
if (line.Contains("[ManualNativeWrapper]"))
{
ManualNativeWrapper = true;
line = line.Replace("[ManualNativeWrapper]", string.Empty);
}
if (line.Contains("[ReturnAsParm]"))
{
ReturnAsParm = true;
line = line.Replace("[ReturnAsParm]", string.Empty);
}
int indexOfOpenParen = line.IndexOf('(');
int indexOfCloseParen = line.IndexOf(')');
string returnTypeAndFunctionName = line.Substring(0, indexOfOpenParen).Canonicalize();
int indexOfLastWhitespaceInReturnTypeAndFunctionName = returnTypeAndFunctionName.LastIndexOfAny(new char[] { ' ', '*' });
FunctionName = returnTypeAndFunctionName.Substring(indexOfLastWhitespaceInReturnTypeAndFunctionName + 1).Canonicalize();
if (FunctionName.StartsWith("*"))
throw new Exception("Names not allowed to start with *");
string returnType = returnTypeAndFunctionName.Substring(0, indexOfLastWhitespaceInReturnTypeAndFunctionName + 1).Canonicalize();
if (!ThunkReturnTypes.TryGetValue(returnType, out ReturnType))
{
throw new Exception(String.Format("Type {0} unknown", returnType));
}
string parameterList = line.Substring(indexOfOpenParen + 1, indexOfCloseParen - indexOfOpenParen - 1).Canonicalize();
string[] parametersString = parameterList.Length == 0 ? new string[0] : parameterList.Split(',');
List<Parameter> parameters = new List<Parameter>();
foreach (string parameterString in parametersString)
{
int indexOfLastWhitespaceInParameter = parameterString.LastIndexOfAny(new char[] { ' ', '*' });
string paramName = parameterString.Substring(indexOfLastWhitespaceInParameter + 1).Canonicalize();
string paramType = parameterString.Substring(0, indexOfLastWhitespaceInParameter + 1).Canonicalize();
TypeReplacement tr;
if (!ThunkTypes.TryGetValue(paramType, out tr))
{
throw new Exception(String.Format("Type {0} unknown", paramType));
}
parameters.Add(new Parameter(paramName, tr));
}
Parameters = parameters.ToArray();
}
public readonly string FunctionName;
public readonly TypeReplacement ReturnType;
public readonly Parameter[] Parameters;
public readonly bool ManualNativeWrapper = false;
public readonly bool ReturnAsParm = false;
}
class Program
{
enum ParseMode
{
RETURNTYPES,
NORMALTYPES,
FUNCTIONS,
IFDEFING
}
static IEnumerable<FunctionDecl> ParseInput(TextReader tr)
{
Dictionary<string, TypeReplacement> ThunkReturnTypes = new Dictionary<string, TypeReplacement>();
Dictionary<string, TypeReplacement> ThunkTypes = new Dictionary<string, TypeReplacement>();
ParseMode currentParseMode = ParseMode.FUNCTIONS;
ParseMode oldParseMode = ParseMode.FUNCTIONS;
List<FunctionDecl> functions = new List<FunctionDecl>();
int currentLineIndex = 1;
for (string currentLine = tr.ReadLine(); currentLine != null; currentLine = tr.ReadLine(), currentLineIndex++)
{
try
{
if (currentLine.Length == 0)
{
continue; // Its an empty line, ignore
}
if (currentLine[0] == ';')
{
continue; // Its a comment
}
if (currentLine == "RETURNTYPES")
{
currentParseMode = ParseMode.RETURNTYPES;
continue;
}
if (currentLine == "NORMALTYPES")
{
currentParseMode = ParseMode.NORMALTYPES;
continue;
}
if (currentLine == "FUNCTIONS")
{
currentParseMode = ParseMode.FUNCTIONS;
continue;
}
if (currentLine == "#endif")
{
currentParseMode = oldParseMode;
continue;
}
if (currentLine.StartsWith("#if"))
{
oldParseMode = currentParseMode;
currentParseMode = ParseMode.IFDEFING;
}
if (currentParseMode == ParseMode.IFDEFING)
{
continue;
}
switch (currentParseMode)
{
case ParseMode.NORMALTYPES:
case ParseMode.RETURNTYPES:
TypeReplacement t = new TypeReplacement(currentLine);
if (currentParseMode == ParseMode.NORMALTYPES)
{
ThunkTypes.Add(t.ThunkTypeName, t);
ThunkReturnTypes.Add(t.ThunkTypeName, t);
}
if (currentParseMode == ParseMode.RETURNTYPES)
{
ThunkReturnTypes[t.ThunkTypeName] = t;
}
break;
case ParseMode.FUNCTIONS:
functions.Add(new FunctionDecl(currentLine, ThunkReturnTypes, ThunkTypes));
break;
}
}
catch (Exception e)
{
Console.Error.WriteLine("Error parsing line {0} : {1}", currentLineIndex, e.Message);
}
}
return functions.AsReadOnly();
}
static void WriteManagedThunkInterface(TextWriter tr, IEnumerable<FunctionDecl> functionData)
{
// Write header
tr.Write(@"
// 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.
// DO NOT EDIT THIS FILE! It IS AUTOGENERATED
using System;
using System.Runtime.InteropServices;
namespace Internal.JitInterface
{
unsafe partial class CorInfoImpl
{
");
#if false
foreach (FunctionDecl decl in functionData)
{
string returnType = decl.ReturnType.ManagedTypeName;
tr.Write(" " + returnType + " " + decl.FunctionName + "(");
tr.Write("IntPtr thisHandle");
foreach (Parameter param in decl.Parameters)
{
tr.Write(", ");
tr.Write(param.Type.ManagedTypeName + " " + param.Name);
}
tr.WriteLine(")");
tr.WriteLine(" { throw new NotImplementedException(); }");
}
tr.WriteLine();
#endif
foreach (FunctionDecl decl in functionData)
{
tr.WriteLine(" [UnmanagedFunctionPointerAttribute(default(CallingConvention))]");
string returnType = decl.ReturnAsParm ? "void" : decl.ReturnType.ManagedTypeName;
int marshalAs = returnType.LastIndexOf(']');
string returnTypeWithDelegate = returnType.Insert((marshalAs != -1) ? (marshalAs + 1) : 0, "delegate ");
tr.Write(" " + returnTypeWithDelegate + " " + "__" + decl.FunctionName + "(");
tr.Write("IntPtr _this");
tr.Write(", IntPtr* ppException");
if (decl.ReturnAsParm)
{
tr.Write(", out " + decl.ReturnType.ManagedTypeName + " _return");
}
foreach (Parameter param in decl.Parameters)
{
tr.Write(", ");
tr.Write(param.Type.ManagedTypeName + " " + param.Name);
}
tr.WriteLine(");");
}
tr.WriteLine();
foreach (FunctionDecl decl in functionData)
{
string returnType = decl.ReturnAsParm ? "void" : decl.ReturnType.ManagedTypeName;
int marshalAs = returnType.LastIndexOf(']');
string returnTypeWithStatic = returnType.Insert((marshalAs != -1) ? (marshalAs + 1) : 0, "static ");
tr.Write(" " + returnTypeWithStatic + " " + "_" + decl.FunctionName + "(");
tr.Write("IntPtr thisHandle");
tr.Write(", IntPtr* ppException");
if (decl.ReturnAsParm)
{
tr.Write(", out " + decl.ReturnType.ManagedTypeName + " _return");
}
foreach (Parameter param in decl.Parameters)
{
tr.Write(", ");
tr.Write(param.Type.ManagedTypeName + " " + param.Name);
}
tr.Write(@")
{
var _this = GetThis(thisHandle);
try
{
");
bool isVoid = decl.ReturnAsParm || decl.ReturnType.ManagedTypeName == "void";
tr.Write(" " + (isVoid ? "" : "return ") + "_this." + decl.FunctionName + "(");
bool isFirst = true;
if (decl.ReturnAsParm)
{
tr.Write("out _return");
isFirst = false;
}
foreach (Parameter param in decl.Parameters)
{
if (isFirst)
{
isFirst = false;
}
else
{
tr.Write(", ");
}
if (param.Type.ManagedTypeName.Contains("ref "))
{
tr.Write("ref ");
}
tr.Write(param.Name);
}
tr.Write(");");
tr.Write(@"
}
catch (Exception ex)
{
*ppException = _this.AllocException(ex);
");
if (!isVoid)
{
string retunTypeWithoutMarshalAs = marshalAs == -1 ? returnType : returnType.Substring(marshalAs + 1);
tr.WriteLine(" return default(" + retunTypeWithoutMarshalAs + ");");
}
else if (decl.ReturnAsParm)
{
tr.WriteLine(" _return = default(" + decl.ReturnType.ManagedTypeName + ");");
}
tr.WriteLine(@" }");
tr.WriteLine(" }");
tr.WriteLine();
}
int total = functionData.Count();
tr.WriteLine(@"
static IntPtr GetUnmanagedCallbacks(out Object keepAlive)
{
IntPtr * callbacks = (IntPtr *)Marshal.AllocCoTaskMem(sizeof(IntPtr) * " + total + @");
Object[] delegates = new Object[" + total + @"];
");
int index = 0;
foreach (FunctionDecl decl in functionData)
{
tr.WriteLine(" var d" + index + " = new " + "__" + decl.FunctionName + "(" + "_" + decl.FunctionName + ");");
tr.WriteLine(" callbacks[" + index + "] = Marshal.GetFunctionPointerForDelegate(d" + index + ");");
tr.WriteLine(" delegates[" + index + "] = d" + index + ";");
index++;
}
tr.WriteLine(@"
keepAlive = delegates;
return (IntPtr)callbacks;
}
}
}
");
}
static void WriteNativeWrapperInterface(TextWriter tw, IEnumerable<FunctionDecl> functionData)
{
tw.Write(@"
// 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.
// DO NOT EDIT THIS FILE! It IS AUTOGENERATED
#include ""corinfoexception.h""
struct CORINFO_LOOKUP_KIND;
struct JitInterfaceCallbacks
{
");
foreach (FunctionDecl decl in functionData)
{
string returnType = decl.ReturnAsParm ? "void" : decl.ReturnType.NativeTypeName;
tw.Write(" " + returnType + " (* " + decl.FunctionName + ")(");
tw.Write("void * thisHandle");
tw.Write(", CorInfoException** ppException");
if (decl.ReturnAsParm)
{
tw.Write(", " + decl.ReturnType.NativeTypeName + "* _return");
}
foreach (Parameter param in decl.Parameters)
{
tw.Write(", ");
tw.Write(param.Type.NativeTypeName + " " + param.Name);
}
tw.WriteLine(");");
}
tw.Write(@"
};
class JitInterfaceWrapper
{
void * _thisHandle;
JitInterfaceCallbacks * _callbacks;
public:
JitInterfaceWrapper(void * thisHandle, void ** callbacks)
: _thisHandle(thisHandle), _callbacks((JitInterfaceCallbacks *)callbacks)
{
}
");
foreach (FunctionDecl decl in functionData)
{
tw.Write(" virtual " + decl.ReturnType.NativeTypeName + " " + decl.FunctionName + "(");
bool isFirst = true;
foreach (Parameter param in decl.Parameters)
{
if (isFirst)
{
isFirst = false;
}
else
{
tw.Write(", ");
}
tw.Write(param.Type.NativeTypeName + " " + param.Name);
}
tw.Write(')');
if (decl.ManualNativeWrapper)
{
tw.WriteLine(';');
continue;
}
tw.Write(@"
{
CorInfoException* pException = nullptr;
");
if (decl.ReturnType.NativeTypeName != "void")
{
tw.Write(decl.ReturnType.NativeTypeName + " _ret = ");
}
tw.Write("_callbacks->" + decl.FunctionName + "(_thisHandle, &pException");
foreach (Parameter param in decl.Parameters)
{
tw.Write(", " + param.Name);
}
tw.Write(@");
if (pException != nullptr)
throw pException;
");
if (decl.ReturnType.NativeTypeName != "void")
{
tw.WriteLine(" return _ret;");
}
tw.WriteLine(" }");
tw.WriteLine();
}
tw.WriteLine("};");
}
static void Main(string[] args)
{
IEnumerable<FunctionDecl> functions = ParseInput(new StreamReader(args[0]));
using (TextWriter tw = new StreamWriter(args[1]))
{
Console.WriteLine("Generating {0}", args[1]);
WriteManagedThunkInterface(tw, functions);
}
using (TextWriter tw = new StreamWriter(args[2]))
{
Console.WriteLine("Generating {0}", args[2]);
WriteNativeWrapperInterface(tw, functions);
}
}
}
}
| 36.723529 | 142 | 0.486999 | [
"MIT"
] | 6opuc/coreclr | src/tools/crossgen2/Common/JitInterface/ThunkGenerator/Program.cs | 18,731 | C# |
#region LICENSE
/*
MIT License
Copyright (c) 2018 Software free CAS Sharp
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CASSharp.Core.Exprs;
namespace CASSharp.Core.CAS
{
abstract public class VarsScope : IVars
{
public IVars Vars { get; private set; }
public IVars Parent { get; private set; }
public abstract IEnumerable<string> NameVars { get; }
public abstract void Clear();
public abstract bool ExistVar(string nvar);
public abstract Expr Get(string nvar);
public abstract void Set(string nvar, Expr e);
public IVars Create(IVars argParent, IVars argVars)
{
if (argParent == null && argVars != null)
return argVars;
if (argVars == null && argParent != null)
return argParent;
var pVars = NewVars();
pVars.Parent = argParent;
pVars.Vars = argVars;
return pVars;
}
abstract protected VarsScope NewVars();
}
}
| 33.030303 | 82 | 0.681193 | [
"MIT"
] | bugbit/CASSharp | CASSharp/CASSharp.Core/CAS/VarsScope.cs | 2,182 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리의 일반 정보는 다음 특성 집합을 통해
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
// 이 특성 값을 변경하십시오.
[assembly: AssemblyTitle("HomePage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HomePage")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
//COM 표시되지 않습니다.
// COM에서 이 어셈블리의 형식에 액세스하려면 해당 형식에 대해 ComVisible 특성을 true로 설정하십시오.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("88933982-31a1-450a-9bfc-ee42d2824436")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.:
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 버전이 자동으로
// 지정되도록 할 수 있습니다:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 28.027778 | 66 | 0.702676 | [
"MIT"
] | lbs1206/.Net_WebBoard_Mvc | HomePage/HomePage/Properties/AssemblyInfo.cs | 1,446 | C# |
#region Usings
using System;
using ModInstallation.Annotations;
#endregion
namespace ModInstallation.Exceptions
{
public class FileVerificationFailedException : Exception
{
public FileVerificationFailedException([NotNull] string filename) : base(string.Format("Failed to verify file '{0}'!", filename))
{
}
}
}
| 20.647059 | 137 | 0.709402 | [
"MIT"
] | asarium/FSOLauncher | Libraries/ModInstallation/Exceptions/FileVerificationFailedException.cs | 353 | C# |
using System;
using GSF.IO;
using GSF.Snap.Types;
namespace openHistorian.Scada.AMI
{
public class AmiKey
: TimestampPointIDBase<AmiKey>
{
public ulong CollectedTime;
public int TableId;
public ulong JobRunTime
{
get => Timestamp;
set => Timestamp = value;
}
public ulong DeviceCode
{
get => PointID;
set => PointID = value;
}
public DateTime JobRunTimeAsDate
{
get => new DateTime((long)Timestamp);
set => Timestamp = (ulong)value.Ticks;
}
public DateTime CollectedTimeAsDate
{
get => new DateTime((long)CollectedTime);
set => CollectedTime = (ulong)value.Ticks;
}
public override Guid GenericTypeGuid =>
// {CA57E35C-BCBD-4E95-89F4-419A023FF09E}
new Guid(0xca57e35c, 0xbcbd, 0x4e95, 0x89, 0xf4, 0x41, 0x9a, 0x02, 0x3f, 0xf0, 0x9e);
public override int Size => 28;
/// <summary>
/// Sets all of the values in this class to their minimum value
/// </summary>
public override void SetMin()
{
Timestamp = ulong.MinValue;
PointID = ulong.MinValue;
TableId = int.MinValue;
CollectedTime = ulong.MinValue;
}
/// <summary>
/// Sets all of the values in this class to their maximum value
/// </summary>
public override void SetMax()
{
Timestamp = ulong.MaxValue;
PointID = ulong.MaxValue;
TableId = int.MaxValue;
CollectedTime = ulong.MaxValue;
}
/// <summary>
/// Sets the key to the default values.
/// </summary>
public override void Clear()
{
//SetMin();
Timestamp = 0;
PointID = 0;
TableId = 0;
CollectedTime = 0;
}
public override void Read(BinaryStreamBase stream)
{
Timestamp = stream.ReadUInt64();
PointID = stream.ReadUInt64();
TableId = stream.ReadInt32();
CollectedTime = stream.ReadUInt64();
}
public override void Write(BinaryStreamBase stream)
{
stream.Write(Timestamp);
stream.Write(PointID);
stream.Write(TableId);
stream.Write(CollectedTime);
}
public override void CopyTo(AmiKey destination)
{
destination.Timestamp = Timestamp;
destination.PointID = PointID;
destination.TableId = TableId;
destination.CollectedTime = CollectedTime;
}
/// <summary>
/// Compares the current instance to <see cref="other"/>.
/// </summary>
/// <param name="other">the key to compare to</param>
/// <returns></returns>
public override int CompareTo(AmiKey other)
{
if (Timestamp < other.Timestamp)
return -1;
if (Timestamp > other.Timestamp)
return 1;
if (PointID < other.PointID)
return -1;
if (PointID > other.PointID)
return 1;
if (TableId < other.TableId)
return -1;
if (TableId > other.TableId)
return 1;
if (CollectedTime < other.CollectedTime)
return -1;
if (CollectedTime > other.CollectedTime)
return 1;
return 0;
}
#region [ Optional Overrides ]
// Read(byte*)
// Write(byte*)
// IsLessThan(T)
// IsEqualTo(T)
// IsGreaterThan(T)
// IsLessThanOrEqualTo(T)
// IsBetween(T,T)
public override unsafe void Read(byte* stream)
{
Timestamp = *(ulong*)stream;
PointID = *(ulong*)(stream + 8);
TableId = *(int*)(stream + 16);
CollectedTime = *(ulong*)(stream + 20);
}
public override unsafe void Write(byte* stream)
{
*(ulong*)stream = Timestamp;
*(ulong*)(stream + 8) = PointID;
*(int*)(stream + 16) = TableId;
*(ulong*)(stream + 20) = CollectedTime;
}
public override bool IsLessThan(AmiKey right)
{
if (Timestamp != right.Timestamp)
return Timestamp < right.Timestamp;
if (PointID != right.PointID)
return PointID < right.PointID;
if (TableId != right.TableId)
return TableId < right.TableId;
return CollectedTime < right.CollectedTime;
}
public override bool IsEqualTo(AmiKey right)
{
return Timestamp == right.Timestamp && PointID == right.PointID &&
TableId == right.TableId && CollectedTime == right.CollectedTime;
}
public override bool IsGreaterThan(AmiKey right)
{
if (Timestamp != right.Timestamp)
return Timestamp > right.Timestamp;
if (PointID != right.PointID)
return PointID > right.PointID;
if (TableId != right.TableId)
return TableId > right.TableId;
return CollectedTime > right.CollectedTime;
}
public override bool IsGreaterThanOrEqualTo(AmiKey right)
{
if (Timestamp != right.Timestamp)
return Timestamp > right.Timestamp;
if (PointID != right.PointID)
return PointID > right.PointID;
if (TableId != right.TableId)
return TableId > right.TableId;
return CollectedTime >= right.CollectedTime;
}
//public override bool IsBetween(HistorianKey lowerBounds, HistorianKey upperBounds)
//{
//
//}
//public override SortedTreeTypeMethods<HistorianKey> CreateValueMethods()
//{
//
//}
#endregion
}
}
| 28.812207 | 97 | 0.516865 | [
"MIT"
] | GridProtectionAlliance/openHistorian | Source/Libraries/openHistorian.Scada/AMI/AmiKey.cs | 6,139 | 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.Ump.V20200918.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class Polygon : AbstractModel
{
/// <summary>
/// 标注列表
/// </summary>
[JsonProperty("Points")]
public Point[] Points{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArrayObj(map, prefix + "Points.", this.Points);
}
}
}
| 28.840909 | 81 | 0.64933 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Ump/V20200918/Models/Polygon.cs | 1,277 | C# |
using Prism;
using Prism.Ioc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace AppConsultarEstatusRS6.UWP
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
LoadApplication(new AppConsultarEstatusRS6.App(new UwpInitializer()));
}
}
public class UwpInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
// Register any platform specific implementations
}
}
}
| 24.657895 | 82 | 0.722519 | [
"MIT"
] | Adriano-Severino/AppConsultarEstatusRS6 | AppConsultarEstatusRS6/AppConsultarEstatusRS6.UWP/MainPage.xaml.cs | 939 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider;
namespace Microsoft.VisualStudio.ProjectSystem.VS.Tree.Dependencies.GraphNodes
{
internal sealed partial class DependenciesGraphProvider
{
/// <summary>
/// Maps between the representation of icons used by <see cref="IVsImageService2"/> and the rest of the dependencies node,
/// caching the mapping data for performance.
/// </summary>
private sealed class GraphIconCache
{
private ImmutableHashSet<ImageMoniker> _registeredIcons = ImmutableHashSet<ImageMoniker>.Empty;
private ImmutableDictionary<(int id, Guid guid), string> _iconNameCache = ImmutableDictionary<(int id, Guid guid), string>.Empty;
private readonly IVsImageService2 _imageService;
public static async Task<GraphIconCache> CreateAsync(IAsyncServiceProvider serviceProvider)
{
#pragma warning disable RS0030 // Do not used banned APIs
var imageService = (IVsImageService2)await serviceProvider.GetServiceAsync(typeof(SVsImageService));
#pragma warning restore RS0030 // Do not used banned APIs
return new GraphIconCache(imageService);
}
private GraphIconCache(IVsImageService2 imageService) => _imageService = imageService;
public string GetName(ImageMoniker icon)
{
return ImmutableInterlocked.GetOrAdd(ref _iconNameCache, (id: icon.Id, guid: icon.Guid), i => $"{i.guid:D};{i.id}");
}
public void Register(ImageMoniker icon)
{
if (ImmutableInterlocked.Update(ref _registeredIcons, (knownIcons, arg) => knownIcons.Add(arg), icon))
{
_imageService.TryAssociateNameWithMoniker(GetName(icon), icon);
}
}
}
}
}
| 44 | 162 | 0.665647 | [
"Apache-2.0"
] | MSLukeWest/project-system | src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/Tree/Dependencies/GraphNodes/DependenciesGraphProvider.IconCache.cs | 2,239 | 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.Iecp.V20210914.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeDracoEdgeNodeInstallerResponse : AbstractModel
{
/// <summary>
/// 在线安装命名
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("OnlineInstallationCommand")]
public string OnlineInstallationCommand{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ 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 + "OnlineInstallationCommand", this.OnlineInstallationCommand);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 32.134615 | 107 | 0.659485 | [
"Apache-2.0"
] | tencentcloudapi-test/tencentcloud-sdk-dotnet | TencentCloud/Iecp/V20210914/Models/DescribeDracoEdgeNodeInstallerResponse.cs | 1,781 | C# |
using System.ComponentModel.DataAnnotations;
using Abp.Localization;
namespace Afonsoft.SetBox.Web.Models.Account
{
public class VerifySecurityCodeViewModel
{
[Required]
public string Provider { get; set; }
[Required]
[AbpDisplayName(SetBoxConsts.LocalizationSourceName, "Code")]
public string Code { get; set; }
public string ReturnUrl { get; set; }
[AbpDisplayName(SetBoxConsts.LocalizationSourceName, "RememberThisBrowser")]
public bool RememberBrowser { get; set; }
public bool RememberMe { get; set; }
public bool IsRememberBrowserEnabled { get; set; }
}
} | 27.5 | 84 | 0.672727 | [
"Apache-2.0"
] | afonsoft/SetBox-VideoPlayer | SetBoxWebUI_New/src/Afonsoft.SetBox.Web.Mvc/Models/Account/VerifySecurityCodeViewModel.cs | 662 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BookOrders.Areas.Admin.Pages
{
[Authorize(Roles = "Admin")]
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
}
| 19.65 | 42 | 0.709924 | [
"Apache-2.0"
] | RadoslavNikolov/BookOrders | BookOrders/Areas/Admin/Pages/Index.cshtml.cs | 395 | C# |
#pragma checksum "C:\Users\Jonathan Villeda\Documents\PROYECTOS C#\AppWebPersonal\Views\Home\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "99464617055fdb505bb0bb7fd91f9b14f7b0d030"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Index), @"mvc.1.0.view", @"/Views/Home/Index.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Home/Index.cshtml", typeof(AspNetCore.Views_Home_Index))]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#line 1 "C:\Users\Jonathan Villeda\Documents\PROYECTOS C#\AppWebPersonal\Views\_ViewImports.cshtml"
using AppWebPersonal;
#line default
#line hidden
#line 2 "C:\Users\Jonathan Villeda\Documents\PROYECTOS C#\AppWebPersonal\Views\_ViewImports.cshtml"
using AppWebPersonal.Models;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"99464617055fdb505bb0bb7fd91f9b14f7b0d030", @"/Views/Home/Index.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"285d8c415f344666eb7198252e4e9224e32f60bc", @"/Views/_ViewImports.cshtml")]
public class Views_Home_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#line 1 "C:\Users\Jonathan Villeda\Documents\PROYECTOS C#\AppWebPersonal\Views\Home\Index.cshtml"
ViewData["Title"] = "Home Page";
#line default
#line hidden
BeginContext(45, 191, true);
WriteLiteral("\r\n<div class=\"text-center\">\r\n <h1 class=\"display-4\">Welcome</h1>\r\n <p>Learn about <a href=\"https://docs.microsoft.com/aspnet/core\">building Web apps with ASP.NET Core</a>.</p>\r\n</div>\r\n");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 55.54386 | 236 | 0.750158 | [
"Apache-2.0"
] | johnsvill/app-almacen | obj/Debug/netcoreapp2.2/Razor/Views/Home/Index.cshtml.g.cs | 3,166 | C# |
using UnityEngine;
using System.Collections;
public class EnemyHit : MonoBehaviour {
//Creating this Variable to stop lasting hitboxes
public int timeSensitive = 0;
//Damages the Player
void Update()
{
//Stop lasting hitboxes
timeSensitive++;
}
void OnTriggerEnter(Collider colid)
{
//If the player is in the hitbox of the punch. Lose health and play audio.
if (colid.tag == "Player" && timeSensitive < 3 && !colid.GetComponent<Mover>().dead) {
GetComponent<AudioSource>().Play ();
colid.GetComponent<Mover>().health -= this.GetComponentInParent<Enemy>().damage;
}
}
}
| 27.090909 | 88 | 0.713087 | [
"Apache-2.0"
] | GrahamMThomas/Summer-Project-2015 | EnemyHit.cs | 598 | C# |
using System.Threading.Tasks;
using OMP.Connector.Domain.Schema.Messages;
using OMP.Connector.Domain.Schema.SensorTelemetry;
namespace OMP.Connector.Infrastructure.MQTT.Common.Publishers
{
public interface IMqttResponsePublisher : IMqttPublisher<CommandResponse>
{ }
public interface IMqttTelemetryPublisher : IMqttPublisher<SensorTelemetryMessage>
{ }
public interface IMqttPublisher<T>
{
Task PublishAsync(T message);
}
}
| 25.777778 | 85 | 0.765086 | [
"MIT"
] | OpenManufacturingPlatform/iotcon-opc-ua-connector-dotnet | src/Infrastructure/MQTT/Common/Publishers/IMqttResponsePublisher.cs | 466 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
namespace System.Data.Entity.ModelConfiguration.Configuration
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Utilities;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Allows configuration to be performed for a lightweight convention based on
/// the entity types in a model that inherit from a common, specified type and a
/// captured value.
/// </summary>
/// <typeparam name="T"> The common type of the entity types that this convention applies to. </typeparam>
/// <typeparam name="TValue"> Type of the captured value. </typeparam>
public class TypeConventionWithHavingConfiguration<T, TValue>
where T : class
where TValue : class
{
private readonly ConventionsConfiguration _conventionsConfiguration;
private readonly IEnumerable<Func<Type, bool>> _predicates;
private readonly Func<Type, TValue> _capturingPredicate;
internal TypeConventionWithHavingConfiguration(
ConventionsConfiguration conventionsConfiguration,
IEnumerable<Func<Type, bool>> predicates,
Func<Type, TValue> capturingPredicate)
{
DebugCheck.NotNull(conventionsConfiguration);
DebugCheck.NotNull(predicates);
DebugCheck.NotNull(capturingPredicate);
_conventionsConfiguration = conventionsConfiguration;
_predicates = predicates;
_capturingPredicate = capturingPredicate;
}
internal ConventionsConfiguration ConventionsConfiguration
{
get { return _conventionsConfiguration; }
}
internal IEnumerable<Func<Type, bool>> Predicates
{
get { return _predicates; }
}
internal Func<Type, TValue> CapturingPredicate
{
get { return _capturingPredicate; }
}
/// <summary>
/// Allows configuration of the entity types that this convention applies to.
/// </summary>
/// <param name="entityConfigurationAction">
/// An action that performs configuration against a <see cref="ConventionTypeConfiguration{T}" />
/// using a captured value.
/// </param>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public void Configure(Action<ConventionTypeConfiguration<T>, TValue> entityConfigurationAction)
{
Check.NotNull(entityConfigurationAction, "entityConfigurationAction");
_conventionsConfiguration.Add(
new TypeConventionWithHaving<T, TValue>(
_predicates,
_capturingPredicate,
entityConfigurationAction));
}
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString()
{
return base.ToString();
}
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
return base.Equals(obj);
}
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Gets the <see cref="Type" /> of the current instance.
/// </summary>
/// <returns>The exact runtime type of the current instance.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
[EditorBrowsable(EditorBrowsableState.Never)]
public new Type GetType()
{
return base.GetType();
}
}
}
| 37.121495 | 144 | 0.639225 | [
"MIT"
] | dotnet/ef6tools | src/EntityFramework/ModelConfiguration/Configuration/Conventions/TypeConventionWithHavingConfiguration`.cs | 3,972 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.ApiManagement.Models
{
/// <summary>
/// Defines values for CertificateStatus.
/// </summary>
public static class CertificateStatus
{
public const string Completed = "Completed";
public const string Failed = "Failed";
public const string InProgress = "InProgress";
}
}
| 29.5 | 74 | 0.700565 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/apimanagement/Microsoft.Azure.Management.ApiManagement/src/Generated/Models/CertificateStatus.cs | 708 | C# |
using System.Collections.Generic;
using System.Security.Principal;
namespace AdvancedWf.Shared.ViewModels
{
public static class LinqExtentions
{
/// <summary>
/// Helper to know if user in any of specific roles
/// </summary>
/// <param name="user">current logged user - Dependancy injection</param>
/// <param name="roles">List of string - roles names</param>
/// <returns></returns>
public static bool IsInAnyRole(this IPrincipal user, List<string> roles)
{
foreach (var item in roles)
if (user.IsInRole(item)) return true;
return false;
}
}
}
| 30.545455 | 81 | 0.60119 | [
"MIT"
] | zeinabkamel/AdvancedWF | AdvancedWf.Shared/ViewModels/DataTable/LINQExtensions.cs | 674 | 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("XMVVM.ExpressApp.Win.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XMVVM.ExpressApp.Win.Test")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("953e9595-20cc-44a9-85b0-1a09c4abcb9f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.459459 | 84 | 0.745608 | [
"MIT"
] | biohazard999/XafMVVM | src/XMVVM/XMVVM.ExpressApp/XMVVM.ExpressApp.Win.Test/Properties/AssemblyInfo.cs | 1,426 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using EntityFramework.BulkInsert.Exceptions;
using EntityFramework.BulkInsert.Providers;
namespace EntityFramework.BulkInsert
{
public class ProviderFactory
{
private static Dictionary<string, Func<IEfBulkInsertProvider>> _providers;
private static readonly object providerInitializerLockObject = new object();
/// <summary>
/// Registered bulkinsert providers container
/// </summary>
private static Dictionary<string, Func<IEfBulkInsertProvider>> Providers
{
get
{
lock (providerInitializerLockObject)
{
if (_providers == null)
{
_providers = new Dictionary<string, Func<IEfBulkInsertProvider>>();
// bundled providers
Register<SqlBulkInsertProvider>();
}
}
return _providers;
}
}
/// <summary>
/// Register new bulkinsert provider.
/// Rplaces existing if name matches.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name"></param>
public static void Register<T>(string name)
where T : IEfBulkInsertProvider, new()
{
Providers[name] = () => new T();
}
/// <summary>
/// Register new bulk insert provider.
/// </summary>
/// <typeparam name="T"></typeparam>
public static void Register<T>()
where T : IEfBulkInsertProvider, new()
{
var instance = new T();
Providers[instance.ProviderIdentifier] = () => new T();
}
/// <summary>
/// Get bulkinsert porvider by connection used in context
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static IEfBulkInsertProvider Get(DbContext context)
{
var connectionTypeName = context.Database.Connection.GetType().FullName;
if (!Providers.ContainsKey(connectionTypeName))
{
throw new BulkInsertProviderNotFoundException(connectionTypeName);
}
return Providers[connectionTypeName]().SetContext(context);
}
}
}
| 31.467532 | 91 | 0.552621 | [
"Apache-2.0"
] | andy-clymer/EntityFramework.BulkInsert | src/EntityFramework.BulkInsert/ProviderFactory.cs | 2,425 | C# |
using System;
namespace FontAwesome
{
/// <summary>
/// The unicode values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Unicode
{
/// <summary>
/// fa-calculator-alt unicode value ("\uf64c").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid (Pro), Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/calculator-alt
/// </summary>
public const string CalculatorAlt = "\uf64c";
}
/// <summary>
/// The Css values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Css
{
/// <summary>
/// CalculatorAlt unicode value ("fa-calculator-alt").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid (Pro), Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/calculator-alt
/// </summary>
public const string CalculatorAlt = "fa-calculator-alt";
}
/// <summary>
/// The Icon names for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Icon
{
/// <summary>
/// fa-calculator-alt unicode value ("\uf64c").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid (Pro), Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/calculator-alt
/// </summary>
public const string CalculatorAlt = "CalculatorAlt";
}
} | 37.295082 | 154 | 0.6 | [
"MIT"
] | michaelswells/FontAwesomeAttribute | FontAwesome/FontAwesome.CalculatorAlt.cs | 2,275 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using NUnit.Framework;
using Restfulie.Server.Marshalling.UrlGenerators;
using Restfulie.Server.Tests.Fixtures;
namespace Restfulie.Server.Tests
{
[TestFixture]
public class RelationsTests
{
[Test]
public void ShouldTransitToAControllerAction()
{
var urlGenerator = new Mock<IUrlGenerator>();
urlGenerator.Setup(ug => ug.For("Some", "SomeSimpleAction", It.IsAny<IDictionary<string, object>>())).Returns("http://Some/SomeSimpleAction");
var relations = new Relations(urlGenerator.Object);
relations.Named("pay").Uses<SomeController>().SomeSimpleAction();
var all = relations.GetAll();
Assert.AreEqual("pay", all.First().Name);
Assert.AreEqual("http://Some/SomeSimpleAction", all.First().Url);
}
[Test]
public void ShouldDetectWrongUseOfFluentAPI()
{
var relations = new Relations(new Mock<IUrlGenerator>().Object);
Assert.Throws<ArgumentException>(() =>
relations.Uses<SomeController>().SomeSimpleAction());
}
[Test]
public void ShouldWorkWhenUsingTheAPIFluentlyInARow()
{
var relations = new Relations(new Mock<IUrlGenerator>().Object);
relations.Named("pay").Uses<SomeController>().SomeSimpleAction();
relations.Named("cancel").Uses<SomeController>().SomeSimpleAction();
var all = relations.GetAll();
Assert.AreEqual(2, all.Count);
Assert.IsNotNull(all.Where(t => t.Name == "pay").Single());
Assert.IsNotNull(all.Where(t => t.Name == "cancel").Single());
}
[Test]
public void ShouldCreateALinkToaNonAction()
{
var relations = new Relations(new Mock<IUrlGenerator>().Object);
relations.Named("to_another_website").At("some/url");
var all = relations.GetAll();
Assert.AreEqual(1, all.Count);
Assert.AreEqual("to_another_website" , all.First().Name);
Assert.AreEqual("some/url", all.First().Url);
}
}
} | 34.861538 | 155 | 0.597529 | [
"Apache-2.0"
] | mauricioaniche/restfulie.net | Restfulie.Server.Tests/RelationsTests.cs | 2,268 | 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 iam-2010-05-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IdentityManagement.Model
{
/// <summary>
/// Contains details about the specified entity (user or role).
///
///
/// <para>
/// This data type is an element of the <a>EntityDetails</a> object.
/// </para>
/// </summary>
public partial class EntityInfo
{
private string _arn;
private string _id;
private string _name;
private string _path;
private PolicyOwnerEntityType _type;
/// <summary>
/// Gets and sets the property Arn.
/// </summary>
[AWSProperty(Required=true, Min=20, Max=2048)]
public string Arn
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property Id.
/// <para>
/// The identifier of the entity (user or role).
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=16, Max=128)]
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the entity (user or role).
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=64)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property Path.
/// <para>
/// The path to the entity (user or role). For more information about paths, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html">IAM
/// Identifiers</a> in the <i>IAM User Guide</i>.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=512)]
public string Path
{
get { return this._path; }
set { this._path = value; }
}
// Check to see if Path property is set
internal bool IsSetPath()
{
return this._path != null;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The type of entity (user or role).
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public PolicyOwnerEntityType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
}
} | 28.05 | 174 | 0.547237 | [
"Apache-2.0"
] | AltairMartinez/aws-sdk-unity-net | src/Services/IdentityManagement/Generated/Model/EntityInfo.cs | 3,927 | C# |
using System;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
namespace Fluid
{
public static class FluidTemplateExtensions
{
public static ValueTask<string> RenderAsync(this IFluidTemplate template, TemplateContext context)
{
return template.RenderAsync(context, NullEncoder.Default);
}
public static string Render(this IFluidTemplate template, TemplateContext context, TextEncoder encoder)
{
return template.RenderAsync(context, encoder).GetAwaiter().GetResult();
}
public static void Render(this IFluidTemplate template, TemplateContext context, TextEncoder encoder, TextWriter writer)
{
template.RenderAsync(writer, encoder, context).GetAwaiter().GetResult();
}
public static async ValueTask<string> RenderAsync(this IFluidTemplate template, TemplateContext context, TextEncoder encoder)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
using (var sb = StringBuilderPool.GetInstance())
{
using (var writer = new StringWriter(sb.Builder))
{
await template.RenderAsync(writer, encoder, context);
await writer.FlushAsync();
}
return sb.ToString();
}
}
public static string Render(this IFluidTemplate template, TemplateContext context)
{
return template.RenderAsync(context).GetAwaiter().GetResult();
}
public static ValueTask<string> RenderAsync(this IFluidTemplate template)
{
return template.RenderAsync(new TemplateContext());
}
public static string Render(this IFluidTemplate template)
{
return template.RenderAsync().GetAwaiter().GetResult();
}
}
}
| 32.292308 | 133 | 0.608861 | [
"MIT"
] | Selz/fluid | Fluid/FluidTemplateExtensions.cs | 2,101 | C# |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2013 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
using System.IO;
using System.Linq;
using System.Text;
#if !MSTEST
using NUnit.Framework;
#else
using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
using TimeoutAttribute = NUnit.Framework.TimeoutAttribute;
using Assert = NUnit.Framework.Assert;
using Is = NUnit.Framework.Is;
#endif
namespace MsgPack
{
// This file was generated from UnpackerTest.Raw.tt and StreamingUnapkcerBase.ttinclude T4Template.
// Do not modify this file. Edit UnpackerTest.Raw.tt and StreamingUnapkcerBase.ttinclude instead.
[TestFixture]
public partial class UnpackingTest_Raw
{
[Test]
public void TestUnpackFixStr_0_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xA0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackFixStr_0_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xA0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackFixStr_0_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xA0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackFixStr_0_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xA0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackFixStr_1_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xA1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackFixStr_1_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xA1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackFixStr_1_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xA1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackFixStr_1_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xA1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackFixStr_1_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xA1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackFixStr_1_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xA1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackFixStr_31_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xBF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackFixStr_31_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xBF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackFixStr_31_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xBF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackFixStr_31_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xBF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackFixStr_31_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xBF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackFixStr_31_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xBF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackStr8_0_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xD9, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackStr8_0_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xD9, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackStr8_0_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xD9, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackStr8_0_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xD9, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackStr8_1_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xD9, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackStr8_1_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xD9, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackStr8_1_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xD9, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr8_1_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xD9, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr8_1_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xD9, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackStr8_1_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xD9, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackStr8_31_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xD9, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackStr8_31_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xD9, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackStr8_31_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xD9, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr8_31_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xD9, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr8_31_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xD9, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackStr8_31_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xD9, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackStr8_32_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xD9, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackStr8_32_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xD9, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackStr8_32_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xD9, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr8_32_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xD9, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr8_32_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xD9, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackStr8_32_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xD9, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackStr8_255_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xD9, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackStr8_255_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xD9, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackStr8_255_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xD9, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr8_255_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xD9, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr8_255_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xD9, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackStr8_255_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xD9, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackStr16_0_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackStr16_0_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackStr16_0_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackStr16_0_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackStr16_1_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackStr16_1_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackStr16_1_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_1_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_1_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackStr16_1_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackStr16_31_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackStr16_31_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackStr16_31_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_31_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_31_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackStr16_31_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackStr16_32_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackStr16_32_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackStr16_32_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_32_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_32_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackStr16_32_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackStr16_255_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackStr16_255_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackStr16_255_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_255_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_255_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackStr16_255_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackStr16_256_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 256 ) ) );
}
}
[Test]
public void TestUnpackStr16_256_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 256 ) ) );
}
[Test]
public void TestUnpackStr16_256_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_256_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_256_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 257 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 256 ) ) );
}
}
[Test]
public void TestUnpackStr16_256_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 257 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 256 ) ) );
}
[Test]
public void TestUnpackStr16_65535_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 65535 ) ) );
}
}
[Test]
public void TestUnpackStr16_65535_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 65535 ) ) );
}
[Test]
public void TestUnpackStr16_65535_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65534 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_65535_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65534 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_65535_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 65535 ) ) );
}
}
[Test]
public void TestUnpackStr16_65535_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 65535 ) ) );
}
[Test]
public void TestUnpackStr32_0_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackStr32_0_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackStr32_0_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackStr32_0_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackStr32_1_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackStr32_1_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackStr32_1_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_1_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_1_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackStr32_1_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackStr32_31_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackStr32_31_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackStr32_31_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_31_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_31_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackStr32_31_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackStr32_32_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackStr32_32_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackStr32_32_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_32_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_32_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackStr32_32_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackStr32_255_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackStr32_255_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackStr32_255_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_255_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_255_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackStr32_255_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackStr32_256_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 256 ) ) );
}
}
[Test]
public void TestUnpackStr32_256_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 256 ) ) );
}
[Test]
public void TestUnpackStr32_256_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_256_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_256_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 257 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 256 ) ) );
}
}
[Test]
public void TestUnpackStr32_256_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 257 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 256 ) ) );
}
[Test]
public void TestUnpackStr32_65535_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 65535 ) ) );
}
}
[Test]
public void TestUnpackStr32_65535_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 65535 ) ) );
}
[Test]
public void TestUnpackStr32_65535_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65534 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_65535_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65534 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_65535_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 65535 ) ) );
}
}
[Test]
public void TestUnpackStr32_65535_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 65535 ) ) );
}
[Test]
public void TestUnpackStr32_65536_AsString_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65536 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 65536 ) ) );
}
}
[Test]
public void TestUnpackStr32_65536_AsString_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65536 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 65536 ) ) );
}
[Test]
public void TestUnpackStr32_65536_AsString_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_65536_AsString_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_65536_AsString_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65537 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65536 ) );
Assert.That( Encoding.UTF8.GetString( result, 0, result.Length ), Is.EqualTo( new String( 'A', 65536 ) ) );
}
}
[Test]
public void TestUnpackStr32_65536_AsString_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65537 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65536 ) );
Assert.That( Encoding.UTF8.GetString( result.Value, 0, result.Value.Length ), Is.EqualTo( new String( 'A', 65536 ) ) );
}
[Test]
public void TestUnpackBin8_0_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC4, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackBin8_0_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC4, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackBin8_0_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC4, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackBin8_0_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC4, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackBin8_1_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC4, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackBin8_1_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC4, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackBin8_1_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC4, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin8_1_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC4, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin8_1_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC4, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackBin8_1_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC4, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackBin8_31_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC4, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackBin8_31_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC4, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackBin8_31_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC4, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin8_31_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC4, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin8_31_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC4, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackBin8_31_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC4, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackBin8_32_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC4, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackBin8_32_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC4, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackBin8_32_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC4, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin8_32_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC4, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin8_32_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC4, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackBin8_32_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC4, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackBin8_255_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC4, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackBin8_255_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC4, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackBin8_255_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC4, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin8_255_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC4, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin8_255_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC4, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackBin8_255_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC4, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackBin16_0_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC5, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackBin16_0_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackBin16_0_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC5, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackBin16_0_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackBin16_1_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC5, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackBin16_1_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC5, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackBin16_1_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC5, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin16_1_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC5, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin16_1_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC5, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackBin16_1_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC5, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackBin16_31_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC5, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackBin16_31_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackBin16_31_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC5, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin16_31_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin16_31_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC5, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackBin16_31_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackBin16_32_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC5, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackBin16_32_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackBin16_32_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC5, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin16_32_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin16_32_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC5, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackBin16_32_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackBin16_255_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC5, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackBin16_255_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackBin16_255_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC5, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin16_255_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin16_255_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC5, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackBin16_255_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC5, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackBin16_256_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC5, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 256 ) ) );
}
}
[Test]
public void TestUnpackBin16_256_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC5, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 256 ) ) );
}
[Test]
public void TestUnpackBin16_256_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC5, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin16_256_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC5, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin16_256_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC5, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 257 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 256 ) ) );
}
}
[Test]
public void TestUnpackBin16_256_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC5, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 257 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 256 ) ) );
}
[Test]
public void TestUnpackBin16_65535_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC5, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 65535 ) ) );
}
}
[Test]
public void TestUnpackBin16_65535_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC5, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 65535 ) ) );
}
[Test]
public void TestUnpackBin16_65535_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC5, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65534 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin16_65535_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC5, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65534 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin16_65535_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC5, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 65535 ) ) );
}
}
[Test]
public void TestUnpackBin16_65535_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC5, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 65535 ) ) );
}
[Test]
public void TestUnpackBin32_0_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackBin32_0_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackBin32_0_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 0 ) ) );
}
}
[Test]
public void TestUnpackBin32_0_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 0 ) ) );
}
[Test]
public void TestUnpackBin32_1_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackBin32_1_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 1 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackBin32_1_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin32_1_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin32_1_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 1 ) ) );
}
}
[Test]
public void TestUnpackBin32_1_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 2 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 1 ) ) );
}
[Test]
public void TestUnpackBin32_31_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackBin32_31_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackBin32_31_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin32_31_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin32_31_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 31 ) ) );
}
}
[Test]
public void TestUnpackBin32_31_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 31 ) ) );
}
[Test]
public void TestUnpackBin32_32_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackBin32_32_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 32 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackBin32_32_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin32_32_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 31 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin32_32_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 32 ) ) );
}
}
[Test]
public void TestUnpackBin32_32_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 33 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 32 ) ) );
}
[Test]
public void TestUnpackBin32_255_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackBin32_255_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackBin32_255_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin32_255_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 254 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin32_255_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 255 ) ) );
}
}
[Test]
public void TestUnpackBin32_255_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 255 ) ) );
}
[Test]
public void TestUnpackBin32_256_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 256 ) ) );
}
}
[Test]
public void TestUnpackBin32_256_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 256 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 256 ) ) );
}
[Test]
public void TestUnpackBin32_256_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin32_256_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 255 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin32_256_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 257 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 256 ) ) );
}
}
[Test]
public void TestUnpackBin32_256_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 257 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 256 ) ) );
}
[Test]
public void TestUnpackBin32_65535_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 65535 ) ) );
}
}
[Test]
public void TestUnpackBin32_65535_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 65535 ) ) );
}
[Test]
public void TestUnpackBin32_65535_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65534 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin32_65535_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65534 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin32_65535_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC6, 0, 0, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 65535 ) ) );
}
}
[Test]
public void TestUnpackBin32_65535_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC6, 0, 0, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 65535 ) ) );
}
[Test]
public void TestUnpackBin32_65536_AsString_UnpackString_JustLength_Success_Stream()
{
var header = new byte[] { 0xC6, 0, 1, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65536 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 65536 ) ) );
}
}
[Test]
public void TestUnpackBin32_65536_AsString_UnpackString_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xC6, 0, 1, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65536 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65536 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 65536 ) ) );
}
[Test]
public void TestUnpackBin32_65536_AsString_UnpackString_TooShort_Fail_Stream()
{
var header = new byte[] { 0xC6, 0, 1, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
}
[Test]
public void TestUnpackBin32_65536_AsString_UnpackString_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xC6, 0, 1, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65535 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackString( buffer ) );
}
[Test]
public void TestUnpackBin32_65536_AsString_UnpackString_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xC6, 0, 1, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )'A', 65537 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackString( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65536 ) );
Assert.That( result, Is.EqualTo( new String( 'A', 65536 ) ) );
}
}
[Test]
public void TestUnpackBin32_65536_AsString_UnpackString_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xC6, 0, 1, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )'A', 65537 ) ).ToArray();
var result = Unpacking.UnpackString( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65536 ) );
Assert.That( result.Value, Is.EqualTo( new String( 'A', 65536 ) ) );
}
[Test]
public void TestUnpackFixStr_0_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xA0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
}
[Test]
public void TestUnpackFixStr_0_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xA0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
[Test]
public void TestUnpackFixStr_0_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xA0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
}
[Test]
public void TestUnpackFixStr_0_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xA0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
[Test]
public void TestUnpackFixStr_1_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xA1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
}
[Test]
public void TestUnpackFixStr_1_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xA1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
[Test]
public void TestUnpackFixStr_1_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xA1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackFixStr_1_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xA1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackFixStr_1_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xA1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
}
[Test]
public void TestUnpackFixStr_1_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xA1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
[Test]
public void TestUnpackFixStr_31_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xBF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
}
[Test]
public void TestUnpackFixStr_31_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xBF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
[Test]
public void TestUnpackFixStr_31_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xBF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackFixStr_31_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xBF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackFixStr_31_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xBF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
}
[Test]
public void TestUnpackFixStr_31_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xBF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
[Test]
public void TestUnpackStr8_0_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xD9, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr8_0_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xD9, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
[Test]
public void TestUnpackStr8_0_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xD9, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr8_0_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xD9, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
[Test]
public void TestUnpackStr8_1_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xD9, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr8_1_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xD9, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
[Test]
public void TestUnpackStr8_1_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xD9, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr8_1_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xD9, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr8_1_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xD9, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr8_1_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xD9, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
[Test]
public void TestUnpackStr8_31_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xD9, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr8_31_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xD9, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
[Test]
public void TestUnpackStr8_31_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xD9, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr8_31_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xD9, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr8_31_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xD9, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr8_31_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xD9, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
[Test]
public void TestUnpackStr8_32_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xD9, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr8_32_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xD9, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
[Test]
public void TestUnpackStr8_32_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xD9, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr8_32_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xD9, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr8_32_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xD9, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 33 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr8_32_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xD9, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 33 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
[Test]
public void TestUnpackStr8_255_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xD9, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr8_255_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xD9, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
[Test]
public void TestUnpackStr8_255_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xD9, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 254 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr8_255_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xD9, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 254 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr8_255_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xD9, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr8_255_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xD9, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 256 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_0_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_0_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_0_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_0_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_1_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_1_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_1_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_1_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_1_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_1_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_31_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_31_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_31_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_31_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_31_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_31_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_32_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_32_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_32_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_32_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_32_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 33 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_32_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 33 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_255_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_255_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_255_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 254 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_255_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 254 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_255_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_255_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 256 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_256_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 256 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_256_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 256 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 256 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_256_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_256_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_256_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 257 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 256 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_256_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 257 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 256 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_65535_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_65535_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) );
}
[Test]
public void TestUnpackStr16_65535_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 65534 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr16_65535_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 65534 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr16_65535_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr16_65535_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDA, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_0_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_0_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_0_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 0 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_0_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 0 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 0 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_1_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_1_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 1 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_1_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_1_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 0 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_1_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 1 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_1_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 1 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 2 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 1 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 1 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_31_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_31_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_31_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 30 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_31_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 30 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_31_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 31 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_31_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x1F };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 31 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 31 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_32_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_32_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 32 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_32_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_32_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 31 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_32_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 33 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 32 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_32_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0x20 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 33 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 32 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 32 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_255_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_255_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_255_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 254 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_255_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 254 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_255_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 255 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_255_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 256 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 255 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 255 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_256_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 256 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 256 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_256_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 256 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 256 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_256_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_256_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 255 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_256_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 257 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 256 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 256 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_256_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 1, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 257 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 256 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 256 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_65535_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_65535_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_65535_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 65534 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_65535_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 65534 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_65535_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_65535_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 0, 0xFF, 0xFF };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65535 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 65535 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_65536_AsBinary_UnpackBinary_JustLength_Success_Stream()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65536 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65536 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_65536_AsBinary_UnpackBinary_JustLength_Success_ByteArray()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 65536 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65536 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 65536 ).ToArray() ) );
}
[Test]
public void TestUnpackStr32_65536_AsBinary_UnpackBinary_TooShort_Fail_Stream()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray()
)
)
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
}
[Test]
public void TestUnpackStr32_65536_AsBinary_UnpackBinary_TooShort_Fail_ByteArray()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 65535 ) ).ToArray();
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackBinary( buffer ) );
}
[Test]
public void TestUnpackStr32_65536_AsBinary_UnpackBinary_HasExtra_NoProblem_Stream()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
using( var buffer =
new MemoryStream(
header.Concat( Enumerable.Repeat( ( byte )0xFF, 65537 ) ).ToArray()
)
)
{
var result = Unpacking.UnpackBinary( buffer );
Assert.That( buffer.Position, Is.EqualTo( header.Length + 65536 ) );
Assert.That( result, Is.EqualTo( Enumerable.Repeat( 0xFF, 65536 ).ToArray() ) );
}
}
[Test]
public void TestUnpackStr32_65536_AsBinary_UnpackBinary_HasExtra_NoProblem_ByteArray()
{
var header = new byte[] { 0xDB, 0, 1, 0, 0 };
var buffer = header.Concat( Enumerable.Repeat( ( byte )0xFF, 65537 ) ).ToArray();
var result = Unpacking.UnpackBinary( buffer );
Assert.That( result.ReadCount, Is.EqualTo( header.Length + 65536 ) );
Assert.That( result.Value, Is.EqualTo( Enumerable.Repeat( 0xFF, 65536 ).ToArray() ) );
}
}
}
| 34.96501 | 122 | 0.665141 | [
"Apache-2.0"
] | benjamin-bader/msgpack-cli | test/MsgPack.UnitTest/UnpackingTest.Raw.cs | 163,883 | 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.Aiven.Outputs
{
[OutputType]
public sealed class ServiceRedisUserConfigMigration
{
public readonly string? Dbname;
public readonly string? Host;
public readonly string? IgnoreDbs;
public readonly string? Password;
public readonly string? Port;
public readonly string? Ssl;
public readonly string? Username;
[OutputConstructor]
private ServiceRedisUserConfigMigration(
string? dbname,
string? host,
string? ignoreDbs,
string? password,
string? port,
string? ssl,
string? username)
{
Dbname = dbname;
Host = host;
IgnoreDbs = ignoreDbs;
Password = password;
Port = port;
Ssl = ssl;
Username = username;
}
}
}
| 24.38 | 88 | 0.59639 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-aiven | sdk/dotnet/Outputs/ServiceRedisUserConfigMigration.cs | 1,219 | 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("OddFilter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OddFilter")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("085d7ebb-70b5-4a94-bb95-5681dd1b5be9")]
// 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.459459 | 84 | 0.746753 | [
"MIT"
] | ztimofeev/Programming_Fundamentals_SoftUni-repo | 07.DictioinariesAndLINQ/OddFilter/Properties/AssemblyInfo.cs | 1,389 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using DataAccess.Framework;
using DataHelper.Framework;
using Entity.Components;
using Entity.Framework;
namespace DataAccess.Components
{
public class FIVE_DIMENSION_TEMPDAO :DataAccess.Framework.AbstractDAO
{
#region Constructor
public FIVE_DIMENSION_TEMPDAO()
{
}
#endregion
#region Override Properties
protected override string SelectCommand
{
get
{
return "PKJ_SELECT.SELECTFIVE_DIMENSION_TEMP";
}
}
protected override string InsertCommand
{
get
{
return "PKJ_MODIFY.MODIFYFIVE_DIMENSION_TEMP";
}
}
protected override string UpdateCommand
{
get
{
return "PKJ_MODIFY.MODIFYFIVE_DIMENSION_TEMP";
}
}
protected override string DeleteCommand
{
get
{
return "PKJ_MODIFY.MODIFYFIVE_DIMENSION_TEMP";
}
}
#endregion
#region Overridden Methods
protected override EntityBase CreateAndBuildEntity(DataHelper.Framework.SafeDataReader dr)
{
FIVE_DIMENSION_TEMP theEntity = new FIVE_DIMENSION_TEMP();
theEntity.PK_ID = !dr.IsDBNull(0) ? dr.GetValue(0).ToString() : string.Empty;
theEntity.VEHICLE_ID = !dr.IsDBNull(1) ? dr.GetValue(1).ToString() : string.Empty;
theEntity.DIMENSION = !dr.IsDBNull(2) ? dr.GetValue(2).ToString() : string.Empty;
theEntity.SCRATCH = !dr.IsDBNull(3) ? dr.GetValue(3).ToString() : string.Empty;
theEntity.MISSING = !dr.IsDBNull(4) ? dr.GetValue(4).ToString() : string.Empty;
theEntity.BROKEN = !dr.IsDBNull(5) ? dr.GetValue(5).ToString() : string.Empty;
theEntity.DENTED = !dr.IsDBNull(6) ? dr.GetValue(6).ToString() : string.Empty;
theEntity.OTHERS = !dr.IsDBNull(7) ? dr.GetValue(7).ToString() : string.Empty;
theEntity.OTHER_DESCRIPTION = !dr.IsDBNull(8) ? dr.GetValue(8).ToString() : string.Empty;
return theEntity;
}
protected override IDbDataParameter[] CreateSelectParameters(EntityBase anEntity)
{
FIVE_DIMENSION_TEMP theEntity = (FIVE_DIMENSION_TEMP)anEntity;
List<IDbDataParameter> cmdParams = new List<IDbDataParameter>();
if(!string.IsNullOrEmpty(theEntity.PK_ID))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_PK_ID",theEntity.PK_ID));
if (!string.IsNullOrEmpty(theEntity.VEHICLE_ID))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_VEHICLE_ID", theEntity.VEHICLE_ID));
if(!string.IsNullOrEmpty(theEntity.DIMENSION))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_DIMENSION",theEntity.DIMENSION));
if(!string.IsNullOrEmpty(theEntity.SCRATCH))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_SCRATCH",theEntity.SCRATCH));
if(!string.IsNullOrEmpty(theEntity.MISSING))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_MISSING",theEntity.MISSING));
if(!string.IsNullOrEmpty(theEntity.BROKEN))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_BROKEN",theEntity.BROKEN));
if(!string.IsNullOrEmpty(theEntity.DENTED))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_DENTED",theEntity.DENTED));
if(!string.IsNullOrEmpty(theEntity.OTHERS))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_OTHERS",theEntity.OTHERS));
if(!string.IsNullOrEmpty(theEntity.OTHER_DESCRIPTION))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_OTHER_DESCRIPTION",theEntity.OTHER_DESCRIPTION));
cmdParams.Add(DataAccessFactory.CreateDataParameter("Result", ""));
return cmdParams.ToArray();
}
protected override IDbDataParameter[] CreateInsertParameters(EntityBase anEntity)
{
FIVE_DIMENSION_TEMP theEntity = (FIVE_DIMENSION_TEMP)anEntity;
List<IDbDataParameter> cmdParams = new List<IDbDataParameter>();
cmdParams.Add(DataAccessFactory.CreateDataParameter("transmode","i"));
if(!string.IsNullOrEmpty(theEntity.PK_ID))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_PK_ID",theEntity.PK_ID));
if (!string.IsNullOrEmpty(theEntity.VEHICLE_ID))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_VEHICLE_ID", theEntity.VEHICLE_ID));
if(!string.IsNullOrEmpty(theEntity.DIMENSION))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_DIMENSION",theEntity.DIMENSION));
if(!string.IsNullOrEmpty(theEntity.SCRATCH))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_SCRATCH",theEntity.SCRATCH));
if(!string.IsNullOrEmpty(theEntity.MISSING))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_MISSING",theEntity.MISSING));
if(!string.IsNullOrEmpty(theEntity.BROKEN))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_BROKEN",theEntity.BROKEN));
if(!string.IsNullOrEmpty(theEntity.DENTED))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_DENTED",theEntity.DENTED));
if(!string.IsNullOrEmpty(theEntity.OTHERS))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_OTHERS",theEntity.OTHERS));
if(!string.IsNullOrEmpty(theEntity.OTHER_DESCRIPTION))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_OTHER_DESCRIPTION",theEntity.OTHER_DESCRIPTION));
cmdParams.Add(DataAccessFactory.CreateDataParameter("errmsg", ""));
return cmdParams.ToArray();
}
protected override IDbDataParameter[] CreateUpdateParameters(EntityBase anEntity)
{
FIVE_DIMENSION_TEMP theEntity = (FIVE_DIMENSION_TEMP)anEntity;
List<IDbDataParameter> cmdParams = new List<IDbDataParameter>();
cmdParams.Add(DataAccessFactory.CreateDataParameter("transmode","u"));
if(!string.IsNullOrEmpty(theEntity.PK_ID))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_PK_ID",theEntity.PK_ID));
if (!string.IsNullOrEmpty(theEntity.VEHICLE_ID))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_VEHICLE_ID", theEntity.VEHICLE_ID));
if(!string.IsNullOrEmpty(theEntity.DIMENSION))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_DIMENSION",theEntity.DIMENSION));
if(!string.IsNullOrEmpty(theEntity.SCRATCH))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_SCRATCH",theEntity.SCRATCH));
if(!string.IsNullOrEmpty(theEntity.MISSING))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_MISSING",theEntity.MISSING));
if(!string.IsNullOrEmpty(theEntity.BROKEN))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_BROKEN",theEntity.BROKEN));
if(!string.IsNullOrEmpty(theEntity.DENTED))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_DENTED",theEntity.DENTED));
if(!string.IsNullOrEmpty(theEntity.OTHERS))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_OTHERS",theEntity.OTHERS));
if(!string.IsNullOrEmpty(theEntity.OTHER_DESCRIPTION))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_OTHER_DESCRIPTION",theEntity.OTHER_DESCRIPTION));
cmdParams.Add(DataAccessFactory.CreateDataParameter("errmsg", ""));
return cmdParams.ToArray();
}
protected override IDbDataParameter[] CreateDeleteParameters(EntityBase anEntity)
{
FIVE_DIMENSION_TEMP theEntity = (FIVE_DIMENSION_TEMP)anEntity;
List<IDbDataParameter> cmdParams = new List<IDbDataParameter>();
cmdParams.Add(DataAccessFactory.CreateDataParameter("transmode","d"));
if(!string.IsNullOrEmpty(theEntity.PK_ID))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_PK_ID",theEntity.PK_ID));
if (!string.IsNullOrEmpty(theEntity.VEHICLE_ID))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_VEHICLE_ID", theEntity.VEHICLE_ID));
if(!string.IsNullOrEmpty(theEntity.DIMENSION))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_DIMENSION",theEntity.DIMENSION));
if(!string.IsNullOrEmpty(theEntity.SCRATCH))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_SCRATCH",theEntity.SCRATCH));
if(!string.IsNullOrEmpty(theEntity.MISSING))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_MISSING",theEntity.MISSING));
if(!string.IsNullOrEmpty(theEntity.BROKEN))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_BROKEN",theEntity.BROKEN));
if(!string.IsNullOrEmpty(theEntity.DENTED))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_DENTED",theEntity.DENTED));
if(!string.IsNullOrEmpty(theEntity.OTHERS))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_OTHERS",theEntity.OTHERS));
if(!string.IsNullOrEmpty(theEntity.OTHER_DESCRIPTION))
cmdParams.Add(DataAccessFactory.CreateDataParameter("VAR_OTHER_DESCRIPTION",theEntity.OTHER_DESCRIPTION));
cmdParams.Add(DataAccessFactory.CreateDataParameter("errmsg", ""));
return cmdParams.ToArray();
}
#endregion
}
}
| 38.67364 | 110 | 0.728551 | [
"MIT"
] | UnIQSaQYA/FleetManagementSystem | transportationArchitecture/DataAccess/Components/FIVE_DIMENSION_TEMPDAO.cs | 9,245 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
class Program
{
public static void Foo()
{
throw new NullReferenceException();
}
}
| 19.692308 | 71 | 0.691406 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Diagnostics.StackTrace/tests/ExceptionTestAssembly/ExceptionTestAssembly.cs | 256 | C# |
using System;
using System.IO;
namespace Cuyahoga.Core.Service.Files
{
/// <summary>
/// The FileService provides services for file manipulation.
/// </summary>
public interface IFileService
{
/// <summary>
/// Read the contents of a file into a stream.
/// </summary>
/// <remarks>
/// NOTE: The caller is responsible for closing the stream.
/// </remarks>
/// <param name="filePath">The physical path where the file is located.</param>
/// <returns></returns>
Stream ReadFile(string filePath);
/// <summary>
/// Write the contents from the given stream to a file.
/// </summary>
/// <remarks>
/// NOTE: The caller is responsible for closing the stream.
/// </remarks>
/// <param name="filePath">The physical file path</param>
/// <param name="fileContents"></param>
void WriteFile(string filePath, Stream fileContents);
/// <summary>
/// Delete a single file.
/// </summary>
/// <param name="filePath">The physical file path</param>
void DeleteFile(string filePath);
/// <summary>
/// Check if the given physical directory is writable for the current user.
/// </summary>
/// <param name="physicalDirectory"></param>
/// <returns></returns>
bool CheckIfDirectoryIsWritable(string physicalDirectory);
}
}
| 28.695652 | 82 | 0.643939 | [
"BSD-3-Clause"
] | dineshkummarc/cuyahoga-1 | Core/Service/Files/IFileService.cs | 1,320 | C# |
using System;
namespace NetworkProtocols
{
// Token: 0x020005EC RID: 1516
public class HeroLevelTaskForNetwork : QuestTaskForNetwork
{
// Token: 0x060034C1 RID: 13505 RVA: 0x0001C901 File Offset: 0x0001AB01
public HeroLevelTaskForNetwork()
{
this.InitRefTypes();
this.UniqueClassID = 3372718083u;
}
// Token: 0x17000683 RID: 1667
// (get) Token: 0x060034C2 RID: 13506 RVA: 0x0001C91A File Offset: 0x0001AB1A
// (set) Token: 0x060034C3 RID: 13507 RVA: 0x0001C922 File Offset: 0x0001AB22
public ulong HeroGUID { get; set; }
// Token: 0x17000684 RID: 1668
// (get) Token: 0x060034C4 RID: 13508 RVA: 0x0001C92B File Offset: 0x0001AB2B
// (set) Token: 0x060034C5 RID: 13509 RVA: 0x0001C933 File Offset: 0x0001AB33
public uint Denominator { get; set; }
// Token: 0x17000685 RID: 1669
// (get) Token: 0x060034C6 RID: 13510 RVA: 0x0001C93C File Offset: 0x0001AB3C
// (set) Token: 0x060034C7 RID: 13511 RVA: 0x0001C944 File Offset: 0x0001AB44
public uint Numerator { get; set; }
// Token: 0x060034C8 RID: 13512 RVA: 0x00108448 File Offset: 0x00106648
public override byte[] SerializeMessage()
{
byte[] newArray = ArrayManager.GetNewArray();
int num = 0;
ArrayManager.WriteUInt64(ref newArray, ref num, this.HeroGUID);
ArrayManager.WriteUInt32(ref newArray, ref num, this.Denominator);
ArrayManager.WriteUInt32(ref newArray, ref num, this.Numerator);
byte[] array = base.SerializeMessage();
if (array.Length + num > newArray.Length)
{
Array.Resize<byte>(ref newArray, array.Length + num);
}
Array.Copy(array, 0, newArray, num, array.Length);
num += array.Length;
Array.Resize<byte>(ref newArray, num);
return newArray;
}
// Token: 0x060034C9 RID: 13513 RVA: 0x001084C8 File Offset: 0x001066C8
public override void DeserializeMessage(byte[] data)
{
int num = 0;
this.HeroGUID = ArrayManager.ReadUInt64(data, ref num);
this.Denominator = ArrayManager.ReadUInt32(data, ref num);
this.Numerator = ArrayManager.ReadUInt32(data, ref num);
byte[] array = new byte[data.Length - num];
Array.Copy(data, num, array, 0, array.Length);
base.DeserializeMessage(array);
}
// Token: 0x060034CA RID: 13514 RVA: 0x0001C94D File Offset: 0x0001AB4D
private void InitRefTypes()
{
this.HeroGUID = 0UL;
this.Denominator = 0u;
this.Numerator = 0u;
}
}
}
| 34.814286 | 80 | 0.689372 | [
"Unlicense"
] | PermaNulled/OMDUC_EMU_CSharp | OMDUC_EMU/NetworkProtocols/HeroLevelTaskForNetwork.cs | 2,439 | C# |
// Copyright 2011-2016 Chris Patterson, Dru Sellers
//
// 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 Automatonymous.Binders
{
using System;
public interface EventActivityBinder<TInstance> :
EventActivities<TInstance>
where TInstance : class
{
StateMachine<TInstance> StateMachine { get; }
Event Event { get; }
EventActivityBinder<TInstance> Add(Activity<TInstance> activity);
/// <summary>
/// Catch the exception of type T, and execute the compensation chain
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="activityCallback"></param>
/// <returns></returns>
EventActivityBinder<TInstance> Catch<T>(
Func<ExceptionActivityBinder<TInstance, T>, ExceptionActivityBinder<TInstance, T>> activityCallback)
where T : Exception;
/// <summary>
/// Create a conditional branch of activities for processing
/// </summary>
/// <param name="condition"></param>
/// <param name="activityCallback"></param>
/// <returns></returns>
EventActivityBinder<TInstance> If(StateMachineCondition<TInstance> condition,
Func<EventActivityBinder<TInstance>, EventActivityBinder<TInstance>> activityCallback);
}
public interface EventActivityBinder<TInstance, TData> :
EventActivities<TInstance>
where TInstance : class
{
StateMachine<TInstance> StateMachine { get; }
Event<TData> Event { get; }
EventActivityBinder<TInstance, TData> Add(Activity<TInstance> activity);
EventActivityBinder<TInstance, TData> Add(Activity<TInstance, TData> activity);
/// <summary>
/// Catch the exception of type T, and execute the compensation chain
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="activityCallback"></param>
/// <returns></returns>
EventActivityBinder<TInstance, TData> Catch<T>(
Func<ExceptionActivityBinder<TInstance, TData, T>, ExceptionActivityBinder<TInstance, TData, T>> activityCallback)
where T : Exception;
/// <summary>
/// Create a conditional branch of activities for processing
/// </summary>
/// <param name="condition"></param>
/// <param name="activityCallback"></param>
/// <returns></returns>
EventActivityBinder<TInstance, TData> If(StateMachineCondition<TInstance, TData> condition,
Func<EventActivityBinder<TInstance, TData>, EventActivityBinder<TInstance, TData>> activityCallback);
}
} | 40.6625 | 127 | 0.641254 | [
"Apache-2.0"
] | igor-toporet/Automatonymous | src/Automatonymous/Binders/EventActivityBinder.cs | 3,253 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Media.Latest.Inputs
{
/// <summary>
/// Describes the properties of a video overlay.
/// </summary>
public sealed class VideoOverlayArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The gain level of audio in the overlay. The value should be in the range [0, 1.0]. The default is 1.0.
/// </summary>
[Input("audioGainLevel")]
public Input<double>? AudioGainLevel { get; set; }
/// <summary>
/// An optional rectangular window used to crop the overlay image or video.
/// </summary>
[Input("cropRectangle")]
public Input<Inputs.RectangleArgs>? CropRectangle { get; set; }
/// <summary>
/// The end position, with reference to the input video, at which the overlay ends. The value should be in ISO 8601 format. For example, PT30S to end the overlay at 30 seconds into the input video. If not specified or the value is greater than the input video duration, the overlay will be applied until the end of the input video if the overlay media duration is greater than the input video duration, else the overlay will last as long as the overlay media duration.
/// </summary>
[Input("end")]
public Input<string>? End { get; set; }
/// <summary>
/// The duration over which the overlay fades in onto the input video. The value should be in ISO 8601 duration format. If not specified the default behavior is to have no fade in (same as PT0S).
/// </summary>
[Input("fadeInDuration")]
public Input<string>? FadeInDuration { get; set; }
/// <summary>
/// The duration over which the overlay fades out of the input video. The value should be in ISO 8601 duration format. If not specified the default behavior is to have no fade out (same as PT0S).
/// </summary>
[Input("fadeOutDuration")]
public Input<string>? FadeOutDuration { get; set; }
/// <summary>
/// The label of the job input which is to be used as an overlay. The Input must specify exactly one file. You can specify an image file in JPG or PNG formats, or an audio file (such as a WAV, MP3, WMA or M4A file), or a video file. See https://aka.ms/mesformats for the complete list of supported audio and video file formats.
/// </summary>
[Input("inputLabel", required: true)]
public Input<string> InputLabel { get; set; } = null!;
/// <summary>
/// The discriminator for derived types.
/// </summary>
[Input("odataType", required: true)]
public Input<string> OdataType { get; set; } = null!;
/// <summary>
/// The opacity of the overlay. This is a value in the range [0 - 1.0]. Default is 1.0 which mean the overlay is opaque.
/// </summary>
[Input("opacity")]
public Input<double>? Opacity { get; set; }
/// <summary>
/// The location in the input video where the overlay is applied.
/// </summary>
[Input("position")]
public Input<Inputs.RectangleArgs>? Position { get; set; }
/// <summary>
/// The start position, with reference to the input video, at which the overlay starts. The value should be in ISO 8601 format. For example, PT05S to start the overlay at 5 seconds into the input video. If not specified the overlay starts from the beginning of the input video.
/// </summary>
[Input("start")]
public Input<string>? Start { get; set; }
public VideoOverlayArgs()
{
}
}
}
| 47.144578 | 476 | 0.639918 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Media/Latest/Inputs/VideoOverlayArgs.cs | 3,913 | C# |
namespace LibraryApp.Utilities.Constants
{
using System.Collections.Generic;
using LibraryApp.LibrarySystem.Models.LibraryItems;
using LibraryApp.LibrarySystem.Models.People;
using LibraryApp.LibrarySystem.Models.People.Contracts;
public static class GlobalConstants
{
public static List<IPerson> Authors = new List<IPerson>()
{
new Author("Joan", "Rowling", 56),
new Author("Sarah", "Maas", 36),
new Author("Stephen", "King", 74),
new Author("Joe", "Kelly", 51),
new Author("Dan", "Slott", 54),
};
public static List<LibraryItem> Books = new List<LibraryItem>()
{
new Book("Harry Potter and the Philosopher's Stone", (Author)Authors[0], "Novel"),
new Book("Harry Potter and the Chamber of Secrets", (Author)Authors[0], "Novel"),
new Book("Harry Potter and the Prisoner of Azkaban", (Author)Authors[0], "Novel"),
new Book("Harry Potter and the Goblet of Fire", (Author)Authors[0], "Novel"),
new Book("Harry Potter and the Order of the Phoenix", (Author)Authors[0], "Novel"),
new Book("Harry Potter and the Half-Blood Prince", (Author)Authors[0], "Novel"),
new Book("Shine", (Author)Authors[2], "Horror"),
new Book("Pet cemetery", (Author)Authors[2], "Horror"),
new Comics("Savage Spider-Man", (Author)Authors[3], "Superhero"),
new Comics("Fantastic Four: Reckoning War Alpha", (Author)Authors[4], "Superhero"),
new Comics("Ms. Marvel: Metamorphosis", (Author)Authors[4], "Superhero"),
};
public static List<string> BannedGenreForChilds = new List<string>()
{
"Horror",
"True Crime"
};
public static bool IsAppRun = true;
public const string CommandSuffix = "command";
public const string DATE_FORMAT = "MM/dd/yyyy";
}
}
| 40.895833 | 95 | 0.603158 | [
"MIT"
] | Statev7/VTU-Design-Patterns | src/LibraryApp/LibraryApp/Utilities/Constants/GlobalConstants.cs | 1,965 | C# |
namespace NeuSim.Commands.Default
{
using Arguments;
using Context;
using Exceptions;
using Exceptions.Default;
using Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
internal class SimulateCommand : CommandBase<SimulateSubOptions>
{
public SimulateCommand(SessionContext sessionContext)
: base(sessionContext)
{
}
public override string Name
{
get { return "simulate"; }
}
public override bool AllowNotInitialized
{
get { return false; }
}
public override void Run(SimulateSubOptions options)
{
if (this.WriteHelp(options))
{
return;
}
if (options.Files != null)
{
this.RunFiles(options);
return;
}
this.RunSingleInput(options);
}
protected override bool ShouldWriteHelp(SimulateSubOptions options)
{
return options == null || (options.Files == null && options.Input == null);
}
private void RunSingleInput(SimulateSubOptions options)
{
var input = options.Input;
if (input == null)
{
throw new InvalidOperationException();
}
if (!input.Any())
{
this.SessionContext.Output.WriteLine("There is no input values.");
return;
}
var network = this.SessionContext.NeuronNetwork;
if (input.Length != network.InputNo)
{
throw new InvalidInputException(this.SessionContext, input.Length);
}
double result;
try
{
result = network.Process(input);
}
catch (Exception ex)
{
throw new InternalProcessException(this.SessionContext, ex);
}
if (options.IgnoreTransform)
{
this.PrintOutput(input, result);
return;
}
if (options.AgreggateResult)
{
var aggregated = this.SessionContext.AggregateResults(new[] { result });
this.PrintOutput(input, aggregated);
return;
}
var transformed = this.SessionContext.TransformResult(result);
this.PrintOutput(input, transformed);
}
private void RunFiles(SimulateSubOptions options)
{
var files = options.Files;
var results = new List<double>();
foreach (var file in files)
{
var filePath = this.SessionContext.RelativeToAbsolute(file);
if (!File.Exists(file))
{
throw new FileAccessException(this.SessionContext, null, file);
}
var input = filePath.DeserializeFromPath<double[]>();
if (input.Length != this.SessionContext.NeuronNetwork.InputNo)
{
throw new InvalidInputInFileException(this.SessionContext, file, input.Length);
}
double output;
try
{
output = this.SessionContext.NeuronNetwork.Process(input);
}
catch (Exception ex)
{
throw new InternalProcessException(this.SessionContext, ex);
}
if (options.IgnoreTransform)
{
this.WriteToFile(output, file);
}
if (options.AgreggateResult)
{
results.Add(output);
}
else
{
var transformed = this.SessionContext.TransformResult(output);
this.WriteToFile(transformed, file);
}
}
if (options.IgnoreTransform || !options.AgreggateResult)
{
return;
}
var aggregated = this.SessionContext.AggregateResults(results.ToArray());
this.PrintOutput(new double[0], aggregated);
}
private void WriteToFile(string output, string inputFile)
{
var fullFile = this.SessionContext.RelativeToAbsolute(inputFile);
fullFile = Path.GetFileNameWithoutExtension(fullFile) + ".out";
if (File.Exists(fullFile))
{
this.SessionContext.Output.WriteLine("Cannot write output to file {0} - it already exist.", fullFile);
return;
}
File.WriteAllText(fullFile, output);
}
private void WriteToFile(double output, string inputFile)
{
this.WriteToFile(output.ToString("R"), inputFile);
}
private void PrintOutput(IEnumerable<double> inputCase, double output)
{
this.PrintOutput(inputCase, output.ToString("R"));
}
private void PrintOutput(IEnumerable<double> inputCase, string output)
{
this.SessionContext.Output.WriteLine("\t{0}: {1}", string.Join(" ", inputCase), output);
}
private class InvalidInputInFileException : SimException
{
private readonly string file;
private readonly int inputLength;
public InvalidInputInFileException(SessionContext context, string file, int inputLength)
: base(context)
{
this.file = file;
this.inputLength = inputLength;
}
public override void WriteError()
{
this.Context.Output.WriteLine("The file {0} contains invalid input lnegth. Actual: {1}. Desired: {2}",
this.file, this.inputLength, this.Context.NeuronNetwork.InputNo);
}
}
private class InvalidInputException : SimException
{
private readonly int inputNo;
public InvalidInputException(SessionContext context, int inputNo)
: base(context)
{
this.inputNo = inputNo;
}
public override void WriteError()
{
this.Context.Output.WriteLine("The number of input doesn't match network. Acutal: {0}. Desired: {1}",
this.inputNo, this.Context.NeuronNetwork.InputNo);
}
}
private class InternalProcessException : SimException
{
public InternalProcessException(SessionContext context, Exception inner) : base(context, inner) { }
public override void WriteError()
{
this.Context.Output.WriteLine("An internal error occured while simulating input data. Message: {0}",
this.InnerException.Message);
}
}
}
}
| 30.65812 | 118 | 0.517424 | [
"MIT"
] | pwasiewicz/neusim | NeuSim/Commands/Default/SimulateCommand.cs | 7,176 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Specialized;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace SteamAuth
{
/// <summary>
/// Handles logging the user into the mobile Steam website. Necessary to generate OAuth token and session cookies.
/// </summary>
public class UserLogin
{
public string Username;
public string Password;
public ulong SteamID;
public bool RequiresCaptcha;
public string CaptchaGID = null;
public string CaptchaText = null;
public bool RequiresEmail;
public string EmailDomain = null;
public string EmailCode = null;
public bool Requires2FA;
public string TwoFactorCode = null;
public SessionData Session = null;
public bool LoggedIn = false;
private CookieContainer _cookies = new CookieContainer();
public UserLogin(string username, string password)
{
this.Username = username;
this.Password = password;
}
public LoginResult DoLogin()
{
var postData = new NameValueCollection();
var cookies = _cookies;
string response = null;
if (cookies.Count == 0)
{
//Generate a SessionID
cookies.Add(new Cookie("mobileClientVersion", "0 (2.1.3)", "/", ".steamcommunity.com"));
cookies.Add(new Cookie("mobileClient", "android", "/", ".steamcommunity.com"));
cookies.Add(new Cookie("Steam_Language", "english", "/", ".steamcommunity.com"));
NameValueCollection headers = new NameValueCollection();
headers.Add("X-Requested-With", "com.valvesoftware.android.steam.community");
SteamWeb.MobileLoginRequest("https://steamcommunity.com/login?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client", "GET", null, cookies, headers);
}
postData.Add("username", this.Username);
response = SteamWeb.MobileLoginRequest(APIEndpoints.COMMUNITY_BASE + "/login/getrsakey", "POST", postData, cookies);
if (response == null) return LoginResult.GeneralFailure;
var rsaResponse = JsonConvert.DeserializeObject<RSAResponse>(response);
if (!rsaResponse.Success)
{
return LoginResult.BadRSA;
}
RNGCryptoServiceProvider secureRandom = new RNGCryptoServiceProvider();
byte[] encryptedPasswordBytes;
using (var rsaEncryptor = new RSACryptoServiceProvider())
{
var passwordBytes = Encoding.ASCII.GetBytes(this.Password);
var rsaParameters = rsaEncryptor.ExportParameters(false);
//new RSAParameters(); ==> permet de faire l'authentification Steam Guard, mais provoque des Forbidden quand on veut récupérer les offres...
rsaParameters.Exponent = Util.HexStringToByteArray(rsaResponse.Exponent);
rsaParameters.Modulus = Util.HexStringToByteArray(rsaResponse.Modulus);
rsaEncryptor.ImportParameters(rsaParameters);
encryptedPasswordBytes = rsaEncryptor.Encrypt(passwordBytes, false);
}
string encryptedPassword = Convert.ToBase64String(encryptedPasswordBytes);
postData.Clear();
postData.Add("username", this.Username);
postData.Add("password", encryptedPassword);
postData.Add("twofactorcode", this.TwoFactorCode ?? "");
postData.Add("captchagid", this.RequiresCaptcha ? this.CaptchaGID : "-1");
postData.Add("captcha_text", this.RequiresCaptcha ? this.CaptchaText : "");
postData.Add("emailsteamid", (this.Requires2FA || this.RequiresEmail) ? this.SteamID.ToString() : "");
postData.Add("emailauth", this.RequiresEmail ? this.EmailCode : "");
postData.Add("rsatimestamp", rsaResponse.Timestamp);
postData.Add("remember_login", "false");
postData.Add("oauth_client_id", "DE45CD61");
postData.Add("oauth_scope", "read_profile write_profile read_client write_client");
postData.Add("loginfriendlyname", "#login_emailauth_friendlyname_mobile");
postData.Add("donotcache", Util.GetSystemUnixTime().ToString());
response = SteamWeb.MobileLoginRequest(APIEndpoints.COMMUNITY_BASE + "/login/dologin", "POST", postData, cookies);
if (response == null) return LoginResult.GeneralFailure;
var loginResponse = JsonConvert.DeserializeObject<LoginResponse>(response);
if (loginResponse.CaptchaNeeded)
{
this.RequiresCaptcha = true;
this.CaptchaGID = loginResponse.CaptchaGID;
return LoginResult.NeedCaptcha;
}
if (loginResponse.EmailAuthNeeded)
{
this.RequiresEmail = true;
this.SteamID = loginResponse.EmailSteamID;
return LoginResult.NeedEmail;
}
if (loginResponse.TwoFactorNeeded && !loginResponse.Success)
{
this.Requires2FA = true;
return LoginResult.Need2FA;
}
if (loginResponse.OAuthData == null || loginResponse.OAuthData.OAuthToken == null || loginResponse.OAuthData.OAuthToken.Length == 0)
{
return LoginResult.GeneralFailure;
}
if (!loginResponse.LoginComplete)
{
return LoginResult.BadCredentials;
}
else
{
var readableCookies = cookies.GetCookies(new Uri("https://steamcommunity.com"));
var oAuthData = loginResponse.OAuthData;
SessionData session = new SessionData();
session.OAuthToken = oAuthData.OAuthToken;
session.SteamID = oAuthData.SteamID;
session.SteamLogin = session.SteamID + "%7C%7C" + oAuthData.SteamLogin;
session.SteamLoginSecure = session.SteamID + "%7C%7C" + oAuthData.SteamLoginSecure;
session.WebCookie = oAuthData.Webcookie;
session.SessionID = readableCookies["sessionid"].Value;
this.Session = session;
this.LoggedIn = true;
return LoginResult.LoginOkay;
}
return LoginResult.GeneralFailure;
}
private class LoginResponse
{
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("login_complete")]
public bool LoginComplete { get; set; }
[JsonProperty("oauth")]
public string OAuthDataString { get; set; }
public OAuth OAuthData
{
get
{
return OAuthDataString != null ? JsonConvert.DeserializeObject<OAuth>(OAuthDataString) : null;
}
}
[JsonProperty("captcha_needed")]
public bool CaptchaNeeded { get; set; }
[JsonProperty("captcha_gid")]
public string CaptchaGID { get; set; }
[JsonProperty("emailsteamid")]
public ulong EmailSteamID { get; set; }
[JsonProperty("emailauth_needed")]
public bool EmailAuthNeeded { get; set; }
[JsonProperty("requires_twofactor")]
public bool TwoFactorNeeded { get; set; }
internal class OAuth
{
[JsonProperty("steamid")]
public ulong SteamID { get; set; }
[JsonProperty("oauth_token")]
public string OAuthToken { get; set; }
[JsonProperty("wgtoken")]
public string SteamLogin { get; set; }
[JsonProperty("wgtoken_secure")]
public string SteamLoginSecure { get; set; }
[JsonProperty("webcookie")]
public string Webcookie { get; set; }
}
}
private class RSAResponse
{
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("publickey_exp")]
public string Exponent { get; set; }
[JsonProperty("publickey_mod")]
public string Modulus { get; set; }
[JsonProperty("timestamp")]
public string Timestamp { get; set; }
[JsonProperty("steamid")]
public ulong SteamID { get; set; }
}
}
public enum LoginResult
{
LoginOkay,
GeneralFailure,
BadRSA,
BadCredentials,
NeedCaptcha,
Need2FA,
NeedEmail,
}
}
| 36.863636 | 206 | 0.583343 | [
"MIT"
] | Noctisae/SteamBot-H1Z1-Test | SteamAuth/SteamAuth/UserLogin.cs | 8,925 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Eon.Context;
using itrlck = Eon.Threading.InterlockedUtilities;
namespace Eon.Text {
public static class TextUtilities {
public const string TemplateRegexSubstituionGroupName = "SubstitutionMarker";
public const string SquareBracketTemplateRegexPattern = @"\[\[([^\[\]]+)\]([^\[\]]*)\]";
public static readonly Regex SquareBracketTemplateRegex = new Regex(pattern: SquareBracketTemplateRegexPattern, options: RegexOptions.Compiled);
static long __VersionCounter;
static ImmutableDictionary<(string openToken, string closeToken), (Regex regex, long version)> __SubstitutionTemplateRegexCache;
static readonly int __MaxSizeOfSubstitutionRegexCache;
static readonly UnicodeCategory[ ] __SubstitutionOpenTokenSet;
static readonly UnicodeCategory[ ] __SubstitutionCloseTokenSet;
static TextUtilities() {
__VersionCounter = long.MinValue;
__SubstitutionTemplateRegexCache = ImmutableDictionary.Create<(string openToken, string closeToken), (Regex regex, long version)>(keyComparer: EqualityComparer<(string, string)>.Default);
__MaxSizeOfSubstitutionRegexCache = 128;
__SubstitutionOpenTokenSet =
new UnicodeCategory[ ] {
UnicodeCategory.LetterNumber,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.UppercaseLetter,
UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OtherPunctuation,
UnicodeCategory.OpenPunctuation
};
__SubstitutionCloseTokenSet =
new UnicodeCategory[ ] {
UnicodeCategory.LetterNumber,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.UppercaseLetter,
UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OtherPunctuation,
UnicodeCategory.ClosePunctuation
};
}
static bool P_TryGetSubstitutionTemplateRegexFromCache((string openToken, string closeToken) key, out Regex regex) {
if (__MaxSizeOfSubstitutionRegexCache > 0) {
if (itrlck.Get(ref __SubstitutionTemplateRegexCache).TryGetValue(key: key, value: out var value)) {
regex = value.regex;
return true;
}
else {
regex = null;
return false;
}
}
else {
regex = null;
return false;
}
}
static bool P_TryPutSubstitutionTemplateRegexInCache((string openToken, string closeToken) key, Regex regex) {
if (__MaxSizeOfSubstitutionRegexCache > 0) {
ImmutableInterlocked
.Update(
location: ref __SubstitutionTemplateRegexCache,
transformer:
locCurrent => {
var locNewVersion = itrlck.Increment(location: ref __VersionCounter, maxInclusive: long.MaxValue, locationName: $"{nameof(TextUtilities)}.{nameof(__VersionCounter)}");
if (locCurrent.Count < __MaxSizeOfSubstitutionRegexCache || locCurrent.ContainsKey(key: key))
return locCurrent.SetItem(key: key, value: (regex: regex, version: locNewVersion));
else {
var locSelectedReplaceVersion = long.MaxValue;
var locSelectedReplaceKey = default((string substitutionStartToken, string substitutionEndToken));
foreach (var locItem in locCurrent) {
if (locItem.Value.version <= locSelectedReplaceVersion) {
locSelectedReplaceVersion = locItem.Value.version;
locSelectedReplaceKey = locItem.Key;
}
}
return locCurrent.Remove(key: locSelectedReplaceKey).Add(key: key, value: (regex: regex, version: locNewVersion));
}
});
return true;
}
else
return false;
}
static Regex P_GetSubstitutionTemplateRegex(string openToken, string closeToken) {
openToken.EnsureNotNull(nameof(openToken)).EnsureHasMaxLength(maxLength: 8).EnsureNotEmptyOrWhiteSpace();
closeToken.EnsureNotNull(nameof(closeToken)).EnsureHasMaxLength(maxLength: 8).EnsureNotEmptyOrWhiteSpace();
//
if (!P_TryGetSubstitutionTemplateRegexFromCache(key: (openToken: openToken, closeToken: closeToken), regex: out var regex)) {
openToken.Arg(nameof(openToken)).EnsureSubset(categories: __SubstitutionOpenTokenSet).EnsureContains(category: UnicodeCategory.OpenPunctuation);
closeToken.Arg(nameof(closeToken)).EnsureSubset(categories: __SubstitutionCloseTokenSet).EnsureContains(category: UnicodeCategory.ClosePunctuation);
var sb = new StringBuilder();
sb.Append('(');
for (var y = 0; y < openToken.Length; y++)
appendRegexPattern(sb, openToken[ y ]);
sb.Append(@"(?<");
sb.Append(TemplateRegexSubstituionGroupName);
sb.Append(@">[^");
for (var y = 0; y < openToken.Length; y++)
appendRegexPattern(sb, openToken[ y ]);
for (var y = 0; y < closeToken.Length; y++)
appendRegexPattern(sb, closeToken[ y ]);
sb.Append('\\');
sb.Append("n]+)");
for (var y = 0; y < closeToken.Length; y++)
appendRegexPattern(sb, closeToken[ y ]);
sb.Append(')');
regex = new Regex(pattern: sb.ToString(), options: RegexOptions.Compiled);
P_TryPutSubstitutionTemplateRegexInCache(key: (openToken: openToken, closeToken: closeToken), regex: regex);
}
return regex;
//
void appendRegexPattern(StringBuilder sb, char ch) {
switch (char.GetUnicodeCategory(c: ch)) {
case UnicodeCategory.LetterNumber:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.DecimalDigitNumber:
sb.Append(ch);
break;
default:
sb.Append('\\');
sb.Append(ch);
break;
}
}
}
// TODO: Put strings into the resources.
//
static string P_GetSubstitutionValue(in TextTemplateVar var, bool required, IReadOnlyDictionary<string, string> values) {
var key = var.Var.PropArg($"{nameof(var)}.{nameof(var.Var)}").EnsureNotNull().Value;
values.EnsureNotNull(nameof(values));
//
if (values.TryGetValue(key: key, value: out var value))
return value;
else if (required)
throw new KeyNotFoundException(message: $"Specified dictionary doesn't contain a value for the specified name.{Environment.NewLine}\tName:{key.FmtStr().GNLI2()}");
else
return null;
}
/// <summary>
/// Substitutes variables with a values provided by <paramref name="substitutor"/>.
/// </summary>
/// <typeparam name="TState">Constraint of the user state type.</typeparam>
/// <param name="openToken">
/// The opening token of the variable's span.
/// <para>Can't be <see langword="null"/>, <see cref="string.Empty"/> or whitespace string.</para>
/// <para>Length can't be greater than <see langword="8"/>.</para>
/// </param>
/// <param name="closeToken">
/// The closing token of the variable's span.
/// <para>Can't be <see langword="null"/>, <see cref="string.Empty"/> or whitespace string.</para>
/// <para>Length can't be greater than <see langword="8"/>.</para>
/// </param>
/// <param name="template">Template.</param>
/// <param name="substitutor">
/// Maps the variable name to a value. That value will be placed instead of variable's span in the template.
/// <para>Can't be <see langword="null"/>.</para>
/// </param>
/// <param name="state">
/// User state that passes to <paramref name="substitutor"/>.
/// </param>
/// <param name="culture">
/// Default culture to be used for substitution.
/// </param>
/// <param name="filter">
/// Special method to filter the variables to be substituted.
/// <para><see langword="true"/> — substitute the variable, variable value will be taken from <paramref name="substitutor"/> method.</para>
/// <para><see langword="false"/> — skip the variable (see <paramref name="filterThrows"/>).</para>
/// </param>
/// <param name="filterThrows">
/// Indicates whether an exception should be thrown when the variable don't match to the <paramref name="filter"/>.
/// <para><see langword="false"/> — the variable's span will be passed to result string as is.</para>
/// </param>
/// <param name="ctx">
/// Operation context.
/// </param>
public static async Task<string> SubstituteTemplateAsync<TState>(
string openToken,
string closeToken,
string template,
Func<(TextTemplateVar var, CultureInfo culture, TState state, IContext ctx), Task<string>> substitutor,
TState state,
CultureInfo culture = default,
InParamFunc<TextTemplateVar, bool> filter = default,
bool filterThrows = default,
IContext ctx = default) {
//
openToken.EnsureNotNull(nameof(openToken)).EnsureHasMaxLength(maxLength: 8).EnsureNotEmptyOrWhiteSpace();
closeToken.EnsureNotNull(nameof(closeToken)).EnsureHasMaxLength(maxLength: 8).EnsureNotEmptyOrWhiteSpace();
substitutor.EnsureNotNull(nameof(substitutor));
//
ctx.ThrowIfCancellationRequested();
//
if (string.IsNullOrEmpty(template))
return template;
else {
var vars = GetTemplateVariables(openToken: openToken, closeToken: closeToken, template: template);
if (vars.Length > 0) {
using (var buffer = EonStringBuilderUtilities.AcquireBuffer()) {
var sb = buffer.StringBuilder;
var varsUpperBound = vars.Length - 1;
var templateReadPosition = 0;
var templateUpperIndex = template.Length - 1;
for (var i = 0; ; i++) {
ctx.ThrowIfCancellationRequested();
//
var templateForepartLength = vars[ i ].SpanStart - templateReadPosition;
if (templateForepartLength != 0)
sb.Append(value: template, startIndex: templateReadPosition, count: templateForepartLength);
templateReadPosition = vars[ i ].SpanStart + vars[ i ].SpanLength;
string variableSubstitution;
if (filter?.Invoke(arg: in vars[ i ]) ?? true)
variableSubstitution = await substitutor(arg: (var: vars[ i ], culture, state, ctx)).ConfigureAwait(false);
else if (filterThrows)
throw new EonException(message: $"Template variable not match the specified filter and not allowed to be substituted.{Environment.NewLine}\tVariable:{vars[ i ].Var.FmtStr().GNLI2()}");
else
variableSubstitution = vars[ i ].Span;
sb.Append(value: variableSubstitution);
if (i == varsUpperBound) {
var templateTailLength = template.Length - templateReadPosition;
if (templateTailLength != 0)
sb.Append(value: template, startIndex: templateReadPosition, count: templateTailLength);
break;
}
}
return sb.ToString();
}
}
else
return template;
}
}
/// <summary>
/// Substitutes variables with a values provided by <paramref name="substitutor"/>.
/// </summary>
/// <param name="openToken">
/// The opening token of the variable's span.
/// <para>Can't be <see langword="null"/>, <see cref="string.Empty"/> or whitespace string.</para>
/// <para>Length can't be greater than <see langword="8"/>.</para>
/// </param>
/// <param name="closeToken">
/// The closing token of the variable's span.
/// <para>Can't be <see langword="null"/>, <see cref="string.Empty"/> or whitespace string.</para>
/// <para>Length can't be greater than <see langword="8"/>.</para>
/// </param>
/// <param name="template">Template.</param>
/// <param name="substitutor">
/// Maps the variable name to a value. That value will be placed instead of variable's span in the template.
/// <para>Can't be <see langword="null"/>.</para>
/// </param>
/// <param name="culture">
/// Default culture to be used for substitution.
/// </param>
/// <param name="filter">
/// Special method to filter the variables to be substituted.
/// <para><see langword="true"/> — substitute the variable, variable value will be taken from <paramref name="substitutor"/> method.</para>
/// <para><see langword="false"/> — skip the variable (see <paramref name="filterThrows"/>).</para>
/// </param>
/// <param name="filterThrows">
/// Indicates whether an exception should be thrown when the variable don't match to the <paramref name="filter"/>.
/// <para><see langword="false"/> — the variable's span will be passed to result string as is.</para>
/// </param>
/// <param name="ctx">
/// Operation context.
/// </param>
public static async Task<string> SubstituteTemplateAsync(
string openToken,
string closeToken,
string template,
Func<(TextTemplateVar var, CultureInfo culture, IContext ctx), Task<string>> substitutor,
CultureInfo culture = default,
InParamFunc<TextTemplateVar, bool> filter = default,
bool filterThrows = default,
IContext ctx = default) {
substitutor.EnsureNotNull(nameof(substitutor));
//
return await SubstituteTemplateAsync(openToken: openToken, closeToken: closeToken, template: template, substitutor: locSubstitutor, state: Nil.Value, culture: culture, filter: filter, filterThrows: filterThrows, ctx: ctx).ConfigureAwait(false);
//
async Task<string> locSubstitutor((TextTemplateVar var, CultureInfo culture, Nil state, IContext ctx) locArgs)
=> await substitutor(arg: (locArgs.var, locArgs.culture, locArgs.ctx)).ConfigureAwait(false);
}
/// <summary>
/// Substitutes variables with a values provided by <paramref name="values"/>.
/// </summary>
/// <param name="openToken">
/// The opening token of the variable's span.
/// <para>Can't be <see langword="null"/>, <see cref="string.Empty"/> or whitespace string.</para>
/// <para>Length can't be greater than <see langword="8"/>.</para>
/// </param>
/// <param name="closeToken">
/// The closing token of the variable's span.
/// <para>Can't be <see langword="null"/>, <see cref="string.Empty"/> or whitespace string.</para>
/// <para>Length can't be greater than <see langword="8"/>.</para>
/// </param>
/// <param name="template">Template.</param>
/// <param name="values">
/// Maps the variable name to a value. That value will be placed instead of variable's span in the template.
/// <para>Can't be <see langword="null"/>.</para>
/// </param>
/// <param name="culture">
/// Culture to be used for formatting.
/// </param>
/// <param name="filter">
/// Special method to filter the variables to be substituted.
/// <para><see langword="true"/> — substitute the variable, variable value will be taken from <paramref name="values"/> method.</para>
/// <para><see langword="false"/> — skip the variable (see <paramref name="filterThrows"/>).</para>
/// </param>
/// <param name="filterThrows">
/// Indicates whether an exception should be thrown when the variable don't match to the <paramref name="filter"/>.
/// <para><see langword="false"/> — the variable's span will be passed to result string as is.</para>
/// </param>
/// <param name="ctx">
/// Operation context.
/// </param>
public static async Task<string> SubstituteTemplateAsync(
string openToken,
string closeToken,
string template,
ITextTemplateVarSubstitution values,
CultureInfo culture = default,
InParamFunc<TextTemplateVar, bool> filter = default,
bool filterThrows = default,
IContext ctx = default) {
//
values.EnsureNotNull(nameof(values));
//
return await SubstituteTemplateAsync(openToken: openToken, closeToken: closeToken, template: template, substitutor: locSubstitutor, state: values, culture: culture, filter: filter, filterThrows: filterThrows, ctx: ctx).ConfigureAwait(false);
//
async Task<string> locSubstitutor((TextTemplateVar var, CultureInfo culture, ITextTemplateVarSubstitution state, IContext ctx) locArgs)
=> await locArgs.state.SubstituteAsync(var: locArgs.var, culture: locArgs.culture, ctx: locArgs.ctx).ConfigureAwait(false);
}
public static string SubstituteTemplate(string openToken, string closeToken, string template, InParamFunc<TextTemplateVar, string> substitutor) {
openToken.EnsureNotNull(nameof(openToken)).EnsureHasMaxLength(maxLength: 8).EnsureNotEmptyOrWhiteSpace();
closeToken.EnsureNotNull(nameof(closeToken)).EnsureHasMaxLength(maxLength: 8).EnsureNotEmptyOrWhiteSpace();
substitutor.EnsureNotNull(nameof(substitutor));
//
if (string.IsNullOrEmpty(template))
return template;
else {
var regex = P_GetSubstitutionTemplateRegex(openToken: openToken, closeToken: closeToken);
return
regex
.Replace(
input: template,
evaluator:
locMatch => {
var locGroup = locMatch.Groups[ TemplateRegexSubstituionGroupName ];
if (locGroup?.Success == true) {
var locVar = new TextTemplateVar(template: template, span: locMatch.Value, spanStart: locMatch.Index, spanLength: locMatch.Length, var: locGroup.Value);
return substitutor(arg: in locVar);
}
else
return default;
});
}
}
public static string SubstituteTemplate(string openToken, string closeToken, string template, ITextTemplateVarSubstitution values, CultureInfo culture = default) {
values.EnsureNotNull(nameof(values));
//
return SubstituteTemplate(openToken: openToken, closeToken: closeToken, template: template, substitutor: locSubstitutor);
//
string locSubstitutor(in TextTemplateVar locVar)
=> values.Substitute(var: in locVar, culture: culture, ctx: null);
}
public static string SubstituteTemplate(string openToken, string closeToken, string template, IReadOnlyDictionary<string, string> values) {
values.EnsureNotNull(nameof(values));
//
return
SubstituteTemplate(
openToken: openToken,
closeToken: closeToken,
template: template,
substitutor:
(in TextTemplateVar locVar)
=>
P_GetSubstitutionValue(var: in locVar, values: values, required: true));
}
public static string SubstituteBraceTemplate(string template, InParamFunc<TextTemplateVar, string> substitutor)
=> SubstituteTemplate(openToken: "{", closeToken: "}", template: template, substitutor: substitutor);
public static string SubstituteBraceTemplate(string template, ITextTemplateVarSubstitution values, CultureInfo culture = default) {
values.EnsureNotNull(nameof(values));
//
return SubstituteBraceTemplate(template: template, substitutor: locSubstitutor);
//
string locSubstitutor(in TextTemplateVar locVar)
=> values.Substitute(var: in locVar, culture: culture, ctx: null);
}
public static string SubstituteBraceTemplate(string template, IReadOnlyDictionary<string, string> values) {
values.EnsureNotNull(nameof(values));
//
return SubstituteBraceTemplate(template: template, substitutor: (in TextTemplateVar locVar) => P_GetSubstitutionValue(var: in locVar, values: values, required: true));
}
public static TextTemplateVar[ ] GetTemplateVariables(string openToken, string closeToken, string template) {
template.EnsureNotNull(nameof(template));
//
if (template.Length < 2)
return new TextTemplateVar[ 0 ];
else {
var regex = P_GetSubstitutionTemplateRegex(openToken: openToken, closeToken: closeToken);
return
regex
.Matches(input: template)
.Cast<Match>()
.Where(locMatch => locMatch.Success)
.Select(
locMatch => {
var locGroup = locMatch.Groups[ TemplateRegexSubstituionGroupName ];
if (locGroup?.Success == true)
return new TextTemplateVar(template: template, span: locMatch.Value, spanStart: locMatch.Index, spanLength: locMatch.Length, var: locGroup.Value);
else
return default;
})
.Where(locItem => !(locItem.Template is null))
.ToArray();
}
}
// TODO: Put exception messages into the resources.
//
public static string GetEncodingWebName(KnownEncodingWebName webName) {
if (webName == KnownEncodingWebName.Cyrillic_Windows)
return "windows-1251";
else if (webName == KnownEncodingWebName.Cyrillic_Dos)
return "cp866";
else if (webName == KnownEncodingWebName.UTF8)
return Encoding.UTF8.WebName;
else
throw new ArgumentOutOfRangeException(paramName: nameof(webName), message: $"Указанное значение '{webName}' не поддерживается.");
}
// TODO: Put strings into the resources.
//
/// <summary>
/// Выполняет парсинг набора пар ключ-значение из строки.
/// </summary>
/// <param name="input">Входная строка, представляющая набор пар ключ-значение.</param>
/// <param name="keyComparer">
/// Компаратор ключей, используемый для проверки уникальности ключей.
/// <para>По умолчанию используется <see cref="StringComparer"/>.<see cref="StringComparer.OrdinalIgnoreCase"/>.</para>
/// </param>
/// <param name="keyValueDelimiter">
/// Символ-разделитель ключа и значения.
/// <para>По умолчанию используется '='.</para>
/// </param>
/// <param name="keyValuePairDelimiter">
/// Символ-разделитель пар ключ-значение.
/// <para>По умолчанию используется ';'.</para>
/// </param>
/// <param name="escapeDelimiterMarker">
/// Символ отмены (экранирования).
/// <para>По умолчанию используется '/'.</para>
/// </param>
/// <param name="inputArgName">Альтернативное имя аргумента <paramref name="input"/> входной строки. Используется для указания в исключениях <see cref="ArgumentException"/>, которые могут быть вызваны данным методом. Если имеет значение null или <see cref="string.Empty"/>, то используется имя <paramref name="input"/>.</param>
/// <returns>Словарь пар ключ-значение.</returns>
public static IDictionary<string, string> ParseKeyValuePairs(
this string input,
StringComparer keyComparer = default,
char keyValueDelimiter = '=',
char keyValuePairDelimiter = ';',
char escapeDelimiterMarker = '/',
string inputArgName = default)
=> ArgumentUtilitiesCoreL1.ParseKeyValuePairs(argument: input.Arg(string.IsNullOrEmpty(inputArgName) ? nameof(input) : inputArgName), keyComparer: keyComparer, keyValueDelimiter: keyValueDelimiter, keyValuePairDelimiter: keyValuePairDelimiter, escapeDelimiterMarker: escapeDelimiterMarker);
}
} | 44.012 | 329 | 0.704808 | [
"MIT"
] | vitalik-mironov/eon-lib | src/eon-lib.core.level-2/Text/TextUtilities.cs | 22,557 | C# |
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Net;
using FastReport.Utils;
using System.Globalization;
using System.Collections;
namespace FastReport.Data
{
internal static class CsvUtils
{
/// <summary>
/// The default field name.
/// </summary>
public const string DEFAULT_FIELD_NAME = "Field";
private static void DetermineTypes(List<string[]> lines, DataTable table, NumberFormatInfo numberInfo, NumberFormatInfo currencyInfo, DateTimeFormatInfo dateTimeInfo)
{
int intTemp;
double doubleTemp;
decimal decimalTemp;
DateTime dateTemp;
for (int i = 0; i < table.Columns.Count; i++)
{
// gather types here
Dictionary<Type, int> types = new Dictionary<Type, int>();
// check all values in the column
for (int j = 0; j < lines.Count; j++)
{
if (i >= lines[j].Length)
{
// number of values is less than number of table columns. Reasons: wrong separator or bad-formed csv file?
// just skip this line
}
else
{
string value = lines[j][i];
if (!String.IsNullOrEmpty(value))
{
if (Int32.TryParse(value, out intTemp))
{
types[typeof(Int32)] = 1;
}
else if (value.Contains(currencyInfo.CurrencySymbol) && Decimal.TryParse(value, NumberStyles.Currency, currencyInfo, out decimalTemp))
{
types[typeof(Decimal)] = 1;
}
else if (Double.TryParse(value, NumberStyles.Number, numberInfo, out doubleTemp))
{
types[typeof(Double)] = 1;
}
else if (DateTime.TryParse(value, dateTimeInfo, DateTimeStyles.NoCurrentDateDefault, out dateTemp))
{
types[typeof(DateTime)] = 1;
}
else
{
types[typeof(String)] = 1;
break;
}
}
}
}
// cases allowed:
// - single type -> the type
// - mix of ints and doubles -> double
// - all others should not be mixed -> string
Type guessType = typeof(String);
if (types.Count == 1)
{
// get a single value this way
foreach (Type t in types.Keys)
{
guessType = t;
}
}
else if (types.Count == 2 && types.ContainsKey(typeof(Int32)) && types.ContainsKey(typeof(Double)))
{
guessType = typeof(Double);
}
table.Columns[i].DataType = guessType;
}
}
internal static List<string> ReadLines(CsvConnectionStringBuilder builder, int maxLines = 0)
{
if (String.IsNullOrEmpty(builder.CsvFile) || String.IsNullOrEmpty(builder.Separator))
return null;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
WebRequest request;
WebResponse response = null;
try
{
Uri uri = new Uri(builder.CsvFile);
if (uri.IsFile)
{
if (Config.ForbidLocalData)
throw new Exception(Res.Get("ConnectionEditors,Common,OnlyUrlException"));
request = (FileWebRequest)WebRequest.Create(uri);
request.Timeout = 5000;
response = (FileWebResponse)request.GetResponse();
}
else if (uri.OriginalString.StartsWith("http"))
{
request = (HttpWebRequest)WebRequest.Create(uri);
request.Timeout = 5000;
response = (HttpWebResponse)request.GetResponse();
}
else if (uri.OriginalString.StartsWith("ftp"))
{
request = (FtpWebRequest)WebRequest.Create(uri);
request.Timeout = 5000;
response = (FtpWebResponse)request.GetResponse();
}
}
catch (Exception e)
{
throw e;
}
if (response == null)
return null;
List<string> lines = new List<string>();
if (maxLines == 0)
maxLines = int.MaxValue;
// read lines
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(builder.Codepage)))
{
for (int i = 0; i < maxLines; i++)
{
string line = reader.ReadLine();
// end of stream reached
if (line == null)
break;
// skip empty lines
if (!String.IsNullOrEmpty(line))
lines.Add(line);
}
}
return lines;
}
internal static DataTable CreateDataTable(CsvConnectionStringBuilder builder, List<string> rawLines)
{
if (rawLines == null)
return null;
// split each line to array of values
List<string[]> lines = new List<string[]>();
for (int i = 0; i < rawLines.Count; i++)
{
string line = rawLines[i];
string[] values = line.Split(builder.Separator.ToCharArray());
if (builder.RemoveQuotationMarks)
{
for (int j = 0; j < values.Length; j++)
{
values[j] = values[j].Trim("\"".ToCharArray());
}
}
lines.Add(values);
}
if (lines.Count == 0)
return null;
NumberFormatInfo numberInfo = CultureInfo.GetCultureInfo(builder.NumberFormat)?.NumberFormat ?? CultureInfo.CurrentCulture.NumberFormat;
NumberFormatInfo currencyInfo = CultureInfo.GetCultureInfo(builder.CurrencyFormat)?.NumberFormat ?? CultureInfo.CurrentCulture.NumberFormat;
DateTimeFormatInfo dateTimeInfo = CultureInfo.GetCultureInfo(builder.DateTimeFormat)?.DateTimeFormat ?? CultureInfo.CurrentCulture.DateTimeFormat;
// get table name from file name
string tableName = Path.GetFileNameWithoutExtension(builder.CsvFile).Replace(".", "_");
if (String.IsNullOrEmpty(tableName))
{
tableName = "Table";
}
DataTable table = new DataTable(tableName);
string[] fields = lines[0];
// create table columns
for (int i = 0; i < fields.Length; i++)
{
DataColumn column = new DataColumn();
column.DataType = typeof(string);
// get field names from first string if needed
string fieldName = fields[i].Replace("\t", "");
if (builder.FieldNamesInFirstString && !table.Columns.Contains(fieldName))
{
column.ColumnName = fieldName;
column.Caption = column.ColumnName;
}
else
{
column.ColumnName = DEFAULT_FIELD_NAME + i.ToString();
column.Caption = column.ColumnName;
}
table.Columns.Add(column);
}
int startIndex = builder.FieldNamesInFirstString ? 1 : 0;
// cast types of fields if needed
if (builder.ConvertFieldTypes)
{
int number = lines.Count - startIndex;
DetermineTypes(lines.GetRange(startIndex, number), table, numberInfo, currencyInfo, dateTimeInfo);
}
// add table rows
for (int i = startIndex; i < lines.Count; i++)
{
if (lines[i].Length > 0)
{
// get values from the string
fields = lines[i];
// add a new row
DataRow row = table.NewRow();
int valuesCount = fields.Length < table.Columns.Count ? fields.Length : table.Columns.Count;
for (int j = 0; j < valuesCount; j++)
{
string value = fields[j];
if (!String.IsNullOrEmpty(value))
{
if (table.Columns[j].DataType == typeof(String))
{
row[j] = value;
}
else if (table.Columns[j].DataType == typeof(Int32))
{
row[j] = Int32.Parse(value);
}
else if (table.Columns[j].DataType == typeof(Decimal))
{
row[j] = Decimal.Parse(value, NumberStyles.Currency, currencyInfo);
}
else if (table.Columns[j].DataType == typeof(Double))
{
row[j] = Double.Parse(value, NumberStyles.Number, numberInfo);
}
else if (table.Columns[j].DataType == typeof(DateTime))
{
row[j] = DateTime.Parse(value, dateTimeInfo);
}
}
}
table.Rows.Add(row);
}
}
return table;
}
}
}
| 38.724638 | 174 | 0.450225 | [
"MIT"
] | anikolop/FastReport | FastReport.Base/Data/CsvUtils.cs | 10,688 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Security.Cryptography
{
internal static partial class ECDiffieHellmanImplementation
{
public sealed partial class ECDiffieHellmanCngPublicKey : ECDiffieHellmanPublicKey
{
private byte[] _keyBlob;
internal string? _curveName;
protected override void Dispose(bool disposing)
{
_keyBlob = null!;
base.Dispose(disposing);
}
public override string ToXmlString()
{
throw new PlatformNotSupportedException();
}
public static ECDiffieHellmanCngPublicKey FromXmlString(string xml)
{
throw new PlatformNotSupportedException();
}
internal ECDiffieHellmanCngPublicKey(byte[] keyBlob, string? curveName) : base(keyBlob)
{
Debug.Assert(keyBlob != null);
_keyBlob = keyBlob;
_curveName = curveName;
}
/// <summary>
/// Exports the key and explicit curve parameters used by the ECC object into an <see cref="ECParameters"/> object.
/// </summary>
/// <exception cref="CryptographicException">
/// if there was an issue obtaining the curve values.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// if explicit export is not supported by this platform. Windows 10 or higher is required.
/// </exception>
/// <returns>The key and explicit curve parameters used by the ECC object.</returns>
public override ECParameters ExportExplicitParameters()
{
if (_keyBlob == null)
{
throw new ObjectDisposedException(nameof(ECDiffieHellmanPublicKey));
}
ECParameters ecparams = default;
ECCng.ExportPrimeCurveParameters(ref ecparams, _keyBlob, includePrivateParameters: false);
return ecparams;
}
/// <summary>
/// Exports the key used by the ECC object into an <see cref="ECParameters"/> object.
/// If the key was created as a named curve, the Curve property will contain named curve parameters
/// otherwise it will contain explicit parameters.
/// </summary>
/// <exception cref="CryptographicException">
/// if there was an issue obtaining the curve values.
/// </exception>
/// <returns>The key and named curve parameters used by the ECC object.</returns>
public override ECParameters ExportParameters()
{
if (_keyBlob == null)
{
throw new ObjectDisposedException(nameof(ECDiffieHellmanPublicKey));
}
if (string.IsNullOrEmpty(_curveName))
{
return ExportExplicitParameters();
}
else
{
ECParameters ecparams = default;
ECCng.ExportNamedCurveParameters(ref ecparams, _keyBlob, includePrivateParameters: false);
ecparams.Curve = ECCurve.CreateFromFriendlyName(_curveName);
return ecparams;
}
}
}
}
}
| 39.322581 | 128 | 0.564124 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs | 3,657 | C# |
namespace GreenTomato.Library.Models
{
public class MovieMX : IMovie
{
}
} | 12.428571 | 36 | 0.655172 | [
"MIT"
] | martinfitzjerl/Samuel-Code | GreenTomato.Library/Models/MovieMX.cs | 87 | 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("pc2x.Application.WebServices.WCF.Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("pc2x.Application.WebServices.WCF.Library")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4906eb59-32fa-4dba-bb09-b03bce016fed")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.27027 | 84 | 0.749484 | [
"MIT"
] | pc2x/Wcf_WebApi_Test | pc2x.Application/pc2x.Application.WebServices.WCF.Library/Properties/AssemblyInfo.cs | 1,456 | 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 discovery-2015-11-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.ApplicationDiscoveryService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ApplicationDiscoveryService.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DeleteTags operation
/// </summary>
public class DeleteTagsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DeleteTagsResponse response = new DeleteTagsResponse();
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("AuthorizationErrorException"))
{
return AuthorizationErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("HomeRegionNotSetException"))
{
return HomeRegionNotSetExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterException"))
{
return InvalidParameterExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValueException"))
{
return InvalidParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServerInternalErrorException"))
{
return ServerInternalErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonApplicationDiscoveryServiceException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DeleteTagsResponseUnmarshaller _instance = new DeleteTagsResponseUnmarshaller();
internal static DeleteTagsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteTagsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.285714 | 210 | 0.657236 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/ApplicationDiscoveryService/Generated/Model/Internal/MarshallTransformations/DeleteTagsResponseUnmarshaller.cs | 4,913 | C# |
// =================================================================================================================================
// Copyright (c) RapidField LLC. Licensed under the MIT License. See LICENSE.txt in the project root for license information.
// =================================================================================================================================
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RapidField.SolidInstruments.Cryptography.Asymmetric.DigitalSignature;
using RapidField.SolidInstruments.Cryptography.Asymmetric.KeyExchange;
using RapidField.SolidInstruments.Cryptography.Extensions;
using System.Security.Cryptography;
namespace RapidField.SolidInstruments.Cryptography.UnitTests.Extensions
{
[TestClass]
public class AlgorithmSpecificationExtensionsTests
{
[TestMethod]
public void ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForBrainpoolP256r1()
{
// Arrange.
var curve = ECCurve.NamedCurves.brainpoolP256r1;
var keyExchangeSpecification = KeyExchangeAlgorithmSpecification.EcdhBrainpoolP256r1;
var digitalSignatureSpecification = DigitalSignatureAlgorithmSpecification.EcdsaBrainpoolP256r1;
// Assert.
ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForEllipticCurveAlgorithms(curve, keyExchangeSpecification, digitalSignatureSpecification);
}
[TestMethod]
public void ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForBrainpoolP384r1()
{
// Arrange.
var curve = ECCurve.NamedCurves.brainpoolP384r1;
var keyExchangeSpecification = KeyExchangeAlgorithmSpecification.EcdhBrainpoolP384r1;
var digitalSignatureSpecification = DigitalSignatureAlgorithmSpecification.EcdsaBrainpoolP384r1;
// Assert.
ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForEllipticCurveAlgorithms(curve, keyExchangeSpecification, digitalSignatureSpecification);
}
[TestMethod]
public void ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForBrainpoolP512r1()
{
// Arrange.
var curve = ECCurve.NamedCurves.brainpoolP512r1;
var keyExchangeSpecification = KeyExchangeAlgorithmSpecification.EcdhBrainpoolP512r1;
var digitalSignatureSpecification = DigitalSignatureAlgorithmSpecification.EcdsaBrainpoolP512r1;
// Assert.
ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForEllipticCurveAlgorithms(curve, keyExchangeSpecification, digitalSignatureSpecification);
}
[TestMethod]
public void ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForNistP256()
{
// Arrange.
var curve = ECCurve.NamedCurves.nistP256;
var keyExchangeSpecification = KeyExchangeAlgorithmSpecification.EcdhNistP256;
var digitalSignatureSpecification = DigitalSignatureAlgorithmSpecification.EcdsaNistP256;
// Assert.
ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForEllipticCurveAlgorithms(curve, keyExchangeSpecification, digitalSignatureSpecification);
}
[TestMethod]
public void ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForNistP384()
{
// Arrange.
var curve = ECCurve.NamedCurves.nistP384;
var keyExchangeSpecification = KeyExchangeAlgorithmSpecification.EcdhNistP384;
var digitalSignatureSpecification = DigitalSignatureAlgorithmSpecification.EcdsaNistP384;
// Assert.
ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForEllipticCurveAlgorithms(curve, keyExchangeSpecification, digitalSignatureSpecification);
}
[TestMethod]
public void ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForNistP521()
{
// Arrange.
var curve = ECCurve.NamedCurves.nistP521;
var keyExchangeSpecification = KeyExchangeAlgorithmSpecification.EcdhNistP521;
var digitalSignatureSpecification = DigitalSignatureAlgorithmSpecification.EcdsaNistP521;
// Assert.
ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForEllipticCurveAlgorithms(curve, keyExchangeSpecification, digitalSignatureSpecification);
}
private static void ExtensionMappingOutput_ShouldMatchRelevantDotNetAnalogs_ForEllipticCurveAlgorithms(ECCurve curve, KeyExchangeAlgorithmSpecification keyExchangeSpecification, DigitalSignatureAlgorithmSpecification digitalSignatureSpecification)
{
// Arrange.
using var ecdhAlgorithm = ECDiffieHellman.Create(curve);
using var ecdsaAlgorithm = ECDsa.Create(curve);
var expectedEcdhPrivateKeyLengthInBytes = ecdhAlgorithm.ExportECPrivateKey().Length;
var expectedEcdhPublicKeyLengthInBytes = ecdhAlgorithm.PublicKey.ToByteArray().Length;
var expectedEcdsaPrivateKeyLengthInBytes = ecdsaAlgorithm.ExportECPrivateKey().Length;
var expectedEcdsaPublicKeyLengthInBytes = ecdsaAlgorithm.ExportSubjectPublicKeyInfo().Length;
// Act.
var actualEcdhCurve = keyExchangeSpecification.ToCurve();
var actualEcdsaCurve = digitalSignatureSpecification.ToCurve();
var actualEcdhPrivateKeyLengthInBytes = keyExchangeSpecification.ToPrivateKeyBitLength() / 8;
var actualEcdhPublicKeyLengthInBytes = keyExchangeSpecification.ToPublicKeyBitLength() / 8;
var actualEcdsaPrivateKeyLengthInBytes = digitalSignatureSpecification.ToPrivateKeyBitLength() / 8;
var actualEcdsaPublicKeyLengthInBytes = digitalSignatureSpecification.ToPublicKeyBitLength() / 8;
// Assert.
actualEcdhCurve.Oid.FriendlyName.Should().Be(curve.Oid.FriendlyName);
actualEcdsaCurve.Oid.FriendlyName.Should().Be(curve.Oid.FriendlyName);
actualEcdhPrivateKeyLengthInBytes.Should().Be(expectedEcdhPrivateKeyLengthInBytes);
actualEcdhPublicKeyLengthInBytes.Should().Be(expectedEcdhPublicKeyLengthInBytes);
actualEcdsaPrivateKeyLengthInBytes.Should().Be(expectedEcdsaPrivateKeyLengthInBytes);
actualEcdsaPublicKeyLengthInBytes.Should().Be(expectedEcdsaPublicKeyLengthInBytes);
}
}
} | 55.853448 | 255 | 0.721253 | [
"MIT"
] | RapidField/solid-instruments | test/RapidField.SolidInstruments.Cryptography.UnitTests/Extensions/AlgorithmSpecificationExtensionsTests.cs | 6,481 | C# |
#pragma checksum "C:\School\NP\Np_class\SSD\RPS-Authentication\RPS-Authentication\Pages\Privacy.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "a0906750319c55d6ce48b545e707c28c2eb4094c"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(RPS_Authentication.Pages.Pages_Privacy), @"mvc.1.0.razor-page", @"/Pages/Privacy.cshtml")]
namespace RPS_Authentication.Pages
{
#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:\School\NP\Np_class\SSD\RPS-Authentication\RPS-Authentication\Pages\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\School\NP\Np_class\SSD\RPS-Authentication\RPS-Authentication\Pages\_ViewImports.cshtml"
using RPS_Authentication;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\School\NP\Np_class\SSD\RPS-Authentication\RPS-Authentication\Pages\_ViewImports.cshtml"
using RPS_Authentication.Data;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"a0906750319c55d6ce48b545e707c28c2eb4094c", @"/Pages/Privacy.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"f567823d1fc78eeea3860b6246cb0ecc65b884a7", @"/Pages/_ViewImports.cshtml")]
public class Pages_Privacy : global::Microsoft.AspNetCore.Mvc.RazorPages.Page
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 3 "C:\School\NP\Np_class\SSD\RPS-Authentication\RPS-Authentication\Pages\Privacy.cshtml"
ViewData["Title"] = "Privacy Policy";
#line default
#line hidden
#nullable disable
WriteLiteral("<h1>");
#nullable restore
#line 6 "C:\School\NP\Np_class\SSD\RPS-Authentication\RPS-Authentication\Pages\Privacy.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
#nullable disable
WriteLiteral("</h1>\r\n\r\n<p>Use this page to detail your site\'s privacy policy.</p>\r\n");
}
#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<PrivacyModel> Html { get; private set; }
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<PrivacyModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<PrivacyModel>)PageContext?.ViewData;
public PrivacyModel Model => ViewData.Model;
}
}
#pragma warning restore 1591
| 47.194805 | 208 | 0.767749 | [
"MIT"
] | dodieboy/Np_class | SSD/week 04/RPS-Authentication/RPS-Authentication/obj/Debug/netcoreapp3.1/Razor/Pages/Privacy.cshtml.g.cs | 3,634 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Codeit.NetStdLibrary.Base.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Codeit.Infrastructure.Identity.Model.Entities;
namespace Codeit.Infrastructure.Identity.Areas.Identity.Pages.Account.Manage
{
public partial class EmailModel : PageModel
{
private readonly UserManager<IdentityAppUser> _userManager;
private readonly SignInManager<IdentityAppUser> _signInManager;
private readonly IEmailSender _emailSender;
public EmailModel(
UserManager<IdentityAppUser> userManager,
SignInManager<IdentityAppUser> signInManager,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
}
public string Username { get; set; }
public string Email { get; set; }
public bool IsEmailConfirmed { get; set; }
[TempData]
public string StatusMessage { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "New email")]
public string NewEmail { get; set; }
}
private async Task LoadAsync(IdentityAppUser user)
{
var email = await _userManager.GetEmailAsync(user);
Email = email;
Input = new InputModel
{
NewEmail = email,
};
IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await LoadAsync(user);
return Page();
}
public async Task<IActionResult> OnPostChangeEmailAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var email = await _userManager.GetEmailAsync(user);
if (Input.NewEmail != email)
{
var userId = await _userManager.GetUserIdAsync(user);
var code = await _userManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail);
var callbackUrl = Url.Page(
"/Account/ConfirmEmailChange",
pageHandler: null,
values: new { userId = userId, email = Input.NewEmail, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(
Input.NewEmail,
"Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
StatusMessage = "Confirmation link to change email sent. Please check your email.";
return RedirectToPage();
}
StatusMessage = "Your email is unchanged.";
return RedirectToPage();
}
public async Task<IActionResult> OnPostSendVerificationEmailAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var userId = await _userManager.GetUserIdAsync(user);
var email = await _userManager.GetEmailAsync(user);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = userId, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(
email,
"Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
StatusMessage = "Verification email sent. Please check your email.";
return RedirectToPage();
}
}
}
| 34.724832 | 126 | 0.580402 | [
"MIT"
] | Leitee/Codeit.Infrastructure.Identity | Codeit.Infrastructure.Identity/Areas/Identity/Pages/Account/Manage/Email.cshtml.cs | 5,176 | C# |
using System;
namespace ApiService.Contracts.MonitoringApi
{
public interface GetOrderStateResponse
{
public Guid OrderId { get; set; }
public int State { get; set; }
}
} | 20 | 44 | 0.655 | [
"MIT"
] | konvovden/masstransit-demo | src/Contracts/ApiService.Contracts/MonitoringApi/GetOrderStateResponse.cs | 202 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// In this algorithm we demonstrate how to use the raw data for our securities
/// and verify that the behavior is correct.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="regression test" />
public class RawDataRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string Ticker = "GOOGL";
private readonly FactorFile _factorFile = FactorFile.Read(Ticker, Market.USA);
private readonly IEnumerator<decimal> _expectedRawPrices = new List<decimal> { 1158.1100m, 1158.7200m,
1131.7800m, 1114.2800m, 1119.6100m, 1114.5500m, 1135.3200m, 567.59000m, 571.4900m, 545.3000m, 540.6400m }.GetEnumerator();
private Symbol _googl;
public override void Initialize()
{
SetStartDate(2014, 3, 25); //Set Start Date
SetEndDate(2014, 4, 7); //Set End Date
SetCash(100000); //Set Strategy Cash
// Set our DataNormalizationMode to raw
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
_googl = AddEquity(Ticker, Resolution.Daily).Symbol;
// Prime our expected values
_expectedRawPrices.MoveNext();
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings(_googl, 1);
}
if (data.Bars.ContainsKey(_googl))
{
var googlData = data.Bars[_googl];
// Assert our volume matches what we expected
if (_expectedRawPrices.Current != googlData.Close)
{
// Our values don't match lets try and give a reason why
var dayFactor = _factorFile.GetPriceScaleFactor(googlData.Time);
var probableRawPrice = googlData.Close / dayFactor; // Undo adjustment
if (_expectedRawPrices.Current == probableRawPrice)
{
throw new Exception($"Close price was incorrect; it appears to be the adjusted value");
}
else
{
throw new Exception($"Close price was incorrect; Data may have changed.");
}
}
// Move to our next expected value
_expectedRawPrices.MoveNext();
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-85.948%"},
{"Drawdown", "7.300%"},
{"Expectancy", "0"},
{"Net Profit", "-7.251%"},
{"Sharpe Ratio", "-3.008"},
{"Probabilistic Sharpe Ratio", "3.159%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.831"},
{"Beta", "-0.223"},
{"Annual Standard Deviation", "0.262"},
{"Annual Variance", "0.069"},
{"Information Ratio", "-2.045"},
{"Tracking Error", "0.289"},
{"Treynor Ratio", "3.525"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$110000000.00"},
{"Lowest Capacity Asset", "GOOG T1AZ164W5VTX"},
{"Fitness Score", "0.006"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-3.445"},
{"Return Over Maximum Drawdown", "-11.853"},
{"Portfolio Turnover", "0.084"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "3702afa2a5d1634ed451768917394502"}
};
}
}
| 42.959732 | 146 | 0.569286 | [
"Apache-2.0"
] | LakshanPerera/Lean | Algorithm.CSharp/RawDataRegressionAlgorithm.cs | 6,401 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HastaneRandevu.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class HastaneEntities1 : DbContext
{
public HastaneEntities1()
: base("name=HastaneEntities1")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Doctor> Doctor { get; set; }
public virtual DbSet<Randevu> Randevu { get; set; }
public virtual DbSet<User> User { get; set; }
}
}
| 32.090909 | 85 | 0.546742 | [
"MIT"
] | Deku7/HastaneRandevu | HastaneRandevu/Models/Model1.Context.cs | 1,061 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BestHTTP;
namespace BestHTTP.Examples
{
public sealed class AssetBundleSample : MonoBehaviour
{
/// <summary>
/// The url of the resource to download
/// </summary>
#if UNITY_WEBGL && !UNITY_EDITOR
const string URL = "https://besthttp.azurewebsites.net/Content/AssetBundle_v5.html";
#else
const string URL = "https://besthttp.azurewebsites.net/Content/AssetBundle.html";
#endif
#region Private Fields
/// <summary>
/// Debug status text
/// </summary>
string status = "Waiting for user interaction";
/// <summary>
/// The downloaded and cached AssetBundle
/// </summary>
AssetBundle cachedBundle;
/// <summary>
/// The loaded texture from the AssetBundle
/// </summary>
Texture2D texture;
/// <summary>
/// A flag that indicates that we are processing the request/bundle to hide the "Start Download" button.
/// </summary>
bool downloading;
#endregion
#region Unity Events
void OnGUI()
{
GUIHelper.DrawArea(GUIHelper.ClientArea, true, () =>
{
GUILayout.Label("Status: " + status);
// Draw the texture from the downloaded bundle
if (texture != null)
GUILayout.Box(texture, GUILayout.MaxHeight(256));
if (!downloading && GUILayout.Button("Start Download"))
{
UnloadBundle();
StartCoroutine(DownloadAssetBundle());
}
});
}
void OnDestroy()
{
UnloadBundle();
}
#endregion
#region Private Helper Functions
IEnumerator DownloadAssetBundle()
{
downloading = true;
// Create and send our request
var request = new HTTPRequest(new Uri(URL)).Send();
status = "Download started";
// Wait while it's finishes and add some fancy dots to display something while the user waits for it.
// A simple "yield return StartCoroutine(request);" would do the job too.
while (request.State < HTTPRequestStates.Finished)
{
yield return new WaitForSeconds(0.1f);
status += ".";
}
// Check the outcome of our request.
switch (request.State)
{
// The request finished without any problem.
case HTTPRequestStates.Finished:
if (request.Response.IsSuccess)
{
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
status = string.Format("AssetBundle downloaded! Loaded from local cache: {0}", request.Response.IsFromCache.ToString());
#else
status = "AssetBundle downloaded!";
#endif
// Start creating the downloaded asset bundle
AssetBundleCreateRequest async =
#if UNITY_5_3_OR_NEWER
AssetBundle.LoadFromMemoryAsync(request.Response.Data);
#else
AssetBundle.LoadFromMemoryAsync(request.Response.Data);
#endif
// wait for it
yield return async;
// And process the bundle
yield return StartCoroutine(ProcessAssetBundle(async.assetBundle));
}
else
{
status = string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
request.Response.StatusCode,
request.Response.Message,
request.Response.DataAsText);
Debug.LogWarning(status);
}
break;
// The request finished with an unexpected error. The request's Exception property may contain more info about the error.
case HTTPRequestStates.Error:
status = "Request Finished with Error! " + (request.Exception != null ? (request.Exception.Message + "\n" + request.Exception.StackTrace) : "No Exception");
Debug.LogError(status);
break;
// The request aborted, initiated by the user.
case HTTPRequestStates.Aborted:
status = "Request Aborted!";
Debug.LogWarning(status);
break;
// Ceonnecting to the server is timed out.
case HTTPRequestStates.ConnectionTimedOut:
status = "Connection Timed Out!";
Debug.LogError(status);
break;
// The request didn't finished in the given time.
case HTTPRequestStates.TimedOut:
status = "Processing the request Timed Out!";
Debug.LogError(status);
break;
}
downloading = false;
}
/// <summary>
/// In this function we can do whatever we want with the freshly downloaded bundle.
/// In this example we will cache it for later use, and we will load a texture from it.
/// </summary>
IEnumerator ProcessAssetBundle(AssetBundle bundle)
{
if (bundle == null)
yield break;
// Save the bundle for future use
cachedBundle = bundle;
// Start loading the asset from the bundle
var asyncAsset =
#if UNITY_5
cachedBundle.LoadAssetAsync("9443182_orig", typeof(Texture2D));
#else
cachedBundle.LoadAsync("9443182_orig", typeof(Texture2D));
#endif
// wait til load
yield return asyncAsset;
// get the texture
texture = asyncAsset.asset as Texture2D;
}
void UnloadBundle()
{
if (cachedBundle != null)
{
cachedBundle.Unload(true);
cachedBundle = null;
}
}
#endregion
}
} | 32.849246 | 176 | 0.517822 | [
"Apache-2.0"
] | eternalflamez/UnityAudioStream | Assets/Best HTTP (Pro)/Examples/HTTP/AssetBundleSample.cs | 6,539 | C# |
using System;
using System.Collections.Generic;
using MG.Utils.Abstract;
namespace MG.Utils.Helpers
{
public static class Converters
{
public static string AsJson<T>(this T instance)
{
return System.Text.Json.JsonSerializer.Serialize(instance);
}
public static T DeserializeAs<T>(this string @string)
{
@string.ThrowIfNull(nameof(@string));
try
{
return System.Text.Json.JsonSerializer.Deserialize<T>(@string);
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Could not deserialize a string as {typeof(T).Name} type", ex);
}
}
public static LinkedList<T> ToLinkedList<T>(this IEnumerable<T> source)
{
source.ThrowIfNull(nameof(source));
if (source is LinkedList<T> linked)
{
return linked;
}
return new LinkedList<T>(source);
}
}
} | 25.878049 | 84 | 0.539114 | [
"MIT"
] | Petrel-AI/AzureAppRelatedUsefulFeatures | src/MG.Utils/Helpers/Converters.cs | 1,063 | C# |
//MIT, 2009-2015, Rene Schulte and WriteableBitmapEx Contributors, https://github.com/teichgraf/WriteableBitmapEx
//
//
// Project: WriteableBitmapEx - WriteableBitmap extensions
// Description: Collection of extension methods for the WriteableBitmap class.
//
// Changed by: $Author: unknown $
// Changed on: $Date: 2015-03-05 18:18:24 +0100 (Do, 05 Mrz 2015) $
// Changed in: $Revision: 113191 $
// Project: $URL: https://writeablebitmapex.svn.codeplex.com/svn/trunk/Source/WriteableBitmapEx/WriteableBitmapBaseExtensions.cs $
// Id: $Id: WriteableBitmapBaseExtensions.cs 113191 2015-03-05 17:18:24Z unknown $
//
//
// Copyright © 2009-2015 Rene Schulte and WriteableBitmapEx Contributors
//
// This code is open source. Please read the License.txt for details. No worries, we won't sue you! ;)
//
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BitmapBufferEx;
namespace WinFormGdiPlus
{
public partial class FormShape : Form
{
private int shapeCount = 100;
private static Random rand = new Random();
private int frameCounter = 0;
enum SampleName
{
DrawStaticShapes,
DrawEllipses,
DrawEllipsesFlower,
}
public FormShape()
{
InitializeComponent();
//setup
}
private void FormShape_Load(object sender, EventArgs e)
{
this.listBox1.Items.AddRange(
new object[]
{
SampleName.DrawEllipses,
SampleName.DrawEllipsesFlower,
SampleName.DrawStaticShapes
});
listBox1.SelectedIndex = 0;
listBox1.SelectedIndexChanged += (s1, e1) => RenderSelectedSample();
}
void RenderSelectedSample()
{
SampleName sampleName = (SampleName)listBox1.SelectedItem;
//render!
using (Graphics g = this.panel1.CreateGraphics())
using (Bitmap bmp1 = new Bitmap(400, 500))
using (LockBmp bmplock = bmp1.Lock())
{
BitmapBuffer wb = bmplock.CreateNewBitmapBuffer();
switch (sampleName)
{
case SampleName.DrawEllipses:
DrawEllipses(wb);
break;
case SampleName.DrawEllipsesFlower:
DrawEllipsesFlower(wb);
break;
case SampleName.DrawStaticShapes:
DrawStaticShapes(wb);
break;
}
bmplock.WriteAndUnlock();
//
g.Clear(System.Drawing.Color.White);
g.DrawImage(bmp1, 0, 0);
}
}
private void button1_Click(object sender, EventArgs e)
{
RenderSelectedSample();
}
/// <summary>
/// Random color fully opaque
/// </summary>
/// <returns></returns>
private static int GetRandomColor()
{
return (int)(0xFF000000 | (uint)rand.Next(0xFFFFFF));
}
/// <summary>
/// Draws circles that decrease in size to build a flower that is animated
/// </summary>
private void DrawEllipsesFlower(BitmapBuffer writeableBmp)
{
// Init some size vars
int w = writeableBmp.PixelWidth - 2;
int h = writeableBmp.PixelHeight - 2;
// Wrap updates in a GetContext call, to prevent invalidation and nested locking/unlocking during this block
using (writeableBmp.GetBitmapContext())
{
// Increment frame counter
if (++frameCounter >= int.MaxValue || frameCounter < 1)
{
frameCounter = 1;
}
double s = Math.Sin(frameCounter * 0.01);
if (s < 0)
{
s *= -1;
}
// Clear
writeableBmp.Clear();
// Draw center circle
int xc = w >> 1;
int yc = h >> 1;
// Animate base size with sine
int r0 = (int)((w + h) * 0.07 * s) + 10;
BitmapBufferEx.ColorInt color_brown =BitmapBufferEx.ColorInt.FromArgb(
255, System.Drawing.Color.Brown.R, System.Drawing.Color.Brown.G, System.Drawing.Color.Brown.B);
writeableBmp.DrawEllipseCentered(xc, yc, r0, r0, color_brown);
// Draw outer circles
int dec = (int)((w + h) * 0.0045f);
int r = (int)((w + h) * 0.025f);
int offset = r0 + r;
for (int i = 1; i < 6 && r > 1; i++)
{
for (double f = 1; f < 7; f += 0.7)
{
// Calc postion based on unit circle
int xc2 = (int)(Math.Sin(frameCounter * 0.002 * i + f) * offset + xc);
int yc2 = (int)(Math.Cos(frameCounter * 0.002 * i + f) * offset + yc);
int col = (int)(0xFFFF0000 | (uint)(0x1A * i) << 8 | (uint)(0x20 * f));
writeableBmp.DrawEllipseCentered(xc2, yc2, r, r, col);
}
// Next ring
offset += r;
r -= dec;
offset += r;
}
// Invalidates on exit of using block
}
}
/// <summary>
/// Draws random ellipses
/// </summary>
private void DrawEllipses(BitmapBuffer writeableBmp)
{
// Init some size vars
int w = writeableBmp.PixelWidth - 2;
int h = writeableBmp.PixelHeight - 2;
int wh = w >> 1;
int hh = h >> 1;
// Wrap updates in a GetContext call, to prevent invalidation and nested locking/unlocking during this block
using (writeableBmp.GetBitmapContext())
{
// Clear
writeableBmp.Clear();
// Draw Ellipses
for (int i = 0; i < shapeCount; i++)
{
writeableBmp.DrawEllipse(rand.Next(wh), rand.Next(hh), rand.Next(wh, w), rand.Next(hh, h),
GetRandomColor());
}
// Invalidates on exit of using block
}
}
/// <summary>
/// Draws the different types of shapes.
/// </summary>
private void DrawStaticShapes(BitmapBuffer writeableBmp)
{
// Wrap updates in a GetContext call, to prevent invalidation and nested locking/unlocking during this block
using (writeableBmp.GetBitmapContext())
{
// Init some size vars
int w = writeableBmp.PixelWidth - 2;
int h = writeableBmp.PixelHeight - 2;
int w3rd = w / 3;
int h3rd = h / 3;
int w6th = w3rd >> 1;
int h6th = h3rd >> 1;
// Clear
writeableBmp.Clear();
// Draw some points
for (int i = 0; i < 200; i++)
{
writeableBmp.SetPixel(rand.Next(w3rd), rand.Next(h3rd), GetRandomColor());
}
// Draw Standard shapes
writeableBmp.DrawLine(rand.Next(w3rd, w3rd * 2), rand.Next(h3rd), rand.Next(w3rd, w3rd * 2), rand.Next(h3rd),
GetRandomColor());
writeableBmp.DrawTriangle(rand.Next(w3rd * 2, w - w6th), rand.Next(h6th), rand.Next(w3rd * 2, w),
rand.Next(h6th, h3rd), rand.Next(w - w6th, w), rand.Next(h3rd),
GetRandomColor());
writeableBmp.DrawQuad(rand.Next(0, w6th), rand.Next(h3rd, h3rd + h6th), rand.Next(w6th, w3rd),
rand.Next(h3rd, h3rd + h6th), rand.Next(w6th, w3rd),
rand.Next(h3rd + h6th, 2 * h3rd), rand.Next(0, w6th), rand.Next(h3rd + h6th, 2 * h3rd),
GetRandomColor());
writeableBmp.DrawRectangle(rand.Next(w3rd, w3rd + w6th), rand.Next(h3rd, h3rd + h6th),
rand.Next(w3rd + w6th, w3rd * 2), rand.Next(h3rd + h6th, 2 * h3rd),
GetRandomColor());
// Random polyline
int[] p = new int[rand.Next(7, 10) * 2];
for (int j = 0; j < p.Length; j += 2)
{
p[j] = rand.Next(w3rd * 2, w);
p[j + 1] = rand.Next(h3rd, 2 * h3rd);
}
writeableBmp.DrawPolyline(p, GetRandomColor());
// Random closed polyline
p = new int[rand.Next(6, 9) * 2];
for (int j = 0; j < p.Length - 2; j += 2)
{
p[j] = rand.Next(w3rd);
p[j + 1] = rand.Next(2 * h3rd, h);
}
p[p.Length - 2] = p[0];
p[p.Length - 1] = p[1];
writeableBmp.DrawPolyline(p, GetRandomColor());
// Ellipses
writeableBmp.DrawEllipse(rand.Next(w3rd, w3rd + w6th), rand.Next(h3rd * 2, h - h6th),
rand.Next(w3rd + w6th, w3rd * 2), rand.Next(h - h6th, h), GetRandomColor());
writeableBmp.DrawEllipseCentered(w - w6th, h - h6th, w6th >> 1, h6th >> 1, GetRandomColor());
// Draw Grid
writeableBmp.DrawLine(0, h3rd, w, h3rd, Colors.Black);
writeableBmp.DrawLine(0, 2 * h3rd, w, 2 * h3rd, Colors.Black);
writeableBmp.DrawLine(w3rd, 0, w3rd, h, Colors.Black);
writeableBmp.DrawLine(2 * w3rd, 0, 2 * w3rd, h, Colors.Black);
// Invalidates on exit of using block
}
}
}
}
| 37.985348 | 142 | 0.475988 | [
"MIT"
] | LayoutFarm/PixelFarm | src/Tests/Test_BackEnd_DrawingBuffer/FormShape.cs | 10,373 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EasyOjima.UserInterface {
public partial class InputBox : Form {
private bool _isValidClose = false;
public InputBox(string message) {
InitializeComponent();
this.messageLabel.Text = message;
this.FormClosing += Inputbox_FormClosing;
}
private void Inputbox_FormClosing(object sender, FormClosingEventArgs e) {
if (e.CloseReason == CloseReason.UserClosing) {
if (!this._isValidClose) {
this.Result = DialogResult.Cancel;
}
}
}
public string ResultText => this.textBox.Text;
public DialogResult Result { get; private set; }
private void Inputbox_Load(object sender, EventArgs e) {
//none
}
private void submitButton_Click(object sender, EventArgs e) {
this.Result = DialogResult.OK;
this._isValidClose = true;
this.Close();
}
private void cancelButton_Click(object sender, EventArgs e) {
this.Result = DialogResult.Cancel;
this._isValidClose = true;
this.Close();
}
}
}
| 28.755102 | 82 | 0.609652 | [
"MIT"
] | Nodoka4318/EasyOjima | src/EasyOjima.UserInterface/InputBox.cs | 1,411 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.ML;
using Microsoft.ML.CommandLine;
using Microsoft.ML.Data;
using Microsoft.ML.Internal.Internallearn;
using Microsoft.ML.Model.OnnxConverter;
using Microsoft.ML.Model.Pfa;
using Microsoft.ML.Runtime;
using Microsoft.ML.Transforms;
using Newtonsoft.Json.Linq;
[assembly: LoadableClass(NormalizeTransform.MinMaxNormalizerSummary, typeof(IDataTransform), typeof(NormalizeTransform), typeof(NormalizeTransform.MinMaxArguments), typeof(SignatureDataTransform),
NormalizeTransform.MinMaxNormalizerUserName, "MinMaxNormalizer", NormalizeTransform.MinMaxNormalizerShortName)]
[assembly: LoadableClass(NormalizeTransform.MeanVarNormalizerSummary, typeof(IDataTransform), typeof(NormalizeTransform), typeof(NormalizeTransform.MeanVarArguments), typeof(SignatureDataTransform),
NormalizeTransform.MeanVarNormalizerUserName, "MeanVarNormalizer", NormalizeTransform.MeanVarNormalizerShortName, "ZScoreNormalizer", "ZScore", "GaussianNormalizer", "Gaussian")]
[assembly: LoadableClass(NormalizeTransform.LogMeanVarNormalizerSummary, typeof(IDataTransform), typeof(NormalizeTransform), typeof(NormalizeTransform.LogMeanVarArguments), typeof(SignatureDataTransform),
NormalizeTransform.LogMeanVarNormalizerUserName, "LogMeanVarNormalizer", NormalizeTransform.LogMeanVarNormalizerShortName, "LogNormalNormalizer", "LogNormal")]
[assembly: LoadableClass(NormalizeTransform.BinNormalizerSummary, typeof(IDataTransform), typeof(NormalizeTransform), typeof(NormalizeTransform.BinArguments), typeof(SignatureDataTransform),
NormalizeTransform.BinNormalizerUserName, "BinNormalizer", NormalizeTransform.BinNormalizerShortName)]
[assembly: LoadableClass(NormalizeTransform.RobustScalingNormalizerSummary, typeof(IDataTransform), typeof(NormalizeTransform), typeof(NormalizeTransform.RobustScalingArguments), typeof(SignatureDataTransform),
NormalizeTransform.RobustScalingNormalizerUserName, "RobustScalingNormalizer", NormalizeTransform.RobustScalingNormalizerShortName)]
[assembly: LoadableClass(typeof(NormalizeTransform.AffineColumnFunction), null, typeof(SignatureLoadColumnFunction),
"Affine Normalizer", AffineNormSerializationUtils.LoaderSignature)]
[assembly: LoadableClass(typeof(NormalizeTransform.CdfColumnFunction), null, typeof(SignatureLoadColumnFunction),
"CDF Normalizer", NormalizeTransform.CdfColumnFunction.LoaderSignature)]
[assembly: LoadableClass(NormalizeTransform.BinNormalizerSummary, typeof(NormalizeTransform.BinColumnFunction), null, typeof(SignatureLoadColumnFunction),
"Bin Normalizer", NormalizeTransform.BinColumnFunction.LoaderSignature)]
namespace Microsoft.ML.Transforms
{
/// <summary>
/// The normalize transform for support of normalization via the <see cref="IDataTransform"/> mechanism.
/// More contemporaneous API usage of normalization ought to use <see cref="NormalizingEstimator"/>
/// and <see cref="NormalizingTransformer"/> rather than this structure.
/// </summary>
internal sealed partial class NormalizeTransform
{
public abstract class ColumnBase : OneToOneColumn
{
[Argument(ArgumentType.AtMostOnce, HelpText = "Max number of examples used to train the normalizer",
Name = "MaxTrainingExamples", ShortName = "maxtrain")]
public long? MaximumExampleCount;
private protected ColumnBase()
{
}
private protected override bool TryUnparseCore(StringBuilder sb)
{
Contracts.AssertValue(sb);
if (MaximumExampleCount != null)
return false;
return base.TryUnparseCore(sb);
}
}
// REVIEW: Support different aggregators on different columns, eg, MinMax vs Variance/ZScore.
public abstract class ControlZeroColumnBase : ColumnBase
{
// REVIEW: This only allows mapping either zero or min to zero. It might make sense to allow also max, midpoint and mean to be mapped to zero.
[Argument(ArgumentType.AtMostOnce, Name="FixZero", HelpText = "Whether to map zero to zero, preserving sparsity", ShortName = "zero")]
public bool? EnsureZeroUntouched;
private protected override bool TryUnparseCore(StringBuilder sb)
{
Contracts.AssertValue(sb);
if (EnsureZeroUntouched != null)
return false;
return base.TryUnparseCore(sb);
}
}
public sealed class AffineColumn : ControlZeroColumnBase
{
internal static AffineColumn Parse(string str)
{
Contracts.AssertNonEmpty(str);
var res = new AffineColumn();
if (res.TryParse(str))
return res;
return null;
}
internal bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
return TryUnparseCore(sb);
}
}
public sealed class BinColumn : ControlZeroColumnBase
{
[Argument(ArgumentType.AtMostOnce, HelpText = "Max number of bins, power of 2 recommended", ShortName = "bins")]
[TGUI(Label = "Max number of bins")]
public int? NumBins;
internal static BinColumn Parse(string str)
{
Contracts.AssertNonEmpty(str);
var res = new BinColumn();
if (res.TryParse(str))
return res;
return null;
}
internal bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
if (NumBins != null)
return false;
return TryUnparseCore(sb);
}
}
public sealed class LogNormalColumn : ColumnBase
{
internal static LogNormalColumn Parse(string str)
{
Contracts.AssertNonEmpty(str);
var res = new LogNormalColumn();
if (res.TryParse(str))
return res;
return null;
}
internal bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
return TryUnparseCore(sb);
}
}
private static class Defaults
{
public const bool EnsureZeroUntouched = true;
public const bool MeanVarCdf = false;
public const bool LogMeanVarCdf = true;
public const int NumBins = 1024;
public const int MinBinSize = 10;
public const bool CenterData = true;
public const int QuantileMin = 25;
public const int QuantileMax = 75;
}
public abstract class ControlZeroArgumentsBase : ArgumentsBase
{
// REVIEW: This only allows mapping either zero or min to zero. It might make sense to allow also max, midpoint and mean to be mapped to zero.
// REVIEW: Convert this to bool? or even an enum{Auto, No, Yes}, and automatically map zero to zero when it is null/Auto.
[Argument(ArgumentType.AtMostOnce, Name = "FixZero", HelpText = "Whether to map zero to zero, preserving sparsity", ShortName = "zero")]
public bool EnsureZeroUntouched = Defaults.EnsureZeroUntouched;
}
public abstract class AffineArgumentsBase : ControlZeroArgumentsBase
{
[Argument(ArgumentType.Multiple | ArgumentType.Required, HelpText = "New column definition(s) (optional form: name:src)", Name = "Column", ShortName = "col", SortOrder = 1)]
public AffineColumn[] Columns;
public override OneToOneColumn[] GetColumns() => Columns;
}
public sealed class MinMaxArguments : AffineArgumentsBase
{
}
public sealed class MeanVarArguments : AffineArgumentsBase
{
[Argument(ArgumentType.AtMostOnce, HelpText = "Whether to use CDF as the output", ShortName = "cdf")]
public bool UseCdf = Defaults.MeanVarCdf;
}
public abstract class ArgumentsBase : TransformInputBase
{
[Argument(ArgumentType.AtMostOnce, HelpText = "Max number of examples used to train the normalizer",
Name = "MaxTrainingExamples", ShortName = "maxtrain")]
public long MaximumExampleCount = 1000000000;
public abstract OneToOneColumn[] GetColumns();
public string TestType(DataViewType type)
{
DataViewType itemType = type;
if (type is VectorDataViewType vectorType)
{
// We require vectors to be of known size.
if (!vectorType.IsKnownSize)
return "Expected known size vector";
itemType = vectorType.ItemType;
}
if (itemType != NumberDataViewType.Single && itemType != NumberDataViewType.Double)
return "Expected Single or Double item type";
return null;
}
}
public sealed class LogMeanVarArguments : ArgumentsBase
{
[Argument(ArgumentType.AtMostOnce, HelpText = "Whether to use CDF as the output", ShortName = "cdf")]
public bool UseCdf = Defaults.LogMeanVarCdf;
[Argument(ArgumentType.Multiple, HelpText = "New column definition(s) (optional form: name:src)", Name = "Column", ShortName = "col", SortOrder = 1)]
public LogNormalColumn[] Columns;
public override OneToOneColumn[] GetColumns() => Columns;
}
public abstract class BinArgumentsBase : ControlZeroArgumentsBase
{
[Argument(ArgumentType.Multiple, HelpText = "New column definition(s) (optional form: name:src)", Name = "Column", ShortName = "col", SortOrder = 1)]
public BinColumn[] Columns;
[Argument(ArgumentType.AtMostOnce, HelpText = "Max number of bins, power of 2 recommended", ShortName = "bins")]
[TGUI(Label = "Max number of bins")]
public int NumBins = Defaults.NumBins;
public override OneToOneColumn[] GetColumns() => Columns;
}
public sealed class BinArguments : BinArgumentsBase
{
}
public sealed class SupervisedBinArguments : BinArgumentsBase
{
// REVIEW: factor in a loss function / optimization algorithm to make it work better in regression case
[Argument(ArgumentType.Required, HelpText = "Label column for supervised binning", ShortName = "label,lab",
Purpose = SpecialPurpose.ColumnName)]
public string LabelColumn;
[Argument(ArgumentType.AtMostOnce, HelpText = "Minimum number of examples per bin")]
public int MinBinSize = Defaults.MinBinSize;
}
public sealed class RobustScalingArguments : AffineArgumentsBase
{
[Argument(ArgumentType.AtMostOnce, HelpText = "Should the data be centered around 0", Name = "CenterData", ShortName = "center", SortOrder = 1)]
public bool CenterData = Defaults.CenterData;
[Argument(ArgumentType.AtMostOnce, HelpText = "Minimum quantile value. Defaults to 25", Name = "QuantileMin", ShortName = "qmin", SortOrder = 2)]
public uint QuantileMin = Defaults.QuantileMin;
[Argument(ArgumentType.AtMostOnce, HelpText = "Maximum quantile value. Defaults to 75", Name = "QuantileMax", ShortName = "qmax", SortOrder = 3)]
public uint QuantileMax = Defaults.QuantileMax;
}
internal const string MinMaxNormalizerSummary = "Normalizes the data based on the observed minimum and maximum values of the data.";
internal const string MeanVarNormalizerSummary = "Normalizes the data based on the computed mean and variance of the data.";
internal const string LogMeanVarNormalizerSummary = "Normalizes the data based on the computed mean and variance of the logarithm of the data.";
internal const string BinNormalizerSummary = "The values are assigned into equidensity bins and a value is mapped to its bin_number/number_of_bins.";
internal const string SupervisedBinNormalizerSummary = "Similar to BinNormalizer, but calculates bins based on correlation with the label column, not equi-density. "
+ "The new value is bin_number / number_of_bins.";
internal const string RobustScalingNormalizerSummary = "Optionally centers the data and scales based on the range of data and the quantile min and max values provided. "
+ "This method is more robust to outliers.";
internal const string MinMaxNormalizerUserName = "Min-Max Normalizer";
internal const string MeanVarNormalizerUserName = "MeanVar Normalizer";
internal const string LogMeanVarNormalizerUserName = "LogMeanVar Normalizer";
internal const string BinNormalizerUserName = "Binning Normalizer";
internal const string SupervisedBinNormalizerUserName = "Supervised Binning Normalizer";
internal const string RobustScalingNormalizerUserName = "Robust Scaling Normalizer";
internal const string MinMaxNormalizerShortName = "MinMax";
internal const string MeanVarNormalizerShortName = "MeanVar";
internal const string LogMeanVarNormalizerShortName = "LogMeanVar";
internal const string BinNormalizerShortName = "Bin";
internal const string SupervisedBinNormalizerShortName = "SupBin";
internal const string RobustScalingNormalizerShortName = "RobScal";
/// <summary>
/// A helper method to create a MinMax normalizer.
/// </summary>
/// <param name="env">Host Environment.</param>
/// <param name="input">Input <see cref="IDataView"/>. This is the output from previous transform or loader.</param>
/// <param name="outputColumnName">Name of the output column.</param>
/// <param name="inputColumnName">Name of the column to be transformed. If this is null '<paramref name="outputColumnName"/>' will be used.</param>
public static IDataView CreateMinMaxNormalizer(IHostEnvironment env, IDataView input, string outputColumnName, string inputColumnName = null)
{
Contracts.CheckValue(env, nameof(env));
var normalizer = new NormalizingEstimator(env, new NormalizingEstimator.MinMaxColumnOptions(outputColumnName, inputColumnName ?? outputColumnName));
return normalizer.Fit(input).MakeDataTransform(input);
}
/// <summary>
/// Factory method corresponding to SignatureDataTransform.
/// </summary>
internal static IDataTransform Create(IHostEnvironment env, MinMaxArguments args, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(args, nameof(args));
env.CheckValue(args.Columns, nameof(args.Columns));
var columns = args.Columns
.Select(col => new NormalizingEstimator.MinMaxColumnOptions(
col.Name,
col.Source ?? col.Name,
col.MaximumExampleCount ?? args.MaximumExampleCount,
col.EnsureZeroUntouched ?? args.EnsureZeroUntouched))
.ToArray();
var normalizer = new NormalizingEstimator(env, columns);
return normalizer.Fit(input).MakeDataTransform(input);
}
// Factory method corresponding to SignatureDataTransform.
internal static IDataTransform Create(IHostEnvironment env, MeanVarArguments args, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(args, nameof(args));
env.CheckValue(args.Columns, nameof(args.Columns));
var columns = args.Columns
.Select(col => new NormalizingEstimator.MeanVarianceColumnOptions(
col.Name,
col.Source ?? col.Name,
col.MaximumExampleCount ?? args.MaximumExampleCount,
col.EnsureZeroUntouched ?? args.EnsureZeroUntouched))
.ToArray();
var normalizer = new NormalizingEstimator(env, columns);
return normalizer.Fit(input).MakeDataTransform(input);
}
/// <summary>
/// Factory method corresponding to SignatureDataTransform.
/// </summary>
internal static IDataTransform Create(IHostEnvironment env, LogMeanVarArguments args, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(args, nameof(args));
env.CheckValue(args.Columns, nameof(args.Columns));
var columns = args.Columns
.Select(col => new NormalizingEstimator.LogMeanVarianceColumnOptions(
col.Name,
col.Source ?? col.Name,
col.MaximumExampleCount ?? args.MaximumExampleCount,
args.UseCdf))
.ToArray();
var normalizer = new NormalizingEstimator(env, columns);
return normalizer.Fit(input).MakeDataTransform(input);
}
/// <summary>
/// Factory method corresponding to SignatureDataTransform.
/// </summary>
internal static IDataTransform Create(IHostEnvironment env, BinArguments args, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(args, nameof(args));
env.CheckValue(args.Columns, nameof(args.Columns));
var columns = args.Columns
.Select(col => new NormalizingEstimator.BinningColumnOptions(
col.Name,
col.Source ?? col.Name,
col.MaximumExampleCount ?? args.MaximumExampleCount,
col.EnsureZeroUntouched ?? args.EnsureZeroUntouched,
col.NumBins ?? args.NumBins))
.ToArray();
var normalizer = new NormalizingEstimator(env, columns);
return normalizer.Fit(input).MakeDataTransform(input);
}
/// <summary>
/// Factory method corresponding to SignatureDataTransform.
/// </summary>
internal static IDataTransform Create(IHostEnvironment env, RobustScalingArguments args, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(args, nameof(args));
env.CheckValue(args.Columns, nameof(args.Columns));
var columns = args.Columns
.Select(col => new NormalizingEstimator.RobustScalingColumnOptions(
col.Name,
col.Source ?? col.Name,
col.MaximumExampleCount ?? args.MaximumExampleCount,
args.CenterData,
args.QuantileMin,
args.QuantileMax))
.ToArray();
var normalizer = new NormalizingEstimator(env, columns);
return normalizer.Fit(input).MakeDataTransform(input);
}
internal abstract partial class AffineColumnFunction : IColumnFunction
{
protected readonly IHost Host;
// The only derived classes are private inner classes
private AffineColumnFunction(IHost host)
{
Contracts.CheckValue(host, nameof(host));
Host = host;
}
void ICanSaveModel.Save(ModelSaveContext ctx) => SaveModel(ctx);
private protected abstract void SaveModel(ModelSaveContext ctx);
public abstract JToken PfaInfo(BoundPfaContext ctx, JToken srcToken);
public bool CanSaveOnnx(OnnxContext ctx) => true;
public abstract bool OnnxInfo(OnnxContext ctx, OnnxNode nodeProtoWrapper, int featureCount);
public abstract Delegate GetGetter(DataViewRow input, int icol);
public abstract void AttachMetadata(MetadataDispatcher.Builder bldr, DataViewType typeSrc);
public abstract NormalizingTransformer.NormalizerModelParametersBase GetNormalizerModelParams();
public static AffineColumnFunction Create(ModelLoadContext ctx, IHost host, DataViewType typeSrc)
{
Contracts.CheckValue(host, nameof(host));
if (typeSrc is NumberDataViewType)
{
if (typeSrc == NumberDataViewType.Single)
return Sng.ImplOne.Create(ctx, host, typeSrc);
if (typeSrc == NumberDataViewType.Double)
return Dbl.ImplOne.Create(ctx, host, typeSrc);
}
else if (typeSrc is VectorDataViewType vectorType && vectorType.ItemType is NumberDataViewType)
{
if (vectorType.ItemType == NumberDataViewType.Single)
return Sng.ImplVec.Create(ctx, host, vectorType);
if (vectorType.ItemType == NumberDataViewType.Double)
return Dbl.ImplVec.Create(ctx, host, vectorType);
}
throw host.ExceptUserArg(nameof(AffineArgumentsBase.Columns), "Wrong column type. Expected: Single, Double, or Vector of Single or Vector of Double. Got: {0}.", typeSrc.ToString());
}
private abstract class ImplOne<TFloat> : AffineColumnFunction
{
protected readonly TFloat Scale;
protected readonly TFloat Offset;
protected ImplOne(IHost host, TFloat scale, TFloat offset)
: base(host)
{
Scale = scale;
Offset = offset;
}
public override void AttachMetadata(MetadataDispatcher.Builder bldr, DataViewType typeSrc)
{
Host.CheckValue(bldr, nameof(bldr));
Host.CheckValue(typeSrc, nameof(typeSrc));
Host.Check(typeSrc.RawType == typeof(TFloat));
bldr.AddPrimitive("AffineScale", typeSrc, Scale);
bldr.AddPrimitive("AffineOffset", typeSrc, Offset);
}
public override NormalizingTransformer.NormalizerModelParametersBase GetNormalizerModelParams()
=> new NormalizingTransformer.AffineNormalizerModelParameters<TFloat>(Scale, Offset);
}
private abstract class ImplVec<TFloat> : AffineColumnFunction
{
protected readonly TFloat[] Scale;
protected readonly TFloat[] Offset;
protected readonly int[] IndicesNonZeroOffset;
protected ImplVec(IHost host, TFloat[] scale, TFloat[] offset, int[] indicesNonZeroOffset)
: base(host)
{
Host.AssertValue(scale);
Host.AssertValueOrNull(offset);
Host.Assert(indicesNonZeroOffset == null || offset != null);
Host.Assert(Offset == null || Offset.Length == Scale.Length);
Scale = scale;
Offset = offset;
IndicesNonZeroOffset = indicesNonZeroOffset;
}
public override void AttachMetadata(MetadataDispatcher.Builder bldr, DataViewType typeSrc)
{
Host.CheckValue(bldr, nameof(bldr));
Host.CheckValue(typeSrc, nameof(typeSrc));
Host.Check(typeSrc.GetVectorSize() == Scale.Length);
Host.Check(typeSrc.GetItemType().RawType == typeof(TFloat));
bldr.AddGetter<VBuffer<TFloat>>("AffineScale", typeSrc, ScaleMetadataGetter);
if (Offset != null)
bldr.AddGetter<VBuffer<TFloat>>("AffineOffset", typeSrc, OffsetMetadataGetter);
}
private void ScaleMetadataGetter(int col, ref VBuffer<TFloat> dst)
{
var src = new VBuffer<TFloat>(Scale.Length, Scale);
src.CopyTo(ref dst);
}
private void OffsetMetadataGetter(int col, ref VBuffer<TFloat> dst)
{
Host.AssertValue(Offset);
var src = new VBuffer<TFloat>(Offset.Length, Offset);
src.CopyTo(ref dst);
}
public override NormalizingTransformer.NormalizerModelParametersBase GetNormalizerModelParams()
=> new NormalizingTransformer.AffineNormalizerModelParameters<ImmutableArray<TFloat>>(ImmutableArray.Create(Scale), ImmutableArray.Create(Offset));
}
}
internal abstract partial class CdfColumnFunction : IColumnFunction
{
protected readonly IHost Host;
// The only derived classes are private inner classes
private CdfColumnFunction(IHost host)
{
Contracts.CheckValue(host, nameof(host));
Host = host;
}
void ICanSaveModel.Save(ModelSaveContext ctx) => SaveModel(ctx);
private protected abstract void SaveModel(ModelSaveContext ctx);
public JToken PfaInfo(BoundPfaContext ctx, JToken srcToken) => null;
public bool CanSaveOnnx(OnnxContext ctx) => false;
public bool OnnxInfo(OnnxContext ctx, OnnxNode nodeProtoWrapper, int featureCount)
=> throw Host.ExceptNotSupp();
public abstract Delegate GetGetter(DataViewRow input, int icol);
public abstract void AttachMetadata(MetadataDispatcher.Builder bldr, DataViewType typeSrc);
public abstract NormalizingTransformer.NormalizerModelParametersBase GetNormalizerModelParams();
public static CdfColumnFunction Create(ModelLoadContext ctx, IHost host, DataViewType typeSrc)
{
Contracts.CheckValue(host, nameof(host));
if (typeSrc is NumberDataViewType)
{
if (typeSrc == NumberDataViewType.Single)
return Sng.ImplOne.Create(ctx, host, typeSrc);
if (typeSrc == NumberDataViewType.Double)
return Dbl.ImplOne.Create(ctx, host, typeSrc);
}
else if (typeSrc is VectorDataViewType vectorType && vectorType.ItemType is NumberDataViewType)
{
if (vectorType.ItemType == NumberDataViewType.Single)
return Sng.ImplVec.Create(ctx, host, vectorType);
if (vectorType.ItemType == NumberDataViewType.Double)
return Dbl.ImplVec.Create(ctx, host, vectorType);
}
throw host.ExceptUserArg(nameof(AffineArgumentsBase.Columns), "Wrong column type. Expected: Single, Double, Vector of Single or Vector of Double. Got: {0}.", typeSrc);
}
private abstract class ImplOne<TFloat> : CdfColumnFunction
{
protected readonly TFloat Mean;
protected readonly TFloat Stddev;
protected readonly bool UseLog;
protected ImplOne(IHost host, TFloat mean, TFloat stddev, bool useLog)
: base(host)
{
Mean = mean;
Stddev = stddev;
UseLog = useLog;
}
public override void AttachMetadata(MetadataDispatcher.Builder bldr, DataViewType typeSrc)
{
Host.CheckValue(bldr, nameof(bldr));
Host.CheckValue(typeSrc, nameof(typeSrc));
Host.Check(typeSrc.RawType == typeof(TFloat));
bldr.AddPrimitive("CdfMean", typeSrc, Mean);
bldr.AddPrimitive("CdfStdDev", typeSrc, Stddev);
bldr.AddPrimitive("CdfUseLog", BooleanDataViewType.Instance, UseLog);
}
public override NormalizingTransformer.NormalizerModelParametersBase GetNormalizerModelParams()
=> new NormalizingTransformer.CdfNormalizerModelParameters<TFloat>(Mean, Stddev, UseLog);
}
private abstract class ImplVec<TFloat> : CdfColumnFunction
{
protected readonly TFloat[] Mean;
protected readonly TFloat[] Stddev;
protected readonly bool UseLog;
protected ImplVec(IHost host, TFloat[] mean, TFloat[] stddev, bool useLog)
: base(host)
{
Host.AssertValue(mean);
Host.AssertValue(stddev);
Host.Assert(mean.Length == stddev.Length);
Mean = mean;
Stddev = stddev;
UseLog = useLog;
}
public override void AttachMetadata(MetadataDispatcher.Builder bldr, DataViewType typeSrc)
{
Host.CheckValue(bldr, nameof(bldr));
Host.CheckValue(typeSrc, nameof(typeSrc));
Host.Check(typeSrc.GetVectorSize() == Mean.Length);
Host.Check(typeSrc.GetItemType().RawType == typeof(TFloat));
bldr.AddGetter<VBuffer<TFloat>>("CdfMean", typeSrc, MeanMetadataGetter);
bldr.AddGetter<VBuffer<TFloat>>("CdfStdDev", typeSrc, StddevMetadataGetter);
bldr.AddPrimitive("CdfUseLog", BooleanDataViewType.Instance, UseLog);
}
private void MeanMetadataGetter(int col, ref VBuffer<TFloat> dst)
{
var src = new VBuffer<TFloat>(Mean.Length, Mean);
src.CopyTo(ref dst);
}
private void StddevMetadataGetter(int col, ref VBuffer<TFloat> dst)
{
var src = new VBuffer<TFloat>(Stddev.Length, Stddev);
src.CopyTo(ref dst);
}
public override NormalizingTransformer.NormalizerModelParametersBase GetNormalizerModelParams()
=> new NormalizingTransformer.CdfNormalizerModelParameters<ImmutableArray<TFloat>>(ImmutableArray.Create(Mean), ImmutableArray.Create(Stddev), UseLog);
}
public const string LoaderSignature = "CdfNormalizeFunction";
public static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "CDFNORMF",
verWrittenCur: 0x00010001, // Initial
verReadableCur: 0x00010001,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature,
loaderAssemblyName: typeof(CdfColumnFunction).Assembly.FullName);
}
}
internal abstract partial class BinColumnFunction : IColumnFunction
{
protected readonly IHost Host;
protected BinColumnFunction(IHost host)
{
Contracts.CheckValue(host, nameof(host));
Host = host;
}
void ICanSaveModel.Save(ModelSaveContext ctx) => SaveModel(ctx);
private protected abstract void SaveModel(ModelSaveContext ctx);
public JToken PfaInfo(BoundPfaContext ctx, JToken srcToken) => null;
public bool CanSaveOnnx(OnnxContext ctx) => false;
public bool OnnxInfo(OnnxContext ctx, OnnxNode nodeProtoWrapper, int featureCount)
=> throw Host.ExceptNotSupp();
public abstract Delegate GetGetter(DataViewRow input, int icol);
public void AttachMetadata(MetadataDispatcher.Builder bldr, DataViewType typeSrc)
{
// REVIEW: How to attach information on the bins, to metadata?
}
public abstract NormalizingTransformer.NormalizerModelParametersBase GetNormalizerModelParams();
public static BinColumnFunction Create(ModelLoadContext ctx, IHost host, DataViewType typeSrc)
{
Contracts.CheckValue(host, nameof(host));
if (typeSrc is NumberDataViewType)
{
if (typeSrc == NumberDataViewType.Single)
return Sng.ImplOne.Create(ctx, host, typeSrc);
if (typeSrc == NumberDataViewType.Double)
return Dbl.ImplOne.Create(ctx, host, typeSrc);
}
if (typeSrc is VectorDataViewType vectorType && vectorType.ItemType is NumberDataViewType)
{
if (vectorType.ItemType == NumberDataViewType.Single)
return Sng.ImplVec.Create(ctx, host, vectorType);
if (vectorType.ItemType == NumberDataViewType.Double)
return Dbl.ImplVec.Create(ctx, host, vectorType);
}
throw host.ExceptUserArg(nameof(BinArguments.Columns), "Wrong column type. Expected: Single, Double, Vector of Single or Vector of Double. Got: {0}.", typeSrc);
}
public const string LoaderSignature = "BinNormalizeFunction";
public static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "BINNORMF",
verWrittenCur: 0x00010001, // Initial
verReadableCur: 0x00010001,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature,
loaderAssemblyName: typeof(BinColumnFunction).Assembly.FullName);
}
}
private abstract class OneColumnFunctionBuilderBase<TFloat> : IColumnFunctionBuilder
{
protected IHost Host;
protected readonly long Lim;
protected long Rem;
private readonly ValueGetter<TFloat> _getSrc;
protected OneColumnFunctionBuilderBase(IHost host, long lim, ValueGetter<TFloat> getSrc)
{
Contracts.CheckValue(host, nameof(host));
Host = host;
Rem = lim;
Lim = lim;
_getSrc = getSrc;
}
public bool ProcessValue()
{
TFloat tmp = default(TFloat);
_getSrc(ref tmp);
return ProcessValue(in tmp);
}
protected virtual bool ProcessValue(in TFloat val)
{
Host.Assert(Rem >= 0);
if (Rem == 0)
return false;
Rem--;
return true;
}
public abstract IColumnFunction CreateColumnFunction();
}
private abstract class VecColumnFunctionBuilderBase<TFloat> : IColumnFunctionBuilder
{
protected IHost Host;
protected readonly long Lim;
protected long Rem;
private readonly ValueGetter<VBuffer<TFloat>> _getSrc;
private VBuffer<TFloat> _buffer;
protected VecColumnFunctionBuilderBase(IHost host, long lim, ValueGetter<VBuffer<TFloat>> getSrc)
{
Contracts.CheckValue(host, nameof(host));
Host = host;
Rem = lim;
Lim = lim;
_getSrc = getSrc;
}
public bool ProcessValue()
{
_getSrc(ref _buffer);
return ProcessValue(in _buffer);
}
protected virtual bool ProcessValue(in VBuffer<TFloat> buffer)
{
Host.Assert(Rem >= 0);
if (Rem == 0)
return false;
Rem--;
return true;
}
public abstract IColumnFunction CreateColumnFunction();
}
private abstract class SupervisedBinFunctionBuilderBase : IColumnFunctionBuilder
{
protected readonly IHost Host;
protected readonly long Lim;
protected long Rem;
protected readonly List<int> Labels;
protected readonly int LabelCardinality;
private readonly ValueGetter<int> _labelGetterSrc;
protected SupervisedBinFunctionBuilderBase(IHost host, long lim, int labelColId, DataViewRow dataRow)
{
Contracts.CheckValue(host, nameof(host));
Host = host;
Rem = lim;
Lim = lim;
Labels = new List<int>();
_labelGetterSrc = GetLabelGetter(dataRow, labelColId, out LabelCardinality);
}
private ValueGetter<int> GetLabelGetter(DataViewRow row, int col, out int labelCardinality)
{
// The label column type is checked as part of args validation.
var type = row.Schema[col].Type;
Host.Assert(type is KeyDataViewType || type is NumberDataViewType);
if (type is KeyDataViewType keyType)
{
Host.Assert(type.GetKeyCountAsInt32(Host) > 0);
labelCardinality = type.GetKeyCountAsInt32(Host);
int size = type.GetKeyCountAsInt32(Host);
ulong src = 0;
var getSrc = RowCursorUtils.GetGetterAs<ulong>(NumberDataViewType.UInt64, row, col);
return
(ref int dst) =>
{
getSrc(ref src);
// The value should fall between 0 and _labelCardinality inclusive, where 0 is considered
// missing/invalid (this is the contract of the KeyType). However, we still handle the
// cases of too large values correctly (by treating them as invalid).
if (src <= (ulong)size)
dst = (int)src - 1;
else
dst = -1;
};
}
else
{
// REVIEW: replace with trainable binning for numeric value
labelCardinality = 2; // any numeric column is split into 0 and 1
Double src = 0;
var getSrc = RowCursorUtils.GetGetterAs<Double>(NumberDataViewType.Double, row, col);
return
(ref int dst) =>
{
getSrc(ref src);
// NaN maps to -1.
if (src > 0)
dst = 1;
else if (src <= 0)
dst = 0;
else
dst = -1;
};
}
}
public virtual bool ProcessValue()
{
Host.Assert(Rem >= 0);
if (Rem == 0)
return false;
Rem--;
int label = 0;
_labelGetterSrc(ref label);
var accept = label >= 0 && AcceptColumnValue(); // skip examples with negative label
if (accept)
Labels.Add(label);
return true;
}
public abstract IColumnFunction CreateColumnFunction();
protected abstract bool AcceptColumnValue();
}
private abstract class OneColumnSupervisedBinFunctionBuilderBase<TFloat> : SupervisedBinFunctionBuilderBase
{
private readonly ValueGetter<TFloat> _colGetterSrc;
protected readonly List<TFloat> ColValues;
protected OneColumnSupervisedBinFunctionBuilderBase(IHost host, long lim, int valueColId, int labelColId,
DataViewRow dataRow)
: base(host, lim, labelColId, dataRow)
{
_colGetterSrc = dataRow.GetGetter<TFloat>(dataRow.Schema[valueColId]);
ColValues = new List<TFloat>();
}
protected override bool AcceptColumnValue()
{
TFloat colValue = default(TFloat);
_colGetterSrc(ref colValue);
var result = AcceptColumnValue(in colValue);
if (result)
ColValues.Add(colValue);
return result;
}
protected abstract bool AcceptColumnValue(in TFloat colValue);
}
private abstract class VecColumnSupervisedBinFunctionBuilderBase<TFloat> : SupervisedBinFunctionBuilderBase
{
private readonly ValueGetter<VBuffer<TFloat>> _colValueGetter;
private VBuffer<TFloat> _buffer;
protected readonly List<TFloat>[] ColValues;
protected readonly int ColumnSlotCount;
protected VecColumnSupervisedBinFunctionBuilderBase(IHost host, long lim, int valueColId, int labelColId, DataViewRow dataRow)
: base(host, lim, labelColId, dataRow)
{
var valueCol = dataRow.Schema[valueColId];
_colValueGetter = dataRow.GetGetter<VBuffer<TFloat>>(valueCol);
Host.Assert(valueCol.Type.IsKnownSizeVector());
ColumnSlotCount = valueCol.Type.GetValueCount();
ColValues = new List<TFloat>[ColumnSlotCount];
for (int i = 0; i < ColumnSlotCount; i++)
ColValues[i] = new List<TFloat>();
_buffer = default(VBuffer<TFloat>);
}
protected override bool AcceptColumnValue()
{
_colValueGetter(ref _buffer);
bool result = AcceptColumnValue(in _buffer);
if (result)
{
if (_buffer.IsDense)
{
var values = _buffer.GetValues();
for (int i = 0; i < ColumnSlotCount; i++)
ColValues[i].Add(values[i]);
}
else
{
var indices = _buffer.GetIndices();
var values = _buffer.GetValues();
int k = 0;
for (int i = 0; i < values.Length; i++)
{
var val = values[i];
var index = indices[i];
while (k < index)
ColValues[k++].Add(default(TFloat));
ColValues[k++].Add(val);
}
while (k < ColumnSlotCount)
ColValues[k++].Add(default(TFloat));
}
}
return result;
}
protected abstract bool AcceptColumnValue(in VBuffer<TFloat> buffer);
}
internal static partial class MinMaxUtils
{
public static IColumnFunctionBuilder CreateBuilder(MinMaxArguments args, IHost host,
int icol, int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
Contracts.AssertValue(host);
host.AssertValue(args);
return CreateBuilder(new NormalizingEstimator.MinMaxColumnOptions(
args.Columns[icol].Name,
args.Columns[icol].Source ?? args.Columns[icol].Name,
args.Columns[icol].MaximumExampleCount ?? args.MaximumExampleCount,
args.Columns[icol].EnsureZeroUntouched ?? args.EnsureZeroUntouched), host, srcIndex, srcType, cursor);
}
public static IColumnFunctionBuilder CreateBuilder(NormalizingEstimator.MinMaxColumnOptions column, IHost host,
int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
var srcColumn = cursor.Schema[srcIndex];
if (srcType is NumberDataViewType)
{
if (srcType == NumberDataViewType.Single)
return Sng.MinMaxOneColumnFunctionBuilder.Create(column, host, srcType, cursor.GetGetter<Single>(srcColumn));
if (srcType == NumberDataViewType.Double)
return Dbl.MinMaxOneColumnFunctionBuilder.Create(column, host, srcType, cursor.GetGetter<Double>(srcColumn));
}
if (srcType is VectorDataViewType vectorType && vectorType.IsKnownSize && vectorType.ItemType is NumberDataViewType)
{
if (vectorType.ItemType == NumberDataViewType.Single)
return Sng.MinMaxVecColumnFunctionBuilder.Create(column, host, vectorType, cursor.GetGetter<VBuffer<Single>>(srcColumn));
if (vectorType.ItemType == NumberDataViewType.Double)
return Dbl.MinMaxVecColumnFunctionBuilder.Create(column, host, vectorType, cursor.GetGetter<VBuffer<Double>>(srcColumn));
}
throw host.ExceptParam(nameof(srcType), "Wrong column type for input column. Expected: Single, Double, Vector of Single or Vector of Double. Got: {0}.", srcType.ToString());
}
}
internal static partial class MeanVarUtils
{
public static IColumnFunctionBuilder CreateBuilder(MeanVarArguments args, IHost host,
int icol, int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
Contracts.AssertValue(host);
host.AssertValue(args);
return CreateBuilder(new NormalizingEstimator.MeanVarianceColumnOptions(
args.Columns[icol].Name,
args.Columns[icol].Source ?? args.Columns[icol].Name,
args.Columns[icol].MaximumExampleCount ?? args.MaximumExampleCount,
args.Columns[icol].EnsureZeroUntouched ?? args.EnsureZeroUntouched,
args.UseCdf), host, srcIndex, srcType, cursor);
}
public static IColumnFunctionBuilder CreateBuilder(NormalizingEstimator.MeanVarianceColumnOptions column, IHost host,
int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
Contracts.AssertValue(host);
var srcColumn = cursor.Schema[srcIndex];
if (srcType is NumberDataViewType)
{
if (srcType == NumberDataViewType.Single)
return Sng.MeanVarOneColumnFunctionBuilder.Create(column, host, srcType, cursor.GetGetter<Single>(srcColumn));
if (srcType == NumberDataViewType.Double)
return Dbl.MeanVarOneColumnFunctionBuilder.Create(column, host, srcType, cursor.GetGetter<Double>(srcColumn));
}
if (srcType is VectorDataViewType vectorType && vectorType.IsKnownSize && vectorType.ItemType is NumberDataViewType)
{
if (vectorType.ItemType == NumberDataViewType.Single)
return Sng.MeanVarVecColumnFunctionBuilder.Create(column, host, vectorType, cursor.GetGetter<VBuffer<Single>>(srcColumn));
if (vectorType.ItemType == NumberDataViewType.Double)
return Dbl.MeanVarVecColumnFunctionBuilder.Create(column, host, vectorType, cursor.GetGetter<VBuffer<Double>>(srcColumn));
}
throw host.ExceptParam(nameof(srcType), "Wrong column type for input column. Expected: Single, Double, Vector of Single or Vector of Double. Got: {0}.", srcType.ToString());
}
}
internal static partial class LogMeanVarUtils
{
public static IColumnFunctionBuilder CreateBuilder(LogMeanVarArguments args, IHost host,
int icol, int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
Contracts.AssertValue(host);
host.AssertValue(args);
return CreateBuilder(new NormalizingEstimator.LogMeanVarianceColumnOptions(
args.Columns[icol].Name,
args.Columns[icol].Source ?? args.Columns[icol].Name,
args.Columns[icol].MaximumExampleCount ?? args.MaximumExampleCount,
args.UseCdf), host, srcIndex, srcType, cursor);
}
public static IColumnFunctionBuilder CreateBuilder(NormalizingEstimator.LogMeanVarianceColumnOptions column, IHost host,
int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
Contracts.AssertValue(host);
host.AssertValue(column);
var srcColumn = cursor.Schema[srcIndex];
if (srcType is NumberDataViewType)
{
if (srcType == NumberDataViewType.Single)
return Sng.MeanVarOneColumnFunctionBuilder.Create(column, host, srcType, cursor.GetGetter<Single>(srcColumn));
if (srcType == NumberDataViewType.Double)
return Dbl.MeanVarOneColumnFunctionBuilder.Create(column, host, srcType, cursor.GetGetter<Double>(srcColumn));
}
if (srcType is VectorDataViewType vectorType && vectorType.IsKnownSize && vectorType.ItemType is NumberDataViewType)
{
if (vectorType.ItemType == NumberDataViewType.Single)
return Sng.MeanVarVecColumnFunctionBuilder.Create(column, host, vectorType, cursor.GetGetter<VBuffer<Single>>(srcColumn));
if (vectorType.ItemType == NumberDataViewType.Double)
return Dbl.MeanVarVecColumnFunctionBuilder.Create(column, host, vectorType, cursor.GetGetter<VBuffer<Double>>(srcColumn));
}
throw host.ExceptUserArg(nameof(column), "Wrong column type for column {0}. Expected: Single, Double, Vector of Single or Vector of Double. Got: {1}.", column.InputColumnName, srcType.ToString());
}
}
internal static partial class BinUtils
{
public static IColumnFunctionBuilder CreateBuilder(BinArguments args, IHost host,
int icol, int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
Contracts.AssertValue(host);
host.AssertValue(args);
return CreateBuilder(new NormalizingEstimator.BinningColumnOptions(
args.Columns[icol].Name,
args.Columns[icol].Source ?? args.Columns[icol].Name,
args.Columns[icol].MaximumExampleCount ?? args.MaximumExampleCount,
args.Columns[icol].EnsureZeroUntouched ?? args.EnsureZeroUntouched,
args.Columns[icol].NumBins ?? args.NumBins), host, srcIndex, srcType, cursor);
}
public static IColumnFunctionBuilder CreateBuilder(NormalizingEstimator.BinningColumnOptions column, IHost host,
int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
Contracts.AssertValue(host);
var srcColumn = cursor.Schema[srcIndex];
if (srcType is NumberDataViewType)
{
if (srcType == NumberDataViewType.Single)
return Sng.BinOneColumnFunctionBuilder.Create(column, host, srcType, cursor.GetGetter<Single>(srcColumn));
if (srcType == NumberDataViewType.Double)
return Dbl.BinOneColumnFunctionBuilder.Create(column, host, srcType, cursor.GetGetter<Double>(srcColumn));
}
if (srcType is VectorDataViewType vectorType && vectorType.IsKnownSize && vectorType.ItemType is NumberDataViewType)
{
if (vectorType.ItemType == NumberDataViewType.Single)
return Sng.BinVecColumnFunctionBuilder.Create(column, host, vectorType, cursor.GetGetter<VBuffer<Single>>(srcColumn));
if (vectorType.ItemType == NumberDataViewType.Double)
return Dbl.BinVecColumnFunctionBuilder.Create(column, host, vectorType, cursor.GetGetter<VBuffer<Double>>(srcColumn));
}
throw host.ExceptParam(nameof(column), "Wrong column type for column {0}. Expected: Single, Double, Vector of Single or Vector of Double. Got: {1}.", column.InputColumnName, srcType.ToString());
}
}
internal static class SupervisedBinUtils
{
public static IColumnFunctionBuilder CreateBuilder(SupervisedBinArguments args, IHost host,
int icol, int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
Contracts.AssertValue(host);
host.AssertValue(args);
// checking for label column
host.CheckUserArg(!string.IsNullOrWhiteSpace(args.LabelColumn), nameof(args.LabelColumn), "Must specify the label column name");
int labelColumnId = GetLabelColumnId(host, cursor.Schema, args.LabelColumn);
var labelColumnType = cursor.Schema[labelColumnId].Type;
if (labelColumnType is KeyDataViewType labelKeyType)
host.CheckUserArg(labelKeyType.Count > 0, nameof(args.LabelColumn), "Label column must have a known cardinality");
else
host.CheckUserArg(labelColumnType is NumberDataViewType, nameof(args.LabelColumn), "Label column must be a number or a key type");
return CreateBuilder(
new NormalizingEstimator.SupervisedBinningColumOptions(
args.Columns[icol].Name,
args.Columns[icol].Source ?? args.Columns[icol].Name,
args.LabelColumn ?? DefaultColumnNames.Label,
args.Columns[icol].MaximumExampleCount ?? args.MaximumExampleCount,
args.Columns[icol].EnsureZeroUntouched ?? args.EnsureZeroUntouched,
args.Columns[icol].NumBins ?? args.NumBins,
args.MinBinSize),
host, labelColumnId, srcIndex, srcType, cursor);
}
public static IColumnFunctionBuilder CreateBuilder(NormalizingEstimator.SupervisedBinningColumOptions column, IHost host,
string labelColumn, int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
int labelColumnId = GetLabelColumnId(host, cursor.Schema, labelColumn);
return CreateBuilder(column, host, labelColumnId, srcIndex, srcType, cursor);
}
private static IColumnFunctionBuilder CreateBuilder(NormalizingEstimator.SupervisedBinningColumOptions column, IHost host,
int labelColumnId, int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
Contracts.AssertValue(host);
if (srcType is NumberDataViewType)
{
if (srcType == NumberDataViewType.Single)
return Sng.SupervisedBinOneColumnFunctionBuilder.Create(column, host, srcIndex, labelColumnId, cursor);
if (srcType == NumberDataViewType.Double)
return Dbl.SupervisedBinOneColumnFunctionBuilder.Create(column, host, srcIndex, labelColumnId, cursor);
}
if (srcType is VectorDataViewType vectorType && vectorType.ItemType is NumberDataViewType)
{
if (vectorType.ItemType == NumberDataViewType.Single)
return Sng.SupervisedBinVecColumnFunctionBuilder.Create(column, host, srcIndex, labelColumnId, cursor);
if (vectorType.ItemType == NumberDataViewType.Double)
return Dbl.SupervisedBinVecColumnFunctionBuilder.Create(column, host, srcIndex, labelColumnId, cursor);
}
throw host.ExceptParam(nameof(column), "Wrong column type for column {0}. Expected: Single, Double, Vec<Single, n> or Vec<Double, n>. Got: {1}.",
column.InputColumnName,
srcType.ToString());
}
public static int GetLabelColumnId(IExceptionContext host, DataViewSchema schema, string labelColumnName)
{
Contracts.AssertValue(host);
host.AssertValue(schema);
int labelColumnId;
if (!schema.TryGetColumnIndex(labelColumnName, out labelColumnId))
throw host.ExceptUserArg(nameof(SupervisedBinArguments.LabelColumn), "Label column '{0}' not found", labelColumnName);
return labelColumnId;
}
}
internal static partial class RobustScaleUtils
{
public static IColumnFunctionBuilder CreateBuilder(RobustScalingArguments args, IHost host,
int icol, int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
Contracts.AssertValue(host);
host.AssertValue(args);
return CreateBuilder(new NormalizingEstimator.RobustScalingColumnOptions(
args.Columns[icol].Name,
args.Columns[icol].Source ?? args.Columns[icol].Name,
args.Columns[icol].MaximumExampleCount ?? args.MaximumExampleCount,
args.CenterData,
args.QuantileMin,
args.QuantileMax), host, srcIndex, srcType, cursor);
}
public static IColumnFunctionBuilder CreateBuilder(NormalizingEstimator.RobustScalingColumnOptions column, IHost host,
int srcIndex, DataViewType srcType, DataViewRowCursor cursor)
{
var srcColumn = cursor.Schema[srcIndex];
if (srcType is NumberDataViewType)
{
if (srcType == NumberDataViewType.Single)
return Sng.RobustScalerOneColumnFunctionBuilder.Create(column, host, srcType, column.CenterData, column.QuantileMin, column.QuantileMax, cursor.GetGetter<Single>(srcColumn));
if (srcType == NumberDataViewType.Double)
return Dbl.RobustScalerOneColumnFunctionBuilder.Create(column, host, srcType, column.CenterData, column.QuantileMin, column.QuantileMax, cursor.GetGetter<double>(srcColumn));
}
if (srcType is VectorDataViewType vectorType && vectorType.IsKnownSize && vectorType.ItemType is NumberDataViewType)
{
if (vectorType.ItemType == NumberDataViewType.Single)
return Sng.RobustScalerVecFunctionBuilder.Create(column, host, srcType as VectorDataViewType, column.CenterData, column.QuantileMin, column.QuantileMax, cursor.GetGetter<VBuffer<float>>(srcColumn));
if (vectorType.ItemType == NumberDataViewType.Double)
return Dbl.RobustScalerVecFunctionBuilder.Create(column, host, srcType as VectorDataViewType, column.CenterData, column.QuantileMin, column.QuantileMax, cursor.GetGetter<VBuffer<double>>(srcColumn));
}
throw host.ExceptParam(nameof(srcType), "Wrong column type for input column. Expected: Single, Double, Vector of Single or Vector of Double. Got: {0}.", srcType.ToString());
}
}
}
internal static partial class AffineNormSerializationUtils
{
public const string LoaderSignature = "AffineNormExec";
private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "AFF NORM",
// verWrittenCur: 0x00010001, // Initial
//verWrittenCur: 0x00010002, // Sparse representation
verWrittenCur: 0x00010003, // Scales multiply instead of divide
verReadableCur: 0x00010003,
verWeCanReadBack: 0x00010003,
loaderSignature: LoaderSignature,
loaderAssemblyName: typeof(AffineNormSerializationUtils).Assembly.FullName);
}
}
internal static partial class BinNormSerializationUtils
{
public const string LoaderSignature = "BinNormExec";
private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "BIN NORM",
verWrittenCur: 0x00010001,
verReadableCur: 0x00010001,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature,
loaderAssemblyName: typeof(BinNormSerializationUtils).Assembly.FullName);
}
}
internal static class MeanVarUtils
{
internal static void AdjustForZeros(ref Double mean, ref Double m2, ref long count, long numZeros)
{
Contracts.Assert(m2 >= 0);
Contracts.Assert(count >= 0);
Contracts.Assert(numZeros >= 0);
if (numZeros == 0)
return;
count += numZeros;
var delta = 0 - mean;
mean += delta * numZeros / count;
var d2 = delta * (0 - mean);
Contracts.Assert(d2 >= 0);
m2 += d2 * numZeros;
Contracts.Assert(m2 >= 0);
}
}
}
| 48.460404 | 223 | 0.595735 | [
"MIT"
] | 1Crazymoney/machinelearning | src/Microsoft.ML.Data/Transforms/NormalizeColumn.cs | 62,417 | C# |
using System;
using System.Windows.Forms;
namespace MasterChief.DotNet4.Utilities.WinForm
{
/// <summary>
/// 涉及窗体的帮助类
/// </summary>
/// 日期:2015-10-12 10:15
/// 备注:
public static class FormHelper
{
#region Methods
/// <summary>
/// 关闭登陆窗口,有别于hide方式,是直接close方式;
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="loginForm">登陆窗口</param>
/// 日期:2015-10-12 10:04
/// 备注:
public static void CloseLoginForm<T>(this T loginForm)
where T : Form, new()
{
if (loginForm != null)
{
loginForm.DialogResult = DialogResult.OK;
loginForm.Close();
}
}
/// <summary>
/// 弹出模式对话框
/// </summary>
/// <param name="paramter">参数</param>
public static void ShowDialogForm<T, P>(P paramter)
where T : Form, new()
where P : class
{
T winForm = (T) Activator.CreateInstance(typeof(T), paramter);
winForm.ShowDialog();
}
/// <summary>
/// 弹出模式对话框
/// </summary>
/// <param name="paramter1">参数1</param>
/// <param name="paramter2">参数2</param>
public static void ShowDialogForm<T, P1, P2>(P1 paramter1, P2 paramter2)
where T : Form, new()
{
var winForm = (T) Activator.CreateInstance(typeof(T), paramter1, paramter2);
winForm.ShowDialog();
}
/// <summary>
/// 弹出模式对话框
/// </summary>
/// <param name="paramter1">参数1</param>
/// <param name="paramter2">参数2</param>
/// <param name="paramter3">参数3</param>
/// <param name="paramter4">参数4</param>
public static void ShowDialogForm<T, P1, P2, P3, P4>(P1 paramter1, P2 paramter2, P3 paramter3, P4 paramter4)
where T : Form, new()
{
var winForm = (T) Activator.CreateInstance(typeof(T), paramter1, paramter2, paramter3, paramter4);
winForm.ShowDialog();
}
/// <summary>
/// 弹出模式对话框
/// </summary>
/// <typeparam name="T">窗体泛型</typeparam>
public static void ShowDialogForm<T>()
where T : Form, new()
{
T winForm = new T();
winForm.ShowDialog();
}
/// <summary>
/// 设置应用登陆界面
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <typeparam name="U">泛型</typeparam>
/// 日期:2015-10-12 9:56
/// 备注:
public static void ShowLoginForm<T, U>()
where T : Form, new()
where U : Form, new()
{
ShowLoginForm<T, U>(null);
}
/// <summary>
/// 设置应用登陆界面
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <typeparam name="U">泛型</typeparam>
/// <param name="mainFormFactory">委托,参数主界面对象</param>
/// 日期:2015-10-12 9:55
/// 备注:
public static void ShowLoginForm<T, U>(Action<U> mainFormFactory)
where T : Form, new()
where U : Form, new()
{
using (var winlogin = new T())
{
if (winlogin.ShowDialog() == DialogResult.OK)
{
var winMain = new U();
if (mainFormFactory != null) mainFormFactory(winMain);
Application.Run(winMain);
}
}
}
#endregion Methods
}
} | 29.622951 | 116 | 0.478141 | [
"MIT"
] | AkonCoder/MasterChief | MasterChief.DotNet4.Utilities/WinForm/FormHelper.cs | 3,890 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace _10.Student_Groups
{
class Program
{
static void Main(string[] args)
{
var townsList = ReadInput();
var numOfTowns = townsList.Count;
var groups = DistributeStudentsIntoGroups(townsList);
PrintOutput(groups, numOfTowns);
}
private static void PrintOutput(List<Group> groups, int num)
{
var numOfGroups = groups.Count;
var numOfTowns = num;
Console.WriteLine("Created {0} groups in {1} towns:", numOfGroups, numOfTowns);
foreach (var group in groups.OrderBy(x => x.Town.Name))
{
Console.WriteLine("{0} => {1}",
group.Town.Name, string.Join(", ", group.Students.Select(x => x.Email).ToList()));
}
}
private static List<Group> DistributeStudentsIntoGroups(List<Town> townsList)
{
var groups = new List<Group>();
foreach (var town in townsList.OrderBy(x => x.Name))
{
var students = town.Students
.OrderBy(d => d.RegistrationDate)
.ThenBy(n => n.Name)
.ThenBy(e => e.Email)
.ToList();
while (students.Any())
{
var group = new Group
{
Town = town,
Students = students.Take(town.Seats).ToList()
};
students = students.Skip(town.Seats).ToList();
groups.Add(group);
}
}
return groups;
}
private static List<Town> ReadInput()
{
var input = Console.ReadLine();
var townList = new List<Town>();
var indexOfLastTown = 0;
while (input != "End")
{
if (input.Contains("=>"))
{
var tokens = input.Split(new char[] { '>', '=', ' ' }, StringSplitOptions.RemoveEmptyEntries);
var townName = string.Empty;
var seats = 0;
if (tokens.Length == 3)
{
townName = tokens[0];
seats = int.Parse(tokens[1]);
}
else
{
townName = tokens[0] + " " + tokens[1];
seats = int.Parse(tokens[2]);
}
var town = new Town
{
Name = townName,
Seats = seats,
Students = new List<Student>()
};
townList.Add(town);
indexOfLastTown = townList.IndexOf(town);
}
else
{
var inputSplit = input.Split(new char[] {'|', ' '},StringSplitOptions.RemoveEmptyEntries);
var student = new Student
{
Name = inputSplit[0] + " " + inputSplit[1],
Email = inputSplit[2],
RegistrationDate = DateTime.ParseExact(inputSplit[3], "d-MMM-yyyy", CultureInfo.InvariantCulture)
};
townList[indexOfLastTown].Students.Add(student);
}
input = Console.ReadLine();
}
return townList;
}
class Student
{
public string Name { get; set; }
public string Email { get; set; }
public DateTime RegistrationDate { get; set; }
}
class Town
{
public string Name {get; set; }
public int Seats { get; set; }
public List<Student> Students { get; set; }
}
class Group
{
public Town Town { get; set; }
public List<Student> Students { get; set; }
}
}
}
| 29.909091 | 121 | 0.431611 | [
"MIT"
] | AneliaDoychinova/Programming-Fundamentals | 09. Objects and Classes/Exercises Objects and Classes/10. Student Groups/10. Student Groups.cs | 4,279 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Web.Mvc.Html;
using System.Web.Mvc.Properties;
using System.Web.Routing;
namespace System.Web.Mvc.Ajax
{
public static class AjaxExtensions
{
private const string LinkOnClickFormat = "Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), {0});";
private const string FormOnClickValue = "Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));";
private const string FormOnSubmitFormat = "Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), {0});";
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, AjaxOptions ajaxOptions)
{
return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, ajaxOptions);
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, object routeValues, AjaxOptions ajaxOptions)
{
return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
{
return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)
{
return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, AjaxOptions ajaxOptions)
{
return ActionLink(ajaxHelper, linkText, actionName, controllerName, null /* values */, ajaxOptions, null /* htmlAttributes */);
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions)
{
return ActionLink(ajaxHelper, linkText, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
{
RouteValueDictionary newValues = new RouteValueDictionary(routeValues);
RouteValueDictionary newAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
return ActionLink(ajaxHelper, linkText, actionName, controllerName, newValues, ajaxOptions, newAttributes);
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)
{
return ActionLink(ajaxHelper, linkText, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
if (String.IsNullOrEmpty(linkText))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");
}
string targetUrl = UrlHelper.GenerateUrl(null, actionName, controllerName, routeValues, ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);
return MvcHtmlString.Create(GenerateLink(ajaxHelper, linkText, targetUrl, GetAjaxOptions(ajaxOptions), htmlAttributes));
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
{
RouteValueDictionary newValues = new RouteValueDictionary(routeValues);
RouteValueDictionary newAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
return ActionLink(ajaxHelper, linkText, actionName, controllerName, protocol, hostName, fragment, newValues, ajaxOptions, newAttributes);
}
public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
if (String.IsNullOrEmpty(linkText))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");
}
string targetUrl = UrlHelper.GenerateUrl(null /* routeName */, actionName, controllerName, protocol, hostName, fragment, routeValues, ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);
return MvcHtmlString.Create(GenerateLink(ajaxHelper, linkText, targetUrl, ajaxOptions, htmlAttributes));
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, AjaxOptions ajaxOptions)
{
string formAction = ajaxHelper.ViewContext.HttpContext.Request.RawUrl;
return FormHelper(ajaxHelper, formAction, ajaxOptions, new RouteValueDictionary());
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, AjaxOptions ajaxOptions)
{
return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, ajaxOptions);
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, object routeValues, AjaxOptions ajaxOptions)
{
return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
{
return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)
{
return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, AjaxOptions ajaxOptions)
{
return BeginForm(ajaxHelper, actionName, controllerName, null /* values */, ajaxOptions, null /* htmlAttributes */);
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions)
{
return BeginForm(ajaxHelper, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
{
RouteValueDictionary newValues = new RouteValueDictionary(routeValues);
RouteValueDictionary newAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
return BeginForm(ajaxHelper, actionName, controllerName, newValues, ajaxOptions, newAttributes);
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)
{
return BeginForm(ajaxHelper, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);
}
public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
// get target URL
string formAction = UrlHelper.GenerateUrl(null, actionName, controllerName, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);
return FormHelper(ajaxHelper, formAction, ajaxOptions, htmlAttributes);
}
public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, AjaxOptions ajaxOptions)
{
return BeginRouteForm(ajaxHelper, routeName, null /* routeValues */, ajaxOptions, null /* htmlAttributes */);
}
public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, object routeValues, AjaxOptions ajaxOptions)
{
return BeginRouteForm(ajaxHelper, routeName, (object)routeValues, ajaxOptions, null /* htmlAttributes */);
}
public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
{
RouteValueDictionary newAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
return BeginRouteForm(ajaxHelper, routeName, new RouteValueDictionary(routeValues), ajaxOptions, newAttributes);
}
public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)
{
return BeginRouteForm(ajaxHelper, routeName, routeValues, ajaxOptions, null /* htmlAttributes */);
}
public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
string formAction = UrlHelper.GenerateUrl(routeName, null /* actionName */, null /* controllerName */, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);
return FormHelper(ajaxHelper, formAction, ajaxOptions, htmlAttributes);
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "You don't want to dispose of this object unless you intend to write to the response")]
private static MvcForm FormHelper(this AjaxHelper ajaxHelper, string formAction, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
TagBuilder builder = new TagBuilder("form");
builder.MergeAttributes(htmlAttributes);
builder.MergeAttribute("action", formAction);
builder.MergeAttribute("method", "post");
ajaxOptions = GetAjaxOptions(ajaxOptions);
if (ajaxHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
{
builder.MergeAttributes(ajaxOptions.ToUnobtrusiveHtmlAttributes());
}
else
{
builder.MergeAttribute("onclick", FormOnClickValue);
builder.MergeAttribute("onsubmit", GenerateAjaxScript(ajaxOptions, FormOnSubmitFormat));
}
if (ajaxHelper.ViewContext.ClientValidationEnabled)
{
// forms must have an ID for client validation
builder.GenerateId(ajaxHelper.ViewContext.FormIdGenerator());
}
ajaxHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));
MvcForm theForm = new MvcForm(ajaxHelper.ViewContext);
if (ajaxHelper.ViewContext.ClientValidationEnabled)
{
ajaxHelper.ViewContext.FormContext.FormId = builder.Attributes["id"];
}
return theForm;
}
public static MvcHtmlString GlobalizationScript(this AjaxHelper ajaxHelper)
{
return GlobalizationScript(ajaxHelper, CultureInfo.CurrentCulture);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "ajaxHelper", Justification = "This is an extension method")]
public static MvcHtmlString GlobalizationScript(this AjaxHelper ajaxHelper, CultureInfo cultureInfo)
{
return GlobalizationScriptHelper(AjaxHelper.GlobalizationScriptPath, cultureInfo);
}
internal static MvcHtmlString GlobalizationScriptHelper(string scriptPath, CultureInfo cultureInfo)
{
if (cultureInfo == null)
{
throw new ArgumentNullException("cultureInfo");
}
TagBuilder tagBuilder = new TagBuilder("script");
tagBuilder.MergeAttribute("type", "text/javascript");
string src = VirtualPathUtility.AppendTrailingSlash(scriptPath) + HttpUtility.UrlEncode(cultureInfo.Name) + ".js";
tagBuilder.MergeAttribute("src", src);
return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, object routeValues, AjaxOptions ajaxOptions)
{
return RouteLink(ajaxHelper, linkText, null /* routeName */, new RouteValueDictionary(routeValues), ajaxOptions,
new Dictionary<string, object>());
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
{
return RouteLink(ajaxHelper, linkText, null /* routeName */, new RouteValueDictionary(routeValues), ajaxOptions,
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)
{
return RouteLink(ajaxHelper, linkText, null /* routeName */, routeValues, ajaxOptions,
new Dictionary<string, object>());
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
return RouteLink(ajaxHelper, linkText, null /* routeName */, routeValues, ajaxOptions, htmlAttributes);
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, AjaxOptions ajaxOptions)
{
return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(), ajaxOptions,
new Dictionary<string, object>());
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, AjaxOptions ajaxOptions, object htmlAttributes)
{
return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(), ajaxOptions, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(), ajaxOptions, htmlAttributes);
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, object routeValues, AjaxOptions ajaxOptions)
{
return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(routeValues), ajaxOptions,
new Dictionary<string, object>());
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
{
return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(routeValues), ajaxOptions,
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)
{
return RouteLink(ajaxHelper, linkText, routeName, routeValues, ajaxOptions, new Dictionary<string, object>());
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
if (String.IsNullOrEmpty(linkText))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");
}
string targetUrl = UrlHelper.GenerateUrl(routeName, null /* actionName */, null /* controllerName */, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);
return MvcHtmlString.Create(GenerateLink(ajaxHelper, linkText, targetUrl, GetAjaxOptions(ajaxOptions), htmlAttributes));
}
public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
if (String.IsNullOrEmpty(linkText))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");
}
string targetUrl = UrlHelper.GenerateUrl(routeName, null /* actionName */, null /* controllerName */, protocol, hostName, fragment, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);
return MvcHtmlString.Create(GenerateLink(ajaxHelper, linkText, targetUrl, GetAjaxOptions(ajaxOptions), htmlAttributes));
}
private static string GenerateLink(AjaxHelper ajaxHelper, string linkText, string targetUrl, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
{
TagBuilder tag = new TagBuilder("a")
{
InnerHtml = HttpUtility.HtmlEncode(linkText)
};
tag.MergeAttributes(htmlAttributes);
tag.MergeAttribute("href", targetUrl);
if (ajaxHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
{
tag.MergeAttributes(ajaxOptions.ToUnobtrusiveHtmlAttributes());
}
else
{
tag.MergeAttribute("onclick", GenerateAjaxScript(ajaxOptions, LinkOnClickFormat));
}
return tag.ToString(TagRenderMode.Normal);
}
private static string GenerateAjaxScript(AjaxOptions ajaxOptions, string scriptFormat)
{
string optionsString = ajaxOptions.ToJavascriptString();
return String.Format(CultureInfo.InvariantCulture, scriptFormat, optionsString);
}
private static AjaxOptions GetAjaxOptions(AjaxOptions ajaxOptions)
{
return (ajaxOptions != null) ? ajaxOptions : new AjaxOptions();
}
}
}
| 57.886427 | 292 | 0.710006 | [
"Apache-2.0"
] | Icenium/aspnetwebstack | src/System.Web.Mvc/Ajax/AjaxExtensions.cs | 20,899 | C# |
// Copyright (c) 2021 Sergey Ivonchik
//
// 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 WhiteSharx.Ci.Revox.Options {
public class EmailOptions {
public string Login { get; private set; }
public string Password { get; private set; }
public string Host { get; private set; }
public int Port { get; private set; }
public int RetryCount { get; private set; }
public int RetryDelaySeconds { get; private set; }
}
}
| 47.677419 | 81 | 0.743572 | [
"MIT"
] | whitesharx/revox | Revox/Revox/Options/EmailOptions.cs | 1,478 | C# |
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using DependencyInjection;
namespace MyPlugin2
{
public class MyFruitConsumer : IFruitConsumer
{
private readonly IEnumerable<IFruitProducer> _producers;
public MyFruitConsumer(IEnumerable<IFruitProducer> producers)
{
_producers = producers;
}
public void Consume()
{
foreach (IFruitProducer? producer in _producers)
{
foreach (Fruit? fruit in producer.Produce())
{
Console.WriteLine($"Consumed {fruit.Name}");
}
}
}
}
}
| 26 | 111 | 0.584881 | [
"Apache-2.0"
] | PeTrProduct/DotNetCorePlugins | samples/dependency-injection/MyPlugin2/MyFruitConsumer.cs | 756 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.