context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Text;
/*
* Do not refactor this class too much.
* Should function as a reference implementation.
* */
namespace SevenDigital.Api.Wrapper.EndpointResolution.OAuth
{
public class OAuthBase
{
/// <summary>
/// Provides a predefined set of algorithms that are supported officially by the protocol
/// </summary>
public enum SignatureTypes
{
HMACSHA1,
PLAINTEXT,
RSASHA1
}
/// <summary>
/// Provides an internal structure to sort the query parameter
/// </summary>
protected class QueryParameter
{
private string name = null;
private string value = null;
public QueryParameter(string name, string value)
{
this.name = name;
this.value = value;
}
public string Name
{
get { return name; }
}
public string Value
{
get { return value; }
}
}
/// <summary>
/// Comparer class used to perform the sorting of the query parameters
/// </summary>
protected class QueryParameterComparer : IComparer<QueryParameter>
{
public int Compare(QueryParameter x, QueryParameter y)
{
if (x.Name == y.Name)
{
return string.Compare(x.Value, y.Value);
}
else
{
return string.Compare(x.Name, y.Name);
}
}
}
public const string OAuthVersion = "1.0";
protected const string OAuthParameterPrefix = "oauth_";
public bool includeVersion = true;
//
// List of know and used oauth parameters' names
//
public const string OAuthConsumerKeyKey = "oauth_consumer_key";
public const string OAuthCallbackKey = "oauth_callback";
public const string OAuthVersionKey = "oauth_version";
public const string OAuthSignatureMethodKey = "oauth_signature_method";
public const string OAuthSignatureKey = "oauth_signature";
public const string OAuthTimestampKey = "oauth_timestamp";
public const string OAuthNonceKey = "oauth_nonce";
public const string OAuthTokenKey = "oauth_token";
public const string OAuthTokenSecretKey = "oauth_token_secret";
public const string HMACSHA1SignatureType = "HMAC-SHA1";
public const string PlainTextSignatureType = "PLAINTEXT";
public const string RSASHA1SignatureType = "RSA-SHA1";
protected Random random = new Random();
protected static string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
/// <summary>
/// Helper function to compute a hash value
/// </summary>
/// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param>
/// <param name="data">The data to hash</param>
/// <returns>a Base64 string of the hash value</returns>
private string ComputeHash(HashAlgorithm hashAlgorithm, string data)
{
if (hashAlgorithm == null)
{
throw new ArgumentNullException("hashAlgorithm");
}
if (string.IsNullOrEmpty(data))
{
throw new ArgumentNullException("data");
}
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(data);
byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
/// <summary>
/// Internal function to cut out all non oauth query string parameters (all parameters not begining with "oauth_")
/// </summary>
/// <param name="parameters">The query string part of the Url</param>
/// <returns>A list of QueryParameter each containing the parameter name and value</returns>
private List<QueryParameter> GetQueryParameters(string parameters)
{
if (parameters.StartsWith("?"))
{
parameters = parameters.Remove(0, 1);
}
List<QueryParameter> result = new List<QueryParameter>();
if (!string.IsNullOrEmpty(parameters))
{
string[] p = parameters.Split('&');
foreach (string s in p)
{
if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix))
{
if (s.IndexOf('=') > -1)
{
string[] temp = s.Split('=');
result.Add(new QueryParameter(temp[0], temp[1]));
}
else
{
result.Add(new QueryParameter(s, string.Empty));
}
}
}
}
return result;
}
/// <summary>
/// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
/// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
/// </summary>
/// <param name="value">The value to Url encode</param>
/// <returns>Returns a Url encoded string</returns>
public static string UrlEncode(string value)
{
StringBuilder result = new StringBuilder();
foreach (char symbol in value)
{
if (unreservedChars.IndexOf(symbol) != -1)
{
result.Append(symbol);
}
else
{
result.Append('%' + String.Format("{0:X2}", (int)symbol));
}
}
return result.ToString();
}
/// <summary>
/// Normalizes the request parameters according to the spec
/// </summary>
/// <param name="parameters">The list of parameters already sorted</param>
/// <returns>a string representing the normalized parameters</returns>
protected string NormalizeRequestParameters(IList<QueryParameter> parameters)
{
StringBuilder sb = new StringBuilder();
QueryParameter p = null;
for (int i = 0; i < parameters.Count; i++)
{
p = parameters[i];
if (p.Name.StartsWith("oauth"))
{
sb.AppendFormat("{0}={1}", p.Name, UrlEncode(p.Value));
}
else
{
sb.AppendFormat("{0}={1}", p.Name, p.Value);
}
if (i < parameters.Count - 1)
{
sb.Append("&");
}
}
return sb.ToString();
}
/// <summary>
/// Generate the signature base that is used to produce the signature
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>.</param>
/// <returns>The signature base</returns>
public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret, string httpMethod, IDictionary<string, string> postParams, string timeStamp, string nonce, string signatureType, out string normalizedUrl, out string normalizedRequestParameters, string oAuthVersion)
{
if (token == null)
{
token = string.Empty;
}
if (tokenSecret == null)
{
tokenSecret = string.Empty;
}
if (string.IsNullOrEmpty(consumerKey))
{
throw new ArgumentNullException("consumerKey");
}
if (string.IsNullOrEmpty(httpMethod))
{
throw new ArgumentNullException("httpMethod");
}
if (string.IsNullOrEmpty(signatureType))
{
throw new ArgumentNullException("signatureType");
}
normalizedUrl = null;
normalizedRequestParameters = null;
List<QueryParameter> parameters = GetQueryParameters(url.Query);
if (!String.IsNullOrEmpty(oAuthVersion))
{
parameters.Add(new QueryParameter(OAuthVersionKey, oAuthVersion));
}
if (postParams != null & httpMethod.ToUpper() == "POST")
{
foreach (var key in postParams.Keys)
{
parameters.Add(new QueryParameter(key, postParams[key]));
}
}
parameters.Add(new QueryParameter(OAuthNonceKey, nonce));
parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));
parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType));
parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey));
if (!string.IsNullOrEmpty(token))
{
parameters.Add(new QueryParameter(OAuthTokenKey, token));
}
parameters.Sort(new QueryParameterComparer());
normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
{
normalizedUrl += ":" + url.Port;
}
normalizedUrl += url.AbsolutePath;
normalizedRequestParameters = NormalizeRequestParameters(parameters);
StringBuilder signatureBase = new StringBuilder();
signatureBase.AppendFormat("{0}&", httpMethod.ToUpper());
signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));
return signatureBase.ToString();
}
/// <summary>
/// Generate the signature value based on the given signature base and hash algorithm
/// </summary>
/// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
/// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash)
{
return ComputeHash(hash, signatureBase);
}
/// <summary>
/// Generates a signature using the HMAC-SHA1 algorithm
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="consumerSecret">The consumer seceret</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out string normalizedRequestParameters, IDictionary<string, string> postParameters)
{
return GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, httpMethod, timeStamp, nonce, SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters, postParameters, OAuthVersion);
}
/// <summary>
/// Generates a signature using the specified signatureType
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="consumerSecret">The consumer seceret</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The type of signature to use</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters, IDictionary<string, string> postParameters, string oAuthVersion)
{
normalizedUrl = null;
normalizedRequestParameters = null;
switch (signatureType)
{
case SignatureTypes.PLAINTEXT:
return Uri.EscapeDataString(string.Format("{0}&{1}", consumerSecret, tokenSecret));
case SignatureTypes.HMACSHA1:
string signatureBase = GenerateSignatureBase(url, consumerKey, token, tokenSecret, httpMethod, postParameters, timeStamp, nonce, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters, oAuthVersion);
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.UTF8.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)));
return GenerateSignatureUsingHash(signatureBase, hmacsha1);
case SignatureTypes.RSASHA1:
throw new NotImplementedException();
default:
throw new ArgumentException("Unknown signature type", "signatureType");
}
}
/// <summary>
/// Generate the timestamp for the signature
/// </summary>
/// <returns></returns>
public virtual string GenerateTimeStamp()
{
// Default implementation of UNIX time of the current UTC time
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/// <summary>
/// Generate a nonce
/// </summary>
/// <returns></returns>
public virtual string GenerateNonce()
{
// Just a simple implementation of a random number between 123400 and 9999999
return random.Next(123400, 9999999).ToString();
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Logging;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.TestHelpers.Stubs;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Cms.Tests.Integration.Testing;
namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Services
{
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)]
public class ContentServicePerformanceTest : UmbracoIntegrationTest
{
protected DocumentRepository DocumentRepository => (DocumentRepository)GetRequiredService<IDocumentRepository>();
protected IFileService FileService => GetRequiredService<IFileService>();
protected IContentTypeService ContentTypeService => GetRequiredService<IContentTypeService>();
protected IContentService ContentService => GetRequiredService<IContentService>();
protected IContentType ContentType { get; set; }
[SetUp]
public void SetUpData() => CreateTestData();
[Test]
public void Profiler() => Assert.IsInstanceOf<TestProfiler>(GetRequiredService<IProfiler>());
private static IProfilingLogger GetTestProfilingLogger()
{
var profiler = new TestProfiler();
return new ProfilingLogger(new NullLogger<ProfilingLogger>(), profiler);
}
[Test]
public void Retrieving_All_Content_In_Site()
{
// NOTE: Doing this the old 1 by 1 way and based on the results of the ContentServicePerformanceTest.Retrieving_All_Content_In_Site
// the old way takes 143795ms, the new above way takes:
// 14249ms
//
// ... NOPE, made some new changes, it is now....
// 5290ms !!!!!!
//
// that is a 96% savings of processing and sql calls!
//
// ... NOPE, made even more nice changes, it is now...
// 4452ms !!!!!!!
Template template = TemplateBuilder.CreateTextPageTemplate();
FileService.SaveTemplate(template);
ContentType contentType1 = ContentTypeBuilder.CreateTextPageContentType("test1", "test1", defaultTemplateId: template.Id);
ContentType contentType2 = ContentTypeBuilder.CreateTextPageContentType("test2", "test2", defaultTemplateId: template.Id);
ContentType contentType3 = ContentTypeBuilder.CreateTextPageContentType("test3", "test3", defaultTemplateId: template.Id);
ContentTypeService.Save(new[] { contentType1, contentType2, contentType3 });
contentType1.AllowedContentTypes = new[]
{
new ContentTypeSort(new Lazy<int>(() => contentType2.Id), 0, contentType2.Alias),
new ContentTypeSort(new Lazy<int>(() => contentType3.Id), 1, contentType3.Alias)
};
contentType2.AllowedContentTypes = new[]
{
new ContentTypeSort(new Lazy<int>(() => contentType1.Id), 0, contentType1.Alias),
new ContentTypeSort(new Lazy<int>(() => contentType3.Id), 1, contentType3.Alias)
};
contentType3.AllowedContentTypes = new[]
{
new ContentTypeSort(new Lazy<int>(() => contentType1.Id), 0, contentType1.Alias),
new ContentTypeSort(new Lazy<int>(() => contentType2.Id), 1, contentType2.Alias)
};
ContentTypeService.Save(new[] { contentType1, contentType2, contentType3 });
IEnumerable<Content> roots = ContentBuilder.CreateTextpageContent(contentType1, -1, 10);
ContentService.Save(roots);
foreach (Content root in roots)
{
IEnumerable<Content> item1 = ContentBuilder.CreateTextpageContent(contentType1, root.Id, 10);
IEnumerable<Content> item2 = ContentBuilder.CreateTextpageContent(contentType2, root.Id, 10);
IEnumerable<Content> item3 = ContentBuilder.CreateTextpageContent(contentType3, root.Id, 10);
ContentService.Save(item1.Concat(item2).Concat(item3));
}
var total = new List<IContent>();
using (GetTestProfilingLogger().TraceDuration<ContentServicePerformanceTest>("Getting all content in site"))
{
TestProfiler.Enable();
total.AddRange(ContentService.GetRootContent());
foreach (IContent content in total.ToArray())
{
total.AddRange(ContentService.GetPagedDescendants(content.Id, 0, int.MaxValue, out long _));
}
TestProfiler.Disable();
StaticApplicationLogging.Logger.LogInformation("Returned {Total} items", total.Count);
}
}
[Test]
public void Creating_100_Items()
{
// Arrange
IContentType contentType = ContentTypeService.Get(ContentType.Id);
IEnumerable<Content> pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100);
// Act
var watch = Stopwatch.StartNew();
ContentService.Save(pages, 0);
watch.Stop();
long elapsed = watch.ElapsedMilliseconds;
Debug.Print("100 content items saved in {0} ms", elapsed);
// Assert
Assert.That(pages.Any(x => x.HasIdentity == false), Is.False);
}
[Test]
public void Creating_1000_Items()
{
// Arrange
IContentType contentType = ContentTypeService.Get(ContentType.Id);
IEnumerable<Content> pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000);
// Act
var watch = Stopwatch.StartNew();
ContentService.Save(pages, 0);
watch.Stop();
long elapsed = watch.ElapsedMilliseconds;
Debug.Print("100 content items saved in {0} ms", elapsed);
// Assert
Assert.That(pages.Any(x => x.HasIdentity == false), Is.False);
}
[Test]
public void Getting_100_Uncached_Items()
{
// Arrange
IContentType contentType = ContentTypeService.Get(ContentType.Id);
IEnumerable<Content> pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100);
ContentService.Save(pages, 0);
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
DocumentRepository repository = DocumentRepository;
// Act
var watch = Stopwatch.StartNew();
IEnumerable<IContent> contents = repository.GetMany();
watch.Stop();
long elapsed = watch.ElapsedMilliseconds;
Debug.Print("100 content items retrieved in {0} ms without caching", elapsed);
// Assert
Assert.That(contents.Any(x => x.HasIdentity == false), Is.False);
Assert.That(contents.Any(x => x == null), Is.False);
}
}
[Test]
public void Getting_1000_Uncached_Items()
{
// Arrange
IContentType contentType = ContentTypeService.Get(ContentType.Id);
IEnumerable<Content> pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000);
ContentService.Save(pages, 0);
using (IScope scope = ScopeProvider.CreateScope())
{
DocumentRepository repository = DocumentRepository;
// Act
var watch = Stopwatch.StartNew();
IEnumerable<IContent> contents = repository.GetMany();
watch.Stop();
long elapsed = watch.ElapsedMilliseconds;
Debug.Print("1000 content items retrieved in {0} ms without caching", elapsed);
// Assert
// Assert.That(contents.Any(x => x.HasIdentity == false), Is.False);
// Assert.That(contents.Any(x => x == null), Is.False);
}
}
[Test]
public void Getting_100_Cached_Items()
{
// Arrange
IContentType contentType = ContentTypeService.Get(ContentType.Id);
IEnumerable<Content> pages = ContentBuilder.CreateTextpageContent(contentType, -1, 100);
ContentService.Save(pages, 0);
using (IScope scope = ScopeProvider.CreateScope())
{
DocumentRepository repository = DocumentRepository;
// Act
IEnumerable<IContent> contents = repository.GetMany();
var watch = Stopwatch.StartNew();
IEnumerable<IContent> contentsCached = repository.GetMany();
watch.Stop();
long elapsed = watch.ElapsedMilliseconds;
Debug.Print("100 content items retrieved in {0} ms with caching", elapsed);
// Assert
Assert.That(contentsCached.Any(x => x.HasIdentity == false), Is.False);
Assert.That(contentsCached.Any(x => x == null), Is.False);
Assert.That(contentsCached.Count(), Is.EqualTo(contents.Count()));
}
}
[Test]
public void Getting_1000_Cached_Items()
{
// Arrange
IContentType contentType = ContentTypeService.Get(ContentType.Id);
IEnumerable<Content> pages = ContentBuilder.CreateTextpageContent(contentType, -1, 1000);
ContentService.Save(pages, 0);
using (IScope scope = ScopeProvider.CreateScope())
{
DocumentRepository repository = DocumentRepository;
// Act
IEnumerable<IContent> contents = repository.GetMany();
var watch = Stopwatch.StartNew();
IEnumerable<IContent> contentsCached = repository.GetMany();
watch.Stop();
long elapsed = watch.ElapsedMilliseconds;
Debug.Print("1000 content items retrieved in {0} ms with caching", elapsed);
// Assert
// Assert.That(contentsCached.Any(x => x.HasIdentity == false), Is.False);
// Assert.That(contentsCached.Any(x => x == null), Is.False);
// Assert.That(contentsCached.Count(), Is.EqualTo(contents.Count()));
}
}
public void CreateTestData()
{
Template template = TemplateBuilder.CreateTextPageTemplate();
FileService.SaveTemplate(template);
// Create and Save ContentType "textpage" -> ContentType.Id
ContentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id);
ContentTypeService.Save(ContentType);
}
}
}
| |
/**
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Fungus
{
public class TextTagParser
{
public enum TokenType
{
Invalid,
Words, // A string of words
BoldStart, // b
BoldEnd, // /b
ItalicStart, // i
ItalicEnd, // /i
ColorStart, // color=red
ColorEnd, // /color
SizeStart, // size=20
SizeEnd, // /size
Wait, // w, w=0.5
WaitForInputNoClear, // wi
WaitForInputAndClear, // wc
WaitOnPunctuationStart, // wp, wp=0.5
WaitOnPunctuationEnd, // /wp
Clear, // c
SpeedStart, // s, s=60
SpeedEnd, // /s
Exit, // x
Message, // m=MessageName
VerticalPunch, // {vpunch=0.5}
HorizontalPunch, // {hpunch=0.5}
Punch, // {punch=0.5}
Flash, // {flash=0.5}
Audio, // {audio=Sound}
AudioLoop, // {audioloop=Sound}
AudioPause, // {audiopause=Sound}
AudioStop // {audiostop=Sound}
}
public class Token
{
public TokenType type = TokenType.Invalid;
public List<string> paramList;
}
public static string GetTagHelp()
{
return "" +
"\t{b} Bold Text {/b}\n" +
"\t{i} Italic Text {/i}\n" +
"\t{color=red} Color Text (color){/color}\n" +
"\t{size=30} Text size {/size}\n" +
"\n" +
"\t{s}, {s=60} Writing speed (chars per sec){/s}\n" +
"\t{w}, {w=0.5} Wait (seconds)\n" +
"\t{wi} Wait for input\n" +
"\t{wc} Wait for input and clear\n" +
"\t{wp}, {wp=0.5} Wait on punctuation (seconds){/wp}\n" +
"\t{c} Clear\n" +
"\t{x} Exit, advance to the next command without waiting for input\n" +
"\n" +
"\t{vpunch=10,0.5} Vertically punch screen (intensity,time)\n" +
"\t{hpunch=10,0.5} Horizontally punch screen (intensity,time)\n" +
"\t{punch=10,0.5} Punch screen (intensity,time)\n" +
"\t{flash=0.5} Flash screen (duration)\n" +
"\n" +
"\t{audio=AudioObjectName} Play Audio Once\n" +
"\t{audioloop=AudioObjectName} Play Audio Loop\n" +
"\t{audiopause=AudioObjectName} Pause Audio\n" +
"\t{audiostop=AudioObjectName} Stop Audio\n" +
"\n" +
"\t{m=MessageName} Broadcast message\n" +
"\t{$VarName} Substitute variable";
}
public virtual List<Token> Tokenize(string storyText)
{
List<Token> tokens = new List<Token>();
string pattern = @"\{.*?\}";
Regex myRegex = new Regex(pattern);
Match m = myRegex.Match(storyText); // m is the first match
int position = 0;
while (m.Success)
{
// Get bit leading up to tag
string preText = storyText.Substring(position, m.Index - position);
string tagText = m.Value;
if (preText != "")
{
AddWordsToken(tokens, preText);
}
AddTagToken(tokens, tagText);
position = m.Index + tagText.Length;
m = m.NextMatch();
}
if (position < storyText.Length)
{
string postText = storyText.Substring(position, storyText.Length - position);
if (postText.Length > 0)
{
AddWordsToken(tokens, postText);
}
}
// Remove all leading whitespace & newlines after a {c} or {wc} tag
// These characters are usually added for legibility when editing, but are not
// desireable when viewing the text in game.
bool trimLeading = false;
foreach (Token token in tokens)
{
if (trimLeading &&
token.type == TokenType.Words)
{
token.paramList[0] = token.paramList[0].TrimStart(' ', '\t', '\r', '\n');
}
if (token.type == TokenType.Clear ||
token.type == TokenType.WaitForInputAndClear)
{
trimLeading = true;
}
else
{
trimLeading = false;
}
}
return tokens;
}
protected virtual void AddWordsToken(List<Token> tokenList, string words)
{
Token token = new Token();
token.type = TokenType.Words;
token.paramList = new List<string>();
token.paramList.Add(words);
tokenList.Add(token);
}
protected virtual void AddTagToken(List<Token> tokenList, string tagText)
{
if (tagText.Length < 3 ||
tagText.Substring(0,1) != "{" ||
tagText.Substring(tagText.Length - 1,1) != "}")
{
return;
}
string tag = tagText.Substring(1, tagText.Length - 2);
TokenType type = TokenType.Invalid;
List<string> parameters = ExtractParameters(tag);
if (tag == "b")
{
type = TokenType.BoldStart;
}
else if (tag == "/b")
{
type = TokenType.BoldEnd;
}
else if (tag == "i")
{
type = TokenType.ItalicStart;
}
else if (tag == "/i")
{
type = TokenType.ItalicEnd;
}
else if (tag.StartsWith("color="))
{
type = TokenType.ColorStart;
}
else if (tag == "/color")
{
type = TokenType.ColorEnd;
}
else if (tag.StartsWith("size="))
{
type = TokenType.SizeStart;
}
else if (tag == "/size")
{
type = TokenType.SizeEnd;
}
else if (tag == "wi")
{
type = TokenType.WaitForInputNoClear;
}
if (tag == "wc")
{
type = TokenType.WaitForInputAndClear;
}
else if (tag.StartsWith("wp="))
{
type = TokenType.WaitOnPunctuationStart;
}
else if (tag == "wp")
{
type = TokenType.WaitOnPunctuationStart;
}
else if (tag == "/wp")
{
type = TokenType.WaitOnPunctuationEnd;
}
else if (tag.StartsWith("w="))
{
type = TokenType.Wait;
}
else if (tag == "w")
{
type = TokenType.Wait;
}
else if (tag == "c")
{
type = TokenType.Clear;
}
else if (tag.StartsWith("s="))
{
type = TokenType.SpeedStart;
}
else if (tag == "s")
{
type = TokenType.SpeedStart;
}
else if (tag == "/s")
{
type = TokenType.SpeedEnd;
}
else if (tag == "x")
{
type = TokenType.Exit;
}
else if (tag.StartsWith("m="))
{
type = TokenType.Message;
}
else if (tag.StartsWith("vpunch") ||
tag.StartsWith("vpunch="))
{
type = TokenType.VerticalPunch;
}
else if (tag.StartsWith("hpunch") ||
tag.StartsWith("hpunch="))
{
type = TokenType.HorizontalPunch;
}
else if (tag.StartsWith("punch") ||
tag.StartsWith("punch="))
{
type = TokenType.Punch;
}
else if (tag.StartsWith("flash") ||
tag.StartsWith("flash="))
{
type = TokenType.Flash;
}
else if (tag.StartsWith("audio="))
{
type = TokenType.Audio;
}
else if (tag.StartsWith("audioloop="))
{
type = TokenType.AudioLoop;
}
else if (tag.StartsWith("audiopause="))
{
type = TokenType.AudioPause;
}
else if (tag.StartsWith("audiostop="))
{
type = TokenType.AudioStop;
}
if (type != TokenType.Invalid)
{
Token token = new Token();
token.type = type;
token.paramList = parameters;
tokenList.Add(token);
}
else
{
Debug.LogWarning("Invalid text tag " + tag);
}
}
protected virtual List<string> ExtractParameters(string input)
{
List<string> paramsList = new List<string>();
int index = input.IndexOf('=');
if (index == -1)
{
return paramsList;
}
string paramsStr = input.Substring(index + 1);
var splits = paramsStr.Split(',');
foreach (var p in splits)
{
paramsList.Add(p.Trim());
}
return paramsList;
}
}
}
| |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using PHBGTU.Areas.Carousel.Models;
using PHBGTU.Data;
using PHBGTU.Areas.Carousel.ViewModels;
namespace PHBGTU.Areas.Carousel.Controllers
{
[Area("Carousel")]//Associate controller with area
[Authorize]//check for authenticated user for all actions
public class SlideshowController : Controller
{
private readonly ApplicationDbContext _context;
public SlideshowController(ApplicationDbContext context)
{
_context = context;
}
// GET: Slideshow
public async Task<IActionResult> Index()
{
return View(await _context.Slideshows.ToListAsync());
}
// GET: Slideshow/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var slideshow = await _context.Slideshows.SingleOrDefaultAsync(m => m.SlideshowId == id);
if (slideshow == null)
{
return NotFound();
}
return View(slideshow);
}
// GET: Slideshow/Create
public IActionResult Create()
{
return View();
}
// POST: Slideshow/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("SlideshowId,CreateTimestamp,CreateUser,Description,Item,ScriptBottom,ScriptTop,Template,UpdateTimestamp,UpdateUser")] Slideshow slideshow)
{
if (ModelState.IsValid)
{
_context.Add(slideshow);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(slideshow);
}
// GET: Slideshow/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var slideshow = await _context.Slideshows.SingleOrDefaultAsync(m => m.SlideshowId == id);
if (slideshow == null)
{
return NotFound();
}
return View(slideshow);
}
// POST: Slideshow/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("SlideshowId,CreateTimestamp,CreateUser,Description,Item,ScriptBottom,ScriptTop,Template,UpdateTimestamp,UpdateUser")] Slideshow slideshow)
{
if (id != slideshow.SlideshowId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(slideshow);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!SlideshowExists(slideshow.SlideshowId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(slideshow);
}
// GET: Slideshow/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var slideshow = await _context.Slideshows.SingleOrDefaultAsync(m => m.SlideshowId == id);
if (slideshow == null)
{
return NotFound();
}
return View(slideshow);
}
// POST: Slideshow/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var slideshow = await _context.Slideshows.SingleOrDefaultAsync(m => m.SlideshowId == id);
_context.Slideshows.Remove(slideshow);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
[AllowAnonymous]
public async Task<IActionResult> FromContentBlock(int? id, bool useLayout = true)
{
if (id == null)
{
return NotFound();
}
var contentBlock = await _context.ContentBlocks.SingleOrDefaultAsync(m => m.ContentBlockId == id);
var contentBlockCategory = await _context.ContentBlockCategories.SingleOrDefaultAsync(m => m.ContentBlockCategoryId == contentBlock.ContentBlockCategoryId);
var contentBlockMedias = await _context.ContentBlockMedias.Where(m => m.ContentBlockId == id).Include(m => m.Media).ToListAsync();
var slideshow = await _context.Slideshows.SingleOrDefaultAsync(m => m.SlideshowId == contentBlock.SlideshowId);
if (contentBlock == null || contentBlockCategory.Description != "Slideshow" || contentBlockMedias == null || slideshow == null)
{
return NotFound();
}
var items = "";
var itemsCount = 0;
foreach (var item in contentBlockMedias)
{
var currentItem = slideshow.Item;
if (itemsCount == 0)
{
currentItem = currentItem.Replace("[Slideshow_ActiveClass]", "active");
}
else {
currentItem = currentItem.Replace("[Slideshow_ActiveClass]", string.Empty);
}
currentItem = currentItem.Replace("[Slideshow_ImageSource]", item.Media.WebPath);
currentItem = currentItem.Replace("[Slideshow_ImageDescription]", item.Media.Description);
currentItem = currentItem.Replace("[Slideshow_LinkReference]", item.Media.LinkURL);
currentItem = currentItem.Replace("[Slideshow_LinkText]", item.Media.LinkText);
currentItem = currentItem.Replace("\r", string.Empty);
currentItem = currentItem.Replace("\n", string.Empty);
currentItem = currentItem.Replace("\t", string.Empty);
items = items + currentItem;
itemsCount++;
}
var content = slideshow.Template;
content = content.Replace("[Slideshow_Items]", items);
var model = new SlideshowFromContentBlockResponse
{
Success = true,
ScriptTop = slideshow.ScriptTop,
Content = content,
ScriptBottom = slideshow.ScriptBottom,
UseLayout = useLayout
};
return View(model);
}
private bool SlideshowExists(int id)
{
return _context.Slideshows.Any(e => e.SlideshowId == id);
}
}
}
| |
// 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 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ProtectedItemsOperations.
/// </summary>
public static partial class ProtectedItemsOperationsExtensions
{
/// <summary>
/// Provides the details of the backed up item. This is an asynchronous
/// operation. To know the status of the operation, call the
/// GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item name whose details are to be fetched.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static ProtectedItemResource Get(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ODataQuery<GetProtectedItemQueryObject> odataQuery = default(ODataQuery<GetProtectedItemQueryObject>))
{
return ((IProtectedItemsOperations)operations).GetAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Provides the details of the backed up item. This is an asynchronous
/// operation. To know the status of the operation, call the
/// GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item name whose details are to be fetched.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ProtectedItemResource> GetAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ODataQuery<GetProtectedItemQueryObject> odataQuery = default(ODataQuery<GetProtectedItemQueryObject>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Enables backup of an item or to modifies the backup policy information of
/// an already backed up item. This is an asynchronous operation. To know the
/// status of the operation, call the GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backup item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backup item.
/// </param>
/// <param name='protectedItemName'>
/// Item name to be backed up.
/// </param>
/// <param name='parameters'>
/// resource backed up item
/// </param>
public static void CreateOrUpdate(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ProtectedItemResource parameters)
{
operations.CreateOrUpdateAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Enables backup of an item or to modifies the backup policy information of
/// an already backed up item. This is an asynchronous operation. To know the
/// status of the operation, call the GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backup item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backup item.
/// </param>
/// <param name='protectedItemName'>
/// Item name to be backed up.
/// </param>
/// <param name='parameters'>
/// resource backed up item
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateOrUpdateAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ProtectedItemResource parameters, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateOrUpdateWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Used to disable backup of an item within a container. This is an
/// asynchronous operation. To know the status of the request, call the
/// GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item to be deleted.
/// </param>
public static void Delete(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName)
{
operations.DeleteAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName).GetAwaiter().GetResult();
}
/// <summary>
/// Used to disable backup of an item within a container. This is an
/// asynchronous operation. To know the status of the request, call the
/// GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure
{
/// <summary>
/// The Service Management API provides programmatic access to much of the
/// functionality available through the Management Portal. The Service
/// Management API is a REST API. All API operations are performed over
/// SSL, and are mutually authenticated using X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public static partial class ServiceCertificateOperationsExtensions
{
/// <summary>
/// The Begin Creating Service Certificate operation adds a certificate
/// to a hosted service. This operation is an asynchronous operation.
/// To determine whether the management service has finished
/// processing the request, call Get Operation Status. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The DNS prefix name of your service.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Creating Service
/// Certificate operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse BeginCreating(this IServiceCertificateOperations operations, string serviceName, ServiceCertificateCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServiceCertificateOperations)s).BeginCreatingAsync(serviceName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Begin Creating Service Certificate operation adds a certificate
/// to a hosted service. This operation is an asynchronous operation.
/// To determine whether the management service has finished
/// processing the request, call Get Operation Status. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The DNS prefix name of your service.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Creating Service
/// Certificate operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> BeginCreatingAsync(this IServiceCertificateOperations operations, string serviceName, ServiceCertificateCreateParameters parameters)
{
return operations.BeginCreatingAsync(serviceName, parameters, CancellationToken.None);
}
/// <summary>
/// The Begin Deleting Service Certificate operation deletes a service
/// certificate from the certificate store of a hosted service. This
/// operation is an asynchronous operation. To determine whether the
/// management service has finished processing the request, call Get
/// Operation Status. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Deleting Service
/// Certificate operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse BeginDeleting(this IServiceCertificateOperations operations, ServiceCertificateDeleteParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServiceCertificateOperations)s).BeginDeletingAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Begin Deleting Service Certificate operation deletes a service
/// certificate from the certificate store of a hosted service. This
/// operation is an asynchronous operation. To determine whether the
/// management service has finished processing the request, call Get
/// Operation Status. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Deleting Service
/// Certificate operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> BeginDeletingAsync(this IServiceCertificateOperations operations, ServiceCertificateDeleteParameters parameters)
{
return operations.BeginDeletingAsync(parameters, CancellationToken.None);
}
/// <summary>
/// The Create Service Certificate operation adds a certificate to a
/// hosted service. This operation is an asynchronous operation. To
/// determine whether the management service has finished processing
/// the request, call Get Operation Status. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The DNS prefix name of your service.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Service Certificate
/// operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse Create(this IServiceCertificateOperations operations, string serviceName, ServiceCertificateCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServiceCertificateOperations)s).CreateAsync(serviceName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Create Service Certificate operation adds a certificate to a
/// hosted service. This operation is an asynchronous operation. To
/// determine whether the management service has finished processing
/// the request, call Get Operation Status. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The DNS prefix name of your service.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Service Certificate
/// operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> CreateAsync(this IServiceCertificateOperations operations, string serviceName, ServiceCertificateCreateParameters parameters)
{
return operations.CreateAsync(serviceName, parameters, CancellationToken.None);
}
/// <summary>
/// The Delete Service Certificate operation deletes a service
/// certificate from the certificate store of a hosted service. This
/// operation is an asynchronous operation. To determine whether the
/// management service has finished processing the request, call Get
/// Operation Status. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Delete Service Certificate
/// operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse Delete(this IServiceCertificateOperations operations, ServiceCertificateDeleteParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServiceCertificateOperations)s).DeleteAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete Service Certificate operation deletes a service
/// certificate from the certificate store of a hosted service. This
/// operation is an asynchronous operation. To determine whether the
/// management service has finished processing the request, call Get
/// Operation Status. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Delete Service Certificate
/// operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> DeleteAsync(this IServiceCertificateOperations operations, ServiceCertificateDeleteParameters parameters)
{
return operations.DeleteAsync(parameters, CancellationToken.None);
}
/// <summary>
/// The Get Service Certificate operation returns the public data for
/// the specified X.509 certificate associated with a hosted service.
/// (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Get Service Certificate
/// operation.
/// </param>
/// <returns>
/// The Get Service Certificate operation response.
/// </returns>
public static ServiceCertificateGetResponse Get(this IServiceCertificateOperations operations, ServiceCertificateGetParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServiceCertificateOperations)s).GetAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Service Certificate operation returns the public data for
/// the specified X.509 certificate associated with a hosted service.
/// (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Get Service Certificate
/// operation.
/// </param>
/// <returns>
/// The Get Service Certificate operation response.
/// </returns>
public static Task<ServiceCertificateGetResponse> GetAsync(this IServiceCertificateOperations operations, ServiceCertificateGetParameters parameters)
{
return operations.GetAsync(parameters, CancellationToken.None);
}
/// <summary>
/// The List Service Certificates operation lists all of the service
/// certificates associated with the specified hosted service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The DNS prefix name of your hosted service.
/// </param>
/// <returns>
/// The List Service Certificates operation response.
/// </returns>
public static ServiceCertificateListResponse List(this IServiceCertificateOperations operations, string serviceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServiceCertificateOperations)s).ListAsync(serviceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List Service Certificates operation lists all of the service
/// certificates associated with the specified hosted service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The DNS prefix name of your hosted service.
/// </param>
/// <returns>
/// The List Service Certificates operation response.
/// </returns>
public static Task<ServiceCertificateListResponse> ListAsync(this IServiceCertificateOperations operations, string serviceName)
{
return operations.ListAsync(serviceName, CancellationToken.None);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.IO;
using System.Text;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
internal static class StringUtils
{
public const string CarriageReturnLineFeed = "\r\n";
public const string Empty = "";
public const char CarriageReturn = '\r';
public const char LineFeed = '\n';
public const char Tab = '\t';
public static string FormatWith(this string format, IFormatProvider provider, object arg0)
{
return format.FormatWith(provider, new[] { arg0 });
}
public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1)
{
return format.FormatWith(provider, new[] { arg0, arg1 });
}
public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2)
{
return format.FormatWith(provider, new[] { arg0, arg1, arg2 });
}
public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2, object arg3)
{
return format.FormatWith(provider, new[] { arg0, arg1, arg2, arg3 });
}
private static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
// leave this a private to force code to use an explicit overload
// avoids stack memory being reserved for the object array
ValidationUtils.ArgumentNotNull(format, nameof(format));
return string.Format(provider, format, args);
}
/// <summary>
/// Determines whether the string is all white space. Empty string will return false.
/// </summary>
/// <param name="s">The string to test whether it is all white space.</param>
/// <returns>
/// <c>true</c> if the string is all white space; otherwise, <c>false</c>.
/// </returns>
public static bool IsWhiteSpace(string s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (s.Length == 0)
{
return false;
}
for (int i = 0; i < s.Length; i++)
{
if (!char.IsWhiteSpace(s[i]))
{
return false;
}
}
return true;
}
public static StringWriter CreateStringWriter(int capacity)
{
StringBuilder sb = new StringBuilder(capacity);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
return sw;
}
public static void ToCharAsUnicode(char c, char[] buffer)
{
buffer[0] = '\\';
buffer[1] = 'u';
buffer[2] = MathUtils.IntToHex((c >> 12) & '\x000f');
buffer[3] = MathUtils.IntToHex((c >> 8) & '\x000f');
buffer[4] = MathUtils.IntToHex((c >> 4) & '\x000f');
buffer[5] = MathUtils.IntToHex(c & '\x000f');
}
public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (valueSelector == null)
{
throw new ArgumentNullException(nameof(valueSelector));
}
var caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase));
if (caseInsensitiveResults.Count() <= 1)
{
return caseInsensitiveResults.SingleOrDefault();
}
else
{
// multiple results returned. now filter using case sensitivity
var caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal));
return caseSensitiveResults.SingleOrDefault();
}
}
public static string ToCamelCase(string s)
{
if (string.IsNullOrEmpty(s) || !char.IsUpper(s[0]))
{
return s;
}
char[] chars = s.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if (i == 1 && !char.IsUpper(chars[i]))
{
break;
}
bool hasNext = (i + 1 < chars.Length);
if (i > 0 && hasNext && !char.IsUpper(chars[i + 1]))
{
break;
}
char c;
#if !(DOTNET || PORTABLE)
c = char.ToLower(chars[i], CultureInfo.InvariantCulture);
#else
c = char.ToLowerInvariant(chars[i]);
#endif
chars[i] = c;
}
return new string(chars);
}
internal enum SnakeCaseState
{
Start,
Lower,
Upper,
NewWord
}
public static string ToSnakeCase(string s)
{
if (string.IsNullOrEmpty(s))
{
return s;
}
StringBuilder sb = new StringBuilder();
SnakeCaseState state = SnakeCaseState.Start;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ' ')
{
if (state != SnakeCaseState.Start)
{
state = SnakeCaseState.NewWord;
}
}
else if (char.IsUpper(s[i]))
{
switch (state)
{
case SnakeCaseState.Upper:
bool hasNext = (i + 1 < s.Length);
if (i > 0 && hasNext)
{
char nextChar = s[i + 1];
if (!char.IsUpper(nextChar) && nextChar != '_')
{
sb.Append('_');
}
}
break;
case SnakeCaseState.Lower:
case SnakeCaseState.NewWord:
sb.Append('_');
break;
}
char c;
#if !(DOTNET || PORTABLE)
c = char.ToLower(s[i], CultureInfo.InvariantCulture);
#else
c = char.ToLowerInvariant(s[i]);
#endif
sb.Append(c);
state = SnakeCaseState.Upper;
}
else if (s[i] == '_')
{
sb.Append('_');
state = SnakeCaseState.Start;
}
else
{
if (state == SnakeCaseState.NewWord)
{
sb.Append('_');
}
sb.Append(s[i]);
state = SnakeCaseState.Lower;
}
}
return sb.ToString();
}
public static bool IsHighSurrogate(char c)
{
#if !(PORTABLE40 || PORTABLE)
return char.IsHighSurrogate(c);
#else
return (c >= 55296 && c <= 56319);
#endif
}
public static bool IsLowSurrogate(char c)
{
#if !(PORTABLE40 || PORTABLE)
return char.IsLowSurrogate(c);
#else
return (c >= 56320 && c <= 57343);
#endif
}
public static bool StartsWith(this string source, char value)
{
return (source.Length > 0 && source[0] == value);
}
public static bool EndsWith(this string source, char value)
{
return (source.Length > 0 && source[source.Length - 1] == value);
}
}
}
| |
#region License
//
// AnnotationStrategy.cs January 2010
//
// Copyright (C) 2010, Niall Gallagher <niallg@users.sf.net>
//
// 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
#region Using directives
using SimpleFramework.Xml.Strategy;
using SimpleFramework.Xml.Stream;
using System.Collections.Generic;
using System;
#endregion
namespace SimpleFramework.Xml.Util {
/// <summary>
/// The <c>AnnotationStrategy</c> object is used to intercept
/// the serialization process and delegate to custom converters. This
/// strategy uses the <c>Convert</c> annotation to specify the
/// converter to use for serialization and deserialization. If there
/// is no annotation present on the field or method representing the
/// object instance to be serialized then this acts as a transparent
/// proxy to an internal strategy.
/// <p>
/// By default the <c>TreeStrategy</c> is used to perform the
/// normal serialization process should there be no annotation
/// specifying a converter to use. However, any implementation can
/// be used, including the <c>CycleStrategy</c>, which handles
/// cycles in the object graph. To specify the internal strategy to
/// use it can be provided in the constructor.
/// </summary>
/// <seealso>
/// SimpleFramework.Xml.Strategy.TreeStrategy
/// </seealso>
public class AnnotationStrategy : Strategy {
/// <summary>
/// This is used to scan for an annotation and create a converter.
/// </summary>
private readonly ConverterScanner scanner;
/// <summary>
/// This is the strategy that is delegated to for serialization.
/// </summary>
private readonly Strategy strategy;
/// <summary>
/// Constructor for the <c>AnnotationStrategy</c> object.
/// This creates a strategy that intercepts serialization on any
/// annotated method or field. If no annotation exists then this
/// delegates to an internal <c>TreeStrategy</c> object.
/// </summary>
public AnnotationStrategy() {
this(new TreeStrategy());
}
/// <summary>
/// Constructor for the <c>AnnotationStrategy</c> object.
/// This creates a strategy that intercepts serialization on any
/// annotated method or field. If no annotation exists then this
/// will delegate to the <c>Strategy</c> provided.
/// </summary>
/// <param name="strategy">
/// the internal strategy to delegate to
/// </param>
public AnnotationStrategy(Strategy strategy) {
this.scanner = new ConverterScanner();
this.strategy = strategy;
}
/// <summary>
/// This is used to read the <c>Value</c> which will be used
/// to represent the deserialized object. If there is an annotation
/// present then the value will contain an object instance. If it
/// does not then it is up to the internal strategy to determine
/// what the returned value contains.
/// </summary>
/// <param name="type">
/// this is the type that represents a method or field
/// </param>
/// <param name="node">
/// this is the node representing the XML element
/// </param>
/// <param name="map">
/// this is the session map that contain variables
/// </param>
/// <returns>
/// the value representing the deserialized value
/// </returns>
public Value Read(Type type, NodeMap<InputNode> node, Dictionary map) {
Value value = strategy.Read(type, node, map);
if(IsReference(value)) {
return value;
}
return Read(type, node, value);
}
/// <summary>
/// This is used to read the <c>Value</c> which will be used
/// to represent the deserialized object. If there is an annotation
/// present then the value will contain an object instance. If it
/// does not then it is up to the internal strategy to determine
/// what the returned value contains.
/// </summary>
/// <param name="type">
/// this is the type that represents a method or field
/// </param>
/// <param name="node">
/// this is the node representing the XML element
/// </param>
/// <param name="value">
/// this is the value from the internal strategy
/// </param>
/// <returns>
/// the value representing the deserialized value
/// </returns>
public Value Read(Type type, NodeMap<InputNode> node, Value value) {
Converter converter = scanner.GetConverter(type, value);
InputNode parent = node.getNode();
if(converter != null) {
Object data = converter.Read(parent);
if(value != null) {
value.setValue(data);
}
return new Reference(value, data);
}
return value;
}
/// <summary>
/// This is used to serialize a representation of the object value
/// provided. If there is a <c>Convert</c> annotation present
/// on the provided type then this will use the converter specified
/// to serialize a representation of the object. If however there
/// is no annotation then this will delegate to the internal
/// strategy. This returns true if the serialization has completed.
/// </summary>
/// <param name="type">
/// this is the type that represents the field or method
/// </param>
/// <param name="value">
/// this is the object instance to be serialized
/// </param>
/// <param name="node">
/// this is the XML element to be serialized to
/// </param>
/// <param name="map">
/// this is the session map used by the serializer
/// </param>
/// <returns>
/// this returns true if it was serialized, false otherwise
/// </returns>
public bool Write(Type type, Object value, NodeMap<OutputNode> node, Dictionary map) {
bool reference = strategy.Write(type, value, node, map);
if(!reference) {
return Write(type, value, node);
}
return reference;
}
/// <summary>
/// This is used to serialize a representation of the object value
/// provided. If there is a <c>Convert</c> annotation present
/// on the provided type then this will use the converter specified
/// to serialize a representation of the object. If however there
/// is no annotation then this will delegate to the internal
/// strategy. This returns true if the serialization has completed.
/// </summary>
/// <param name="type">
/// this is the type that represents the field or method
/// </param>
/// <param name="value">
/// this is the object instance to be serialized
/// </param>
/// <param name="node">
/// this is the XML element to be serialized to
/// </param>
/// <returns>
/// this returns true if it was serialized, false otherwise
/// </returns>
public bool Write(Type type, Object value, NodeMap<OutputNode> node) {
Converter converter = scanner.GetConverter(type, value);
OutputNode parent = node.getNode();
if(converter != null) {
converter.Write(parent, value);
return true;
}
return false;
}
/// <summary>
/// This is used to determine if the <c>Value</c> provided
/// represents a reference. If it does represent a reference then
/// this will return true, if it does not then this returns false.
/// </summary>
/// <param name="value">
/// this is the value instance to be evaluated
/// </param>
/// <returns>
/// this returns true if the value represents a reference
/// </returns>
public bool IsReference(Value value) {
return value != null && value.IsReference();
}
}
}
| |
// Copyright (c) 2015 James Liu
//
// See the LISCENSE file for copying permission.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Hourai.DanmakU {
public static class DanmakuCollectionExtensions {
public static IEnumerable<Danmaku> ForEach(this IEnumerable<Danmaku> danmakus,
Action<Danmaku> action,
Func<Danmaku, bool> filter = null) {
if (danmakus == null)
return null;
if (action == null)
throw new ArgumentNullException("action");
foreach (Danmaku danmaku in danmakus) {
if (danmaku != null && (filter == null || filter(danmaku)))
action(danmaku);
}
return danmakus;
}
#region Position Functions
/// <summary>
/// Moves all of the Danmaku in the collection to a specified 2D point.
/// </summary>
/// <remarks>
/// All contained null objects will be ignored.
/// If the collection is <c>null</c>, this function does nothing and returns null.
/// See: <see cref="Danmaku.Position"/>
/// </remarks>
/// <param name="danmakus">The enumerable collection of Danmaku. Will throw NullReferenceException if null.</param>
/// <param name="position">the position to move the contained danmaku to, in absolute world coordinates.</param>
public static IEnumerable<Danmaku> MoveTo(this IEnumerable<Danmaku> danmakus, Vector2 position, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Position = position, filter);
}
/// <summary>
/// Moves all of the Danmaku in the collection to random 2D points specified by a array of 2D positions.
/// </summary>
/// <remarks>
/// Positions are chosen randomly and independently for each Danmaku from a uniform distribution.
/// This function is not thread-safe: it can only be called from the Unity main thread as it utilizes Unity API calls.
/// All contained null objects will be ignored.
/// See: <see cref="Danmaku.Position"/>
/// </remarks>
/// <param name="danmakus">The enumerable collection of Danmaku. Will throw NullReferenceException if null.</param>
/// <param name="positions">the potential positions to move the contained danmaku to, in absolute world coordinates.</param>
/// <exception cref="ArgumentNullException">Thrown if the position array is null.</exception>
public static IEnumerable<Danmaku> MoveTo(this IEnumerable<Danmaku> danmakus, ICollection<Vector2> positions, Func<Danmaku, bool> filter = null)
{
if (positions == null)
throw new ArgumentNullException("positions");
return danmakus.ForEach(x => x.Position = positions.Random(), filter);
}
/// <summary>
/// Moves all of the Danmaku in the collection to a specified 2D point based on a Unity Transform's absolute world position.
/// </summary>
/// <remarks>
/// This function discards the Z axis and will place the Danmaku at the corresponding 2D location on the Z = 0 plane.
/// This function is not thread-safe: it can only be called from the Unity main thread as it utilizes Unity API calls.
/// All contained null objects will be ignored.
/// See: <see cref="Danmaku.Position"/>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if the transform is null.</exception>
/// <param name="danmakus">The enumerable collection of Danmaku. Function does nothing if this is null.</param>
/// <param name="transform">The Transform to move to.</param>
public static IEnumerable<Danmaku> MoveTo(this IEnumerable<Danmaku> danmakus, Transform transform, Func<Danmaku, bool> filter = null)
{
if (transform == null)
throw new ArgumentNullException("transform");
return danmakus.MoveTo(transform.position);
}
/// <summary>
/// Moves all of the Danmaku in the collection to a specified 2D point based on a Unity Component's Transform's absolute world position.
/// </summary>
/// <remarks>
/// This function discards the Z axis and will place the Danmaku at the corresponding 2D location on the Z = 0 plane.
/// This function is not thread-safe: it can only be called from the Unity main thread as it utilizes Unity API calls.
/// All contained null objects will be ignored.
/// See: <see cref="Danmaku.Position"/>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if the Component is null.</exception>
/// <param name="danmakus">The enumerable collection of Danmaku. Function does nothing if this is null.</param>
/// <param name="component">The Component to move to.</param>
public static IEnumerable<Danmaku> MoveTo(this IEnumerable<Danmaku> danmakus, Component component, Func<Danmaku, bool> filter = null)
{
if (component == null)
throw new ArgumentNullException("component");
return danmakus.MoveTo(component.transform.position);
}
/// <summary>
/// Moves all of the Danmaku in the collection to a specified 2D point based on a Unity GameObject's Transform's absolute world position.
/// </summary>
/// <remarks>
/// This function discards the Z axis and will place the Danmaku at the corresponding 2D location on the Z = 0 plane.
/// This function is not thread-safe: it can only be called from the Unity main thread as it utilizes Unity API calls.
/// All contained null objects will be ignored.
/// See: <see cref="Danmaku.Position"/>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if the position array is null.</exception>
/// <param name="danmakus">The enumerable collection of Danmaku. Does nothing if it is null.</param>
/// <param name="gameObject">The GameObject to move to. Will throw ArgumentNullException if null.</param>
public static IEnumerable<Danmaku> MoveTo(this IEnumerable<Danmaku> danmakus, GameObject gameObject, Func<Danmaku, bool> filter = null)
{
if (gameObject == null)
throw new ArgumentNullException("gameObject");
return danmakus.MoveTo(gameObject.transform.position);
}
/// <summary>
/// Moves all of the Danmaku in the collection to a random 2D points within a specified rectangular area.
/// </summary>
/// <remarks>
/// Positions are chosen randomly and independently for each Danmaku from a uniform distribution within a specified Rect.
/// This function is not thread-safe: it can only be called from the Unity main thread as it utilizes Unity API calls.
/// All contained null objects will be ignored.
/// The Danmaku objects can be filtered with the <paramref name="filter"/> parameter. If it returns <c>true</c> for an Danmaku, then it is moved.
/// If <paramref name="filter"/> is null, all Danmaku are moved.
/// See: <see cref="Danmaku.Position"/>
/// </remarks>
/// <param name="danmakus">The enumerable collection of Danmaku. This function does nothing if it is null.</param>
/// <param name="area">The rectangular area to move the contained Danmaku to.</param>
/// <param name="filter">a function to filter whether or not to apply the action. Returns true if it should. Defaults to null.</param>
public static IEnumerable<Danmaku> MoveTo(this IEnumerable<Danmaku> danmakus, Rect area, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Position = area.RandomPoint(), filter);
}
/// <summary>
/// Moves all of the Danmaku in a collection towards a specified point in space.
/// </summary>
/// <remarks>
/// Positions are chosen randomly and independently for each Danmaku from a uniform distribution.
/// This function is not thread-safe: it can only be called from the Unity main thread as it utilizes Unity API calls.
/// All contained null objects will be ignored.
/// The Danmaku objects can be filtered with the <paramref name="filter"/> parameter. If it returns <c>true</c> for an Danmaku, then it is moved.
/// If <paramref name="filter"/> is null, all Danmaku are moved.
/// See: <see cref="Danmaku.Position"/>
/// </remarks>
/// <param name="danmakus">The enumerable collection of Danmaku. This function does nothing if it is null.</param>
/// <param name="target">The target point in space to move towards, in absolute world coordinates.</param>
/// <param name="maxDistanceDelta">The maximum distance to move.</param>
/// <param name="filter">a function to filter whether or not to apply the action. Returns true if it should. Defaults to null.</param>
/// <typeparam name="IEnumerable<Danmaku>">The type of the collection.</typeparam>
public static IEnumerable<Danmaku> MoveTowards(this IEnumerable<Danmaku> danmakus,
Vector2 target,
float maxDistanceDelta,
Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Position = Vector2.MoveTowards(x.Position, target, maxDistanceDelta), filter);
}
public static IEnumerable<Danmaku> MoveTowards(this IEnumerable<Danmaku> danmakus,
Transform target,
float maxDistanceDelta,
Func<Danmaku, bool> filter = null)
{
if (target == null)
throw new ArgumentNullException("target");
return danmakus.MoveTowards(target.position, maxDistanceDelta);
}
public static IEnumerable<Danmaku> MoveTowards(this IEnumerable<Danmaku> danmakus,
Component target,
float maxDistanceDelta,
Func<Danmaku, bool> filter = null)
{
if (target == null)
throw new ArgumentNullException("target");
return danmakus.MoveTowards(target.transform.position,
maxDistanceDelta);
}
public static IEnumerable<Danmaku> MoveTowards(this IEnumerable<Danmaku> danmakus,
GameObject target,
float maxDistanceDelta,
Func<Danmaku, bool> filter = null)
{
if (target == null)
throw new ArgumentNullException("target");
return danmakus.MoveTowards(target.transform.position,
maxDistanceDelta);
}
/// <summary>
/// Instantaneously translates all of the Danmaku in the collections by a specified change in position.
/// All contained null objects will be ignored.
/// </summary>
/// <param name="danmakus">The enumerable collection of Danmaku. Does nothing if it is null.</param>
/// <param name="deltaPos">The change in position.</param>
public static IEnumerable<Danmaku> Translate(this IEnumerable<Danmaku> danmakus, Vector2 deltaPos, Func<Danmaku, bool> filter = null)
{
if (deltaPos != Vector2.zero)
return danmakus.ForEach(x => x.Position += deltaPos, filter);
return danmakus;
}
#endregion
#region Rotation Functions
public static IEnumerable<Danmaku> RotateTo(this IEnumerable<Danmaku> danmakus, float rotation, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Rotation = rotation, filter);
}
public static IEnumerable<Danmaku> RotateTo(this IEnumerable<Danmaku> danmakus,
ICollection<float> rotations,
Func<Danmaku, bool> filter = null)
{
if (rotations == null)
throw new ArgumentNullException("rotations");
return danmakus.ForEach(x => x.Rotation = rotations.Random(), filter);
}
public static IEnumerable<Danmaku> Rotate(this IEnumerable<Danmaku> danmakus, float delta, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Rotation += delta, filter);
}
#endregion
#region Speed Functions
public static IEnumerable<Danmaku> Speed(this IEnumerable<Danmaku> danmakus, float speed, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Speed = speed, filter);
}
public static IEnumerable<Danmaku> Speed(this IEnumerable<Danmaku> danmakus, ICollection<float> speeds, Func<Danmaku, bool> filter = null)
{
if (speeds == null)
throw new ArgumentNullException("speeds");
return danmakus.ForEach(x => x.Speed = speeds.Random(), filter);
}
public static IEnumerable<Danmaku> Accelerate(this IEnumerable<Danmaku> danmakus, float deltaSpeed, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Speed += deltaSpeed, filter);
}
#endregion
#region Angular Speed Functions
public static IEnumerable<Danmaku> AngularSpeed(this IEnumerable<Danmaku> danmakus,
float angularSpeed,
Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.AngularSpeed = angularSpeed, filter);
}
public static IEnumerable<Danmaku> AngularSpeed(this IEnumerable<Danmaku> danmakus,
ICollection<float> angularSpeeds,
Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.AngularSpeed = angularSpeeds.Random(), filter);
}
public static IEnumerable<Danmaku> AngularAccelerate(this IEnumerable<Danmaku> danmakus,
float deltaSpeed,
Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.AngularSpeed += deltaSpeed, filter);
}
#endregion
#region Damage Functions
public static IEnumerable<Danmaku> Damage(this IEnumerable<Danmaku> danmakus, int damage, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Damage = damage, filter);
}
public static IEnumerable<Danmaku> Damage(this IEnumerable<Danmaku> danmakus, ICollection<int> damages, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.AngularSpeed = damages.Random(), filter);
}
#endregion
#region Color Functions
public static IEnumerable<Danmaku> Color(this IEnumerable<Danmaku> danmakus, Color color, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Color = color, filter);
}
public static IEnumerable<Danmaku> Color(this IEnumerable<Danmaku> danmakus, ICollection<Color> colors, Func<Danmaku, bool> filter = null)
{
if (colors == null)
throw new ArgumentNullException("colors");
return danmakus.ForEach(x => x.Color = colors.Random(), filter);
}
public static IEnumerable<Danmaku> Color(this IEnumerable<Danmaku> danmakus, Gradient colors, Func<Danmaku, bool> filter = null)
{
if (colors == null)
throw new ArgumentNullException("colors");
return danmakus.ForEach(x => x.Color = colors.Random(), filter);
}
#endregion
#region Controller Functions
public static IEnumerable<Danmaku> AddController(this IEnumerable<Danmaku> danmakus,
Action<Danmaku> controller,
Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Controller += controller, filter);
}
public static IEnumerable<Danmaku> RemoveController(this IEnumerable<Danmaku> danmakus,
Action<Danmaku> controller,
Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Controller -= controller, filter);
}
public static IEnumerable<Danmaku> ClearControllers(this IEnumerable<Danmaku> danmakus, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.ClearControllers(), filter);
}
#endregion
#region General Functions
public static IEnumerable<Danmaku> Destroy(this IEnumerable<Danmaku> danmakus, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.Destroy(), filter);
}
#endregion
#region Misc Functions
public static IEnumerable<Danmaku> CollisionCheck(this IEnumerable<Danmaku> danmakus, bool collisionCheck, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => x.CollisionCheck = collisionCheck, filter);
}
public static IEnumerable<Danmaku> Match(this IEnumerable<Danmaku> danmakus, DanmakuPrefab prefab, Func<Danmaku, bool> filter = null)
{
return danmakus.ForEach(x => prefab.Match(x), filter);
}
#endregion
#region Fire Functions
public static IEnumerable<Danmaku> Fire(this IEnumerable<Danmaku> danmakus,
FireData data,
bool useRotation = true,
Func<Danmaku, bool> filter = null)
{
Vector2 tempPos = data.Position;
float tempRot = data.Rotation;
danmakus.ForEach(delegate(Danmaku danmaku) {
data.Position = danmaku.Position;
if (useRotation)
data.Rotation = danmaku.Rotation;
data.Fire();
},
filter);
data.Position = tempPos;
data.Rotation = tempRot;
return danmakus;
}
#endregion
}
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK;
using OpenTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Sprites;
using osu.Game.Users;
using osu.Game.Graphics;
using osu.Game.Graphics.Backgrounds;
using osu.Game.Overlays.MedalSplash;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input;
using OpenTK.Input;
using System.Linq;
using osu.Framework.Graphics.Shapes;
using System;
using osu.Framework.MathUtils;
namespace osu.Game.Overlays
{
public class MedalOverlay : FocusedOverlayContainer
{
public const float DISC_SIZE = 400;
private const float border_width = 5;
private readonly Medal medal;
private readonly Box background;
private readonly Container backgroundStrip, particleContainer;
private readonly BackgroundStrip leftStrip, rightStrip;
private readonly CircularContainer disc;
private readonly Sprite innerSpin, outerSpin;
private DrawableMedal drawableMedal;
private SampleChannel getSample;
public MedalOverlay(Medal medal)
{
this.medal = medal;
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
background = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(60),
},
outerSpin = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(DISC_SIZE + 500),
Alpha = 0f,
},
backgroundStrip = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = border_width,
Alpha = 0f,
Children = new[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.CentreRight,
Width = 0.5f,
Padding = new MarginPadding { Right = DISC_SIZE / 2 },
Children = new[]
{
leftStrip = new BackgroundStrip(0f, 1f)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
},
},
new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.CentreLeft,
Width = 0.5f,
Padding = new MarginPadding { Left = DISC_SIZE / 2 },
Children = new[]
{
rightStrip = new BackgroundStrip(1f, 0f),
},
},
},
},
particleContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Alpha = 0f,
},
disc = new CircularContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Alpha = 0f,
Masking = true,
AlwaysPresent = true,
BorderColour = Color4.White,
BorderThickness = border_width,
Size = new Vector2(DISC_SIZE),
Scale = new Vector2(0.8f),
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.FromHex(@"05262f"),
},
new Triangles
{
RelativeSizeAxes = Axes.Both,
TriangleScale = 2,
ColourDark = OsuColour.FromHex(@"04222b"),
ColourLight = OsuColour.FromHex(@"052933"),
},
innerSpin = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(1.05f),
Alpha = 0.25f,
},
},
},
};
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, TextureStore textures, AudioManager audio)
{
getSample = audio.Sample.Get(@"MedalSplash/medal-get");
innerSpin.Texture = outerSpin.Texture = textures.Get(@"MedalSplash/disc-spin");
disc.EdgeEffect = leftStrip.EdgeEffect = rightStrip.EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Glow,
Colour = colours.Blue.Opacity(0.5f),
Radius = 50,
};
disc.Add(drawableMedal = new DrawableMedal(medal)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.X,
});
}
protected override void LoadComplete()
{
base.LoadComplete();
Show();
}
protected override void Update()
{
base.Update();
particleContainer.Add(new MedalParticle(RNG.Next(0, 359)));
}
protected override bool OnClick(InputState state)
{
dismiss();
return true;
}
protected override void OnFocusLost(InputState state)
{
if (state.Keyboard.Keys.Contains(Key.Escape)) dismiss();
}
private const double initial_duration = 400;
private const double step_duration = 900;
protected override void PopIn()
{
base.PopIn();
this.FadeIn(200);
background.FlashColour(Color4.White.Opacity(0.25f), 400);
getSample.Play();
innerSpin.Spin(20000, RotationDirection.Clockwise);
outerSpin.Spin(40000, RotationDirection.Clockwise);
using (BeginDelayedSequence(200, true))
{
disc.FadeIn(initial_duration)
.ScaleTo(1f, initial_duration * 2, Easing.OutElastic);
particleContainer.FadeIn(initial_duration);
outerSpin.FadeTo(0.1f, initial_duration * 2);
using (BeginDelayedSequence(initial_duration + 200, true))
{
backgroundStrip.FadeIn(step_duration);
leftStrip.ResizeWidthTo(1f, step_duration, Easing.OutQuint);
rightStrip.ResizeWidthTo(1f, step_duration, Easing.OutQuint);
this.Animate().Schedule(() =>
{
if (drawableMedal.State != DisplayState.Full)
drawableMedal.State = DisplayState.Icon;
})
.Delay(step_duration).Schedule(() =>
{
if (drawableMedal.State != DisplayState.Full)
drawableMedal.State = DisplayState.MedalUnlocked;
})
.Delay(step_duration).Schedule(() =>
{
if (drawableMedal.State != DisplayState.Full)
drawableMedal.State = DisplayState.Full;
});
}
}
}
protected override void PopOut()
{
base.PopOut();
this.FadeOut(200);
}
private void dismiss()
{
if (drawableMedal.State != DisplayState.Full)
{
// if we haven't yet, play out the animation fully
drawableMedal.State = DisplayState.Full;
FinishTransforms(true);
return;
}
Hide();
Expire();
}
private class BackgroundStrip : Container
{
public BackgroundStrip(float start, float end)
{
RelativeSizeAxes = Axes.Both;
Width = 0f;
Colour = ColourInfo.GradientHorizontal(Color4.White.Opacity(start), Color4.White.Opacity(end));
Masking = true;
Children = new[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.White,
}
};
}
}
private class MedalParticle : CircularContainer
{
private readonly float direction;
private Vector2 positionForOffset(float offset) => new Vector2((float)(offset * Math.Sin(direction)), (float)(offset * Math.Cos(direction)));
public MedalParticle(float direction)
{
this.direction = direction;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Position = positionForOffset(DISC_SIZE / 2);
Masking = true;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Glow,
Colour = colours.Blue.Opacity(0.5f),
Radius = 5,
};
this.MoveTo(positionForOffset(DISC_SIZE / 2 + 200), 500);
this.FadeOut(500);
Expire();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using NuGet.Common;
namespace NuGet.Commands
{
[Command(typeof(NuGetResources), "pack", "PackageCommandDescription", MaxArgs = 1, UsageSummaryResourceName = "PackageCommandUsageSummary",
UsageDescriptionResourceName = "PackageCommandUsageDescription", UsageExampleResourceName = "PackCommandUsageExamples")]
public class PackCommand : Command
{
internal static readonly string SymbolsExtension = ".symbols" + Constants.PackageExtension;
private static readonly string[] _defaultExcludes = new[] {
// Exclude previous package files
@"**\*" + Constants.PackageExtension,
// Exclude all files and directories that begin with "."
@"**\\.**", ".**"
};
// Target file paths to exclude when building the lib package for symbol server scenario
private static readonly string[] _libPackageExcludes = new[] {
@"**\*.pdb",
@"src\**\*"
};
// Target file paths to exclude when building the symbols package for symbol server scenario
private static readonly string[] _symbolPackageExcludes = new[] {
@"content\**\*",
@"tools\**\*.ps1"
};
private readonly HashSet<string> _excludes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, string> _properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private static readonly HashSet<string> _allowedExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
Constants.ManifestExtension,
".csproj",
".vbproj",
".fsproj",
".nproj"
};
[Option(typeof(NuGetResources), "PackageCommandOutputDirDescription")]
public string OutputDirectory { get; set; }
[Option(typeof(NuGetResources), "PackageCommandBasePathDescription")]
public string BasePath { get; set; }
[Option(typeof(NuGetResources), "PackageCommandVerboseDescription")]
public bool Verbose { get; set; }
[Option(typeof(NuGetResources), "PackageCommandVersionDescription")]
public string Version { get; set; }
[Option(typeof(NuGetResources), "PackageCommandExcludeDescription")]
public ICollection<string> Exclude
{
get { return _excludes; }
}
[Option(typeof(NuGetResources), "PackageCommandSymbolsDescription")]
public bool Symbols { get; set; }
[Option(typeof(NuGetResources), "PackageCommandToolDescription")]
public bool Tool { get; set; }
[Option(typeof(NuGetResources), "PackageCommandBuildDescription")]
public bool Build { get; set; }
[Option(typeof(NuGetResources), "PackageCommandNoDefaultExcludes")]
public bool NoDefaultExcludes { get; set; }
[Option(typeof(NuGetResources), "PackageCommandNoRunAnalysis")]
public bool NoPackageAnalysis { get; set; }
[Option(typeof(NuGetResources), "PackageCommandPropertiesDescription")]
public Dictionary<string, string> Properties
{
get
{
return _properties;
}
}
[ImportMany]
public IEnumerable<IPackageRule> Rules { get; set; }
public override void ExecuteCommand()
{
// Get the input file
string path = GetInputFile();
Console.WriteLine(NuGetResources.PackageCommandAttemptingToBuildPackage, Path.GetFileName(path));
IPackage package = BuildPackage(path);
if (package != null && !NoPackageAnalysis)
{
AnalyzePackage(package);
}
}
private IPackage BuildPackage(string path, PackageBuilder builder, string outputPath = null)
{
if (!String.IsNullOrEmpty(Version))
{
builder.Version = new SemanticVersion(Version);
}
outputPath = outputPath ?? GetOutputPath(builder);
// If the BasePath is not specified, use the directory of the input file (nuspec / proj) file
BasePath = String.IsNullOrEmpty(BasePath) ? Path.GetDirectoryName(Path.GetFullPath(path)) : BasePath;
ExcludeFiles(builder.Files);
// Track if the package file was already present on disk
bool isExistingPackage = File.Exists(outputPath);
try
{
using (Stream stream = File.Create(outputPath))
{
builder.Save(stream);
}
}
catch
{
if (!isExistingPackage && File.Exists(outputPath))
{
File.Delete(outputPath);
}
throw;
}
if (Verbose)
{
PrintVerbose(outputPath);
}
Console.WriteLine(NuGetResources.PackageCommandSuccess, outputPath);
return new ZipPackage(outputPath);
}
private void PrintVerbose(string outputPath)
{
Console.WriteLine();
var package = new ZipPackage(outputPath);
Console.WriteLine("Id: {0}", package.Id);
Console.WriteLine("Version: {0}", package.Version);
Console.WriteLine("Authors: {0}", String.Join(", ", package.Authors));
Console.WriteLine("Description: {0}", package.Description);
if (package.LicenseUrl != null)
{
Console.WriteLine("License Url: {0}", package.LicenseUrl);
}
if (package.ProjectUrl != null)
{
Console.WriteLine("Project Url: {0}", package.ProjectUrl);
}
if (!String.IsNullOrEmpty(package.Tags))
{
Console.WriteLine("Tags: {0}", package.Tags.Trim());
}
if (package.Dependencies.Any())
{
Console.WriteLine("Dependencies: {0}", String.Join(", ", package.Dependencies.Select(d => d.ToString())));
}
else
{
Console.WriteLine("Dependencies: None");
}
Console.WriteLine();
foreach (var file in package.GetFiles().OrderBy(p => p.Path))
{
Console.WriteLine(NuGetResources.PackageCommandAddedFile, file.Path);
}
Console.WriteLine();
}
internal void ExcludeFiles(ICollection<IPackageFile> packageFiles)
{
// Always exclude the nuspec file
// Review: This exclusion should be done by the package builder because it knows which file would collide with the auto-generated
// manifest file.
var wildCards = _excludes.Concat(new[] { @"**\*" + Constants.ManifestExtension });
if (!NoDefaultExcludes)
{
// The user has not explicitly disabled default filtering.
wildCards = wildCards.Concat(_defaultExcludes);
}
PathResolver.FilterPackageFiles(packageFiles, ResolvePath, wildCards);
}
private string ResolvePath(IPackageFile packageFile)
{
var physicalPackageFile = packageFile as PhysicalPackageFile;
// For PhysicalPackageFiles, we want to filter by SourcePaths, the path on disk. The Path value maps to the TargetPath
if (physicalPackageFile == null)
{
return packageFile.Path;
}
var path = physicalPackageFile.SourcePath;
int index = path.IndexOf(BasePath, StringComparison.OrdinalIgnoreCase);
if (index != -1)
{
// Since wildcards are going to be relative to the base path, remove the BasePath portion of the file's source path.
// Also remove any leading path separator slashes
path = path.Substring(index + BasePath.Length).TrimStart(Path.DirectorySeparatorChar);
}
return path;
}
private string GetOutputPath(PackageBuilder builder, bool symbols = false)
{
string version = String.IsNullOrEmpty(Version) ? builder.Version.ToString() : Version;
// Output file is {id}.{version}
string outputFile = builder.Id + "." + version;
// If this is a source package then add .symbols.nupkg to the package file name
if (symbols)
{
outputFile += SymbolsExtension;
}
else
{
outputFile += Constants.PackageExtension;
}
string outputDirectory = OutputDirectory ?? Directory.GetCurrentDirectory();
return Path.Combine(outputDirectory, outputFile);
}
private IPackage BuildPackage(string path)
{
string extension = Path.GetExtension(path);
if (extension.Equals(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase))
{
return BuildFromNuspec(path);
}
else
{
return BuildFromProjectFile(path);
}
}
private IPackage BuildFromNuspec(string path)
{
PackageBuilder packageBuilder = CreatePackageBuilderFromNuspec(path);
if (Symbols)
{
// remove source related files when building the lib package
ExcludeFilesForLibPackage(packageBuilder.Files);
if (!packageBuilder.Files.Any())
{
throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageCommandNoFilesForLibPackage,
path, CommandLineConstants.NuGetDocs));
}
}
IPackage package = BuildPackage(path, packageBuilder);
if (Symbols)
{
BuildSymbolsPackage(path);
}
return package;
}
private void BuildSymbolsPackage(string path)
{
PackageBuilder symbolsBuilder = CreatePackageBuilderFromNuspec(path);
// remove unnecessary files when building the symbols package
ExcludeFilesForSymbolPackage(symbolsBuilder.Files);
if (!symbolsBuilder.Files.Any())
{
throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageCommandNoFilesForSymbolsPackage,
path, CommandLineConstants.NuGetDocs));
}
string outputPath = GetOutputPath(symbolsBuilder, symbols: true);
BuildPackage(path, symbolsBuilder, outputPath);
}
internal static void ExcludeFilesForLibPackage(ICollection<IPackageFile> files)
{
PathResolver.FilterPackageFiles(files, file => file.Path, _libPackageExcludes);
}
internal static void ExcludeFilesForSymbolPackage(ICollection<IPackageFile> files)
{
PathResolver.FilterPackageFiles(files, file => file.Path, _symbolPackageExcludes);
}
private PackageBuilder CreatePackageBuilderFromNuspec(string path)
{
// Set the version property if the flag is set
if (!String.IsNullOrEmpty(Version))
{
Properties["version"] = Version;
}
// Initialize the property provider based on what was passed in using the properties flag
var propertyProvider = new DictionaryPropertyProvider(Properties);
if (String.IsNullOrEmpty(BasePath))
{
return new PackageBuilder(path, propertyProvider);
}
return new PackageBuilder(path, BasePath, propertyProvider);
}
private IPackage BuildFromProjectFile(string path)
{
var factory = new ProjectFactory(path)
{
IsTool = Tool,
Logger = Console,
Build = Build,
};
// Add the additional Properties to the properties of the Project Factory
foreach (var property in Properties)
{
factory.Properties.Add(property.Key, property.Value);
}
// Create a builder for the main package as well as the sources/symbols package
PackageBuilder mainPackageBuilder = factory.CreateBuilder(BasePath);
// Build the main package
IPackage package = BuildPackage(path, mainPackageBuilder);
// If we're excluding symbols then do nothing else
if (!Symbols)
{
return package;
}
Console.WriteLine();
Console.WriteLine(NuGetResources.PackageCommandAttemptingToBuildSymbolsPackage, Path.GetFileName(path));
factory.IncludeSymbols = true;
PackageBuilder symbolsBuilder = factory.CreateBuilder(BasePath);
symbolsBuilder.Version = mainPackageBuilder.Version;
// Get the file name for the sources package and build it
string outputPath = GetOutputPath(symbolsBuilder, symbols: true);
BuildPackage(path, symbolsBuilder, outputPath);
// this is the real package, not the symbol package
return package;
}
internal void AnalyzePackage(IPackage package)
{
IEnumerable<IPackageRule> packageRules = Rules;
if (!String.IsNullOrEmpty(package.Version.SpecialVersion))
{
// If a package contains a special token, we'll warn users if it does not strictly follow semver guidelines.
packageRules = packageRules.Concat(new[] { new StrictSemanticVersionValidationRule() });
}
IList<PackageIssue> issues = package.Validate(packageRules).OrderBy(p => p.Title, StringComparer.CurrentCulture).ToList();
if (issues.Count > 0)
{
Console.WriteLine();
Console.WriteWarning(NuGetResources.PackageCommandPackageIssueSummary, issues.Count, package.Id);
foreach (var issue in issues)
{
PrintPackageIssue(issue);
}
}
}
private void PrintPackageIssue(PackageIssue issue)
{
Console.WriteLine();
Console.WriteWarning(
prependWarningText: false,
value: NuGetResources.PackageCommandIssueTitle,
args: issue.Title);
Console.WriteWarning(
prependWarningText: false,
value: NuGetResources.PackageCommandIssueDescription,
args: issue.Description);
if (!String.IsNullOrEmpty(issue.Solution))
{
Console.WriteWarning(
prependWarningText: false,
value: NuGetResources.PackageCommandIssueSolution,
args: issue.Solution);
}
}
private string GetInputFile()
{
IEnumerable<string> files;
if (Arguments.Any())
{
files = Arguments;
}
else
{
files = Directory.GetFiles(Directory.GetCurrentDirectory());
}
return GetInputFile(files);
}
internal static string GetInputFile(IEnumerable<string> files)
{
var candidates = files.Where(file => _allowedExtensions.Contains(Path.GetExtension(file)))
.ToList();
switch (candidates.Count)
{
case 1:
return candidates.Single();
case 2:
// Remove all nuspec files
candidates.RemoveAll(file => Path.GetExtension(file).Equals(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase));
if (candidates.Count == 1)
{
return candidates.Single();
}
goto default;
default:
throw new CommandLineException(NuGetResources.PackageCommandSpecifyInputFileError);
}
}
private class DictionaryPropertyProvider : IPropertyProvider
{
private readonly IDictionary<string, string> _properties;
public DictionaryPropertyProvider(IDictionary<string, string> properties)
{
_properties = properties;
}
public dynamic GetPropertyValue(string propertyName)
{
string value;
if (_properties.TryGetValue(propertyName, out value))
{
return value;
}
return null;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using Dalssoft.DiagramNet;
namespace Dalssoft.TestForm
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private bool changeDocumentProp = true;
private System.Windows.Forms.ToolBar toolBar1;
private System.Windows.Forms.ToolBarButton btnSize;
private System.Windows.Forms.ToolBarButton btnAdd;
private System.Windows.Forms.ToolBarButton btnDelete;
private System.Windows.Forms.ToolBarButton btnConnect;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.ToolBarButton sep1;
private System.Windows.Forms.ToolBarButton btnSave;
private System.Windows.Forms.ToolBarButton btnOpen;
private System.Windows.Forms.ToolBarButton sep2;
private System.Windows.Forms.ToolBarButton btnUndo;
private System.Windows.Forms.ToolBarButton btnRedo;
private System.Windows.Forms.ToolBarButton sep3;
private System.Windows.Forms.ToolBarButton btnFront;
private System.Windows.Forms.ToolBarButton btnBack;
private System.Windows.Forms.ToolBarButton btnMoveUp;
private System.Windows.Forms.ToolBarButton btnMoveDown;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem11;
private System.Windows.Forms.MenuItem menuItem20;
private System.Windows.Forms.MenuItem menuItem26;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.PropertyGrid propertyGrid1;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.MenuItem mnuFile;
private System.Windows.Forms.MenuItem mnuOpen;
private System.Windows.Forms.MenuItem mnuSave;
private System.Windows.Forms.MenuItem mnuExit;
private System.Windows.Forms.MenuItem mnuEdit;
private System.Windows.Forms.MenuItem mnuRedo;
private System.Windows.Forms.MenuItem mnuAdd;
private System.Windows.Forms.MenuItem mnuRectangle;
private System.Windows.Forms.MenuItem mnuElipse;
private System.Windows.Forms.MenuItem mnuRectangleNode;
private System.Windows.Forms.MenuItem mnuElipseNode;
private System.Windows.Forms.MenuItem mnuDelete;
private System.Windows.Forms.MenuItem mnuConnect;
private System.Windows.Forms.MenuItem mnuOrder;
private System.Windows.Forms.MenuItem mnuBringToFront;
private System.Windows.Forms.MenuItem mnuSendToBack;
private System.Windows.Forms.MenuItem mnuMoveUp;
private System.Windows.Forms.MenuItem mnuMoveDown;
private System.Windows.Forms.MenuItem mnuHelp;
private System.Windows.Forms.MenuItem mnuAbout;
private System.Windows.Forms.MenuItem mnuSize;
private System.Windows.Forms.MenuItem mnuTbRectangle;
private System.Windows.Forms.MenuItem mnuTbElipse;
private System.Windows.Forms.MenuItem mnuTbRectangleNode;
private System.Windows.Forms.MenuItem mnuTbElipseNode;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.MenuItem mnuUndo;
private System.Windows.Forms.ContextMenu contextMenu2;
private System.Windows.Forms.MenuItem mnuTbStraightLink;
private System.Windows.Forms.MenuItem mnuTbRightAngleLink;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem mnuCut;
private System.Windows.Forms.MenuItem mnuPaste;
private System.Windows.Forms.MenuItem mnuCopy;
private System.Windows.Forms.ToolBarButton sep4;
private System.Windows.Forms.ToolBarButton btnCut;
private System.Windows.Forms.ToolBarButton btnCopy;
private System.Windows.Forms.ToolBarButton btnPaste;
private System.Windows.Forms.ToolBarButton sep5;
private System.Windows.Forms.ToolBarButton btnZoom;
private System.Windows.Forms.ContextMenu contextMenu_Zoom;
private System.Windows.Forms.MenuItem mnuZoom_10;
private System.Windows.Forms.MenuItem mnuZoom_25;
private System.Windows.Forms.MenuItem mnuZoom_50;
private System.Windows.Forms.MenuItem mnuZoom_75;
private System.Windows.Forms.MenuItem mnuZoom_100;
private System.Windows.Forms.MenuItem mnuZoom_150;
private System.Windows.Forms.MenuItem mnuZoom_200;
private System.Windows.Forms.Splitter splitter2;
private System.Windows.Forms.TextBox txtLog;
private System.Windows.Forms.MenuItem mnuShowDebugLog;
private System.Windows.Forms.MenuItem menuItem1;
private Designer designer1;
private System.Windows.Forms.MenuItem TbCommentBox;
private System.ComponentModel.IContainer components;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.toolBar1 = new System.Windows.Forms.ToolBar();
this.btnOpen = new System.Windows.Forms.ToolBarButton();
this.btnSave = new System.Windows.Forms.ToolBarButton();
this.sep1 = new System.Windows.Forms.ToolBarButton();
this.btnCut = new System.Windows.Forms.ToolBarButton();
this.btnCopy = new System.Windows.Forms.ToolBarButton();
this.btnPaste = new System.Windows.Forms.ToolBarButton();
this.btnDelete = new System.Windows.Forms.ToolBarButton();
this.sep4 = new System.Windows.Forms.ToolBarButton();
this.btnSize = new System.Windows.Forms.ToolBarButton();
this.btnAdd = new System.Windows.Forms.ToolBarButton();
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.mnuTbRectangle = new System.Windows.Forms.MenuItem();
this.mnuTbElipse = new System.Windows.Forms.MenuItem();
this.mnuTbRectangleNode = new System.Windows.Forms.MenuItem();
this.mnuTbElipseNode = new System.Windows.Forms.MenuItem();
this.TbCommentBox = new System.Windows.Forms.MenuItem();
this.btnConnect = new System.Windows.Forms.ToolBarButton();
this.contextMenu2 = new System.Windows.Forms.ContextMenu();
this.mnuTbStraightLink = new System.Windows.Forms.MenuItem();
this.mnuTbRightAngleLink = new System.Windows.Forms.MenuItem();
this.sep2 = new System.Windows.Forms.ToolBarButton();
this.btnUndo = new System.Windows.Forms.ToolBarButton();
this.btnRedo = new System.Windows.Forms.ToolBarButton();
this.sep3 = new System.Windows.Forms.ToolBarButton();
this.btnZoom = new System.Windows.Forms.ToolBarButton();
this.contextMenu_Zoom = new System.Windows.Forms.ContextMenu();
this.mnuZoom_10 = new System.Windows.Forms.MenuItem();
this.mnuZoom_25 = new System.Windows.Forms.MenuItem();
this.mnuZoom_50 = new System.Windows.Forms.MenuItem();
this.mnuZoom_75 = new System.Windows.Forms.MenuItem();
this.mnuZoom_100 = new System.Windows.Forms.MenuItem();
this.mnuZoom_150 = new System.Windows.Forms.MenuItem();
this.mnuZoom_200 = new System.Windows.Forms.MenuItem();
this.sep5 = new System.Windows.Forms.ToolBarButton();
this.btnFront = new System.Windows.Forms.ToolBarButton();
this.btnBack = new System.Windows.Forms.ToolBarButton();
this.btnMoveUp = new System.Windows.Forms.ToolBarButton();
this.btnMoveDown = new System.Windows.Forms.ToolBarButton();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
this.mnuFile = new System.Windows.Forms.MenuItem();
this.mnuOpen = new System.Windows.Forms.MenuItem();
this.mnuSave = new System.Windows.Forms.MenuItem();
this.menuItem26 = new System.Windows.Forms.MenuItem();
this.mnuExit = new System.Windows.Forms.MenuItem();
this.mnuEdit = new System.Windows.Forms.MenuItem();
this.mnuUndo = new System.Windows.Forms.MenuItem();
this.mnuRedo = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.mnuCut = new System.Windows.Forms.MenuItem();
this.mnuCopy = new System.Windows.Forms.MenuItem();
this.mnuPaste = new System.Windows.Forms.MenuItem();
this.mnuDelete = new System.Windows.Forms.MenuItem();
this.menuItem11 = new System.Windows.Forms.MenuItem();
this.mnuSize = new System.Windows.Forms.MenuItem();
this.mnuAdd = new System.Windows.Forms.MenuItem();
this.mnuRectangle = new System.Windows.Forms.MenuItem();
this.mnuElipse = new System.Windows.Forms.MenuItem();
this.mnuRectangleNode = new System.Windows.Forms.MenuItem();
this.mnuElipseNode = new System.Windows.Forms.MenuItem();
this.mnuConnect = new System.Windows.Forms.MenuItem();
this.menuItem20 = new System.Windows.Forms.MenuItem();
this.mnuOrder = new System.Windows.Forms.MenuItem();
this.mnuBringToFront = new System.Windows.Forms.MenuItem();
this.mnuSendToBack = new System.Windows.Forms.MenuItem();
this.mnuMoveUp = new System.Windows.Forms.MenuItem();
this.mnuMoveDown = new System.Windows.Forms.MenuItem();
this.mnuHelp = new System.Windows.Forms.MenuItem();
this.mnuShowDebugLog = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.mnuAbout = new System.Windows.Forms.MenuItem();
this.panel1 = new System.Windows.Forms.Panel();
this.designer1 = new Dalssoft.DiagramNet.Designer();
this.splitter2 = new System.Windows.Forms.Splitter();
this.txtLog = new System.Windows.Forms.TextBox();
this.splitter1 = new System.Windows.Forms.Splitter();
this.propertyGrid1 = new System.Windows.Forms.PropertyGrid();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// toolBar1
//
this.toolBar1.AllowDrop = true;
this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.btnOpen,
this.btnSave,
this.sep1,
this.btnCut,
this.btnCopy,
this.btnPaste,
this.btnDelete,
this.sep4,
this.btnSize,
this.btnAdd,
this.btnConnect,
this.sep2,
this.btnUndo,
this.btnRedo,
this.sep3,
this.btnZoom,
this.sep5,
this.btnFront,
this.btnBack,
this.btnMoveUp,
this.btnMoveDown});
this.toolBar1.Divider = false;
this.toolBar1.DropDownArrows = true;
this.toolBar1.ImageList = this.imageList1;
this.toolBar1.Location = new System.Drawing.Point(0, 0);
this.toolBar1.Name = "toolBar1";
this.toolBar1.ShowToolTips = true;
this.toolBar1.Size = new System.Drawing.Size(696, 26);
this.toolBar1.TabIndex = 1;
this.toolBar1.Wrappable = false;
this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
//
// btnOpen
//
this.btnOpen.ImageIndex = 6;
this.btnOpen.Name = "btnOpen";
this.btnOpen.Tag = "Open";
this.btnOpen.ToolTipText = "Open";
//
// btnSave
//
this.btnSave.ImageIndex = 5;
this.btnSave.Name = "btnSave";
this.btnSave.Tag = "Save";
this.btnSave.ToolTipText = "Save";
//
// sep1
//
this.sep1.Name = "sep1";
this.sep1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// btnCut
//
this.btnCut.ImageIndex = 13;
this.btnCut.Name = "btnCut";
this.btnCut.Tag = "Cut";
this.btnCut.ToolTipText = "Cut";
//
// btnCopy
//
this.btnCopy.ImageIndex = 14;
this.btnCopy.Name = "btnCopy";
this.btnCopy.Tag = "Copy";
this.btnCopy.ToolTipText = "Copy";
//
// btnPaste
//
this.btnPaste.ImageIndex = 15;
this.btnPaste.Name = "btnPaste";
this.btnPaste.Tag = "Paste";
this.btnPaste.ToolTipText = "Paste";
//
// btnDelete
//
this.btnDelete.ImageIndex = 2;
this.btnDelete.Name = "btnDelete";
this.btnDelete.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;
this.btnDelete.Tag = "Delete";
this.btnDelete.ToolTipText = "Delete";
//
// sep4
//
this.sep4.Name = "sep4";
this.sep4.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// btnSize
//
this.btnSize.ImageIndex = 0;
this.btnSize.Name = "btnSize";
this.btnSize.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;
this.btnSize.Tag = "Size";
this.btnSize.ToolTipText = "Size";
//
// btnAdd
//
this.btnAdd.DropDownMenu = this.contextMenu1;
this.btnAdd.ImageIndex = 1;
this.btnAdd.Name = "btnAdd";
this.btnAdd.Style = System.Windows.Forms.ToolBarButtonStyle.DropDownButton;
this.btnAdd.Tag = "Add";
this.btnAdd.ToolTipText = "Add";
//
// contextMenu1
//
this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuTbRectangle,
this.mnuTbElipse,
this.mnuTbRectangleNode,
this.mnuTbElipseNode,
this.TbCommentBox});
//
// mnuTbRectangle
//
this.mnuTbRectangle.Index = 0;
this.mnuTbRectangle.Text = "&Rectangle";
this.mnuTbRectangle.Click += new System.EventHandler(this.mnuTbRectangle_Click);
//
// mnuTbElipse
//
this.mnuTbElipse.Index = 1;
this.mnuTbElipse.Text = "&Elipse";
this.mnuTbElipse.Click += new System.EventHandler(this.mnuTbElipse_Click);
//
// mnuTbRectangleNode
//
this.mnuTbRectangleNode.Index = 2;
this.mnuTbRectangleNode.Text = "&Node Rectangle";
this.mnuTbRectangleNode.Click += new System.EventHandler(this.mnuTbRectangleNode_Click);
//
// mnuTbElipseNode
//
this.mnuTbElipseNode.Index = 3;
this.mnuTbElipseNode.Text = "N&ode Elipse";
this.mnuTbElipseNode.Click += new System.EventHandler(this.mnuTbElipseNode_Click);
//
// TbCommentBox
//
this.TbCommentBox.Index = 4;
this.TbCommentBox.Text = "Comment Box";
this.TbCommentBox.Click += new System.EventHandler(this.TbCommentBox_Click);
//
// btnConnect
//
this.btnConnect.DropDownMenu = this.contextMenu2;
this.btnConnect.ImageIndex = 3;
this.btnConnect.Name = "btnConnect";
this.btnConnect.Style = System.Windows.Forms.ToolBarButtonStyle.DropDownButton;
this.btnConnect.Tag = "Connect";
this.btnConnect.ToolTipText = "Connect";
//
// contextMenu2
//
this.contextMenu2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuTbStraightLink,
this.mnuTbRightAngleLink});
//
// mnuTbStraightLink
//
this.mnuTbStraightLink.Index = 0;
this.mnuTbStraightLink.Text = "Straight Link";
this.mnuTbStraightLink.Click += new System.EventHandler(this.mnuTbStraightLink_Click);
//
// mnuTbRightAngleLink
//
this.mnuTbRightAngleLink.Index = 1;
this.mnuTbRightAngleLink.Text = "Right Angle Link";
this.mnuTbRightAngleLink.Click += new System.EventHandler(this.mnuTbRightAngleLink_Click);
//
// sep2
//
this.sep2.Name = "sep2";
this.sep2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// btnUndo
//
this.btnUndo.ImageIndex = 7;
this.btnUndo.Name = "btnUndo";
this.btnUndo.Tag = "Undo";
this.btnUndo.ToolTipText = "Undo";
//
// btnRedo
//
this.btnRedo.ImageIndex = 8;
this.btnRedo.Name = "btnRedo";
this.btnRedo.Tag = "Redo";
this.btnRedo.ToolTipText = "Redo";
//
// sep3
//
this.sep3.Name = "sep3";
this.sep3.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// btnZoom
//
this.btnZoom.DropDownMenu = this.contextMenu_Zoom;
this.btnZoom.ImageIndex = 16;
this.btnZoom.Name = "btnZoom";
this.btnZoom.Style = System.Windows.Forms.ToolBarButtonStyle.DropDownButton;
this.btnZoom.Tag = "Zoom";
//
// contextMenu_Zoom
//
this.contextMenu_Zoom.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuZoom_10,
this.mnuZoom_25,
this.mnuZoom_50,
this.mnuZoom_75,
this.mnuZoom_100,
this.mnuZoom_150,
this.mnuZoom_200});
//
// mnuZoom_10
//
this.mnuZoom_10.Index = 0;
this.mnuZoom_10.Text = "10%";
this.mnuZoom_10.Click += new System.EventHandler(this.mnuZoom_10_Click);
//
// mnuZoom_25
//
this.mnuZoom_25.Index = 1;
this.mnuZoom_25.Text = "25%";
this.mnuZoom_25.Click += new System.EventHandler(this.mnuZoom_25_Click);
//
// mnuZoom_50
//
this.mnuZoom_50.Index = 2;
this.mnuZoom_50.Text = "50%";
this.mnuZoom_50.Click += new System.EventHandler(this.mnuZoom_50_Click);
//
// mnuZoom_75
//
this.mnuZoom_75.Index = 3;
this.mnuZoom_75.Text = "75%";
this.mnuZoom_75.Click += new System.EventHandler(this.mnuZoom_75_Click);
//
// mnuZoom_100
//
this.mnuZoom_100.Index = 4;
this.mnuZoom_100.Text = "100%";
this.mnuZoom_100.Click += new System.EventHandler(this.mnuZoom_100_Click);
//
// mnuZoom_150
//
this.mnuZoom_150.Index = 5;
this.mnuZoom_150.Text = "150%";
this.mnuZoom_150.Click += new System.EventHandler(this.mnuZoom_150_Click);
//
// mnuZoom_200
//
this.mnuZoom_200.Index = 6;
this.mnuZoom_200.Text = "200%";
this.mnuZoom_200.Click += new System.EventHandler(this.mnuZoom_200_Click);
//
// sep5
//
this.sep5.Name = "sep5";
this.sep5.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// btnFront
//
this.btnFront.ImageIndex = 9;
this.btnFront.Name = "btnFront";
this.btnFront.Tag = "Front";
this.btnFront.ToolTipText = "Bring to Front";
//
// btnBack
//
this.btnBack.ImageIndex = 10;
this.btnBack.Name = "btnBack";
this.btnBack.Tag = "Back";
this.btnBack.ToolTipText = "Send to Back";
//
// btnMoveUp
//
this.btnMoveUp.ImageIndex = 11;
this.btnMoveUp.Name = "btnMoveUp";
this.btnMoveUp.Tag = "MoveUp";
this.btnMoveUp.ToolTipText = "Move Up";
//
// btnMoveDown
//
this.btnMoveDown.ImageIndex = 12;
this.btnMoveDown.Name = "btnMoveDown";
this.btnMoveDown.Tag = "MoveDown";
this.btnMoveDown.ToolTipText = "Move Down";
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Silver;
this.imageList1.Images.SetKeyName(0, "");
this.imageList1.Images.SetKeyName(1, "");
this.imageList1.Images.SetKeyName(2, "");
this.imageList1.Images.SetKeyName(3, "");
this.imageList1.Images.SetKeyName(4, "");
this.imageList1.Images.SetKeyName(5, "");
this.imageList1.Images.SetKeyName(6, "");
this.imageList1.Images.SetKeyName(7, "");
this.imageList1.Images.SetKeyName(8, "");
this.imageList1.Images.SetKeyName(9, "");
this.imageList1.Images.SetKeyName(10, "");
this.imageList1.Images.SetKeyName(11, "");
this.imageList1.Images.SetKeyName(12, "");
this.imageList1.Images.SetKeyName(13, "");
this.imageList1.Images.SetKeyName(14, "");
this.imageList1.Images.SetKeyName(15, "");
this.imageList1.Images.SetKeyName(16, "");
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuFile,
this.mnuEdit,
this.mnuHelp});
//
// mnuFile
//
this.mnuFile.Index = 0;
this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuOpen,
this.mnuSave,
this.menuItem26,
this.mnuExit});
this.mnuFile.Text = "&File";
//
// mnuOpen
//
this.mnuOpen.Index = 0;
this.mnuOpen.Text = "&Open";
this.mnuOpen.Click += new System.EventHandler(this.mnuOpen_Click);
//
// mnuSave
//
this.mnuSave.Index = 1;
this.mnuSave.Text = "&Save";
this.mnuSave.Click += new System.EventHandler(this.mnuSave_Click);
//
// menuItem26
//
this.menuItem26.Index = 2;
this.menuItem26.Text = "-";
//
// mnuExit
//
this.mnuExit.Index = 3;
this.mnuExit.Text = "&Exit";
this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click);
//
// mnuEdit
//
this.mnuEdit.Index = 1;
this.mnuEdit.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuUndo,
this.mnuRedo,
this.menuItem3,
this.mnuCut,
this.mnuCopy,
this.mnuPaste,
this.mnuDelete,
this.menuItem11,
this.mnuSize,
this.mnuAdd,
this.mnuConnect,
this.menuItem20,
this.mnuOrder});
this.mnuEdit.Text = "&Edit";
//
// mnuUndo
//
this.mnuUndo.Index = 0;
this.mnuUndo.Text = "&Undo";
this.mnuUndo.Click += new System.EventHandler(this.mnuUndo_Click);
//
// mnuRedo
//
this.mnuRedo.Index = 1;
this.mnuRedo.Text = "&Redo";
this.mnuRedo.Click += new System.EventHandler(this.mnuRedo_Click);
//
// menuItem3
//
this.menuItem3.Index = 2;
this.menuItem3.Text = "-";
//
// mnuCut
//
this.mnuCut.Index = 3;
this.mnuCut.Text = "Cu&t";
this.mnuCut.Click += new System.EventHandler(this.mnuCut_Click);
//
// mnuCopy
//
this.mnuCopy.Index = 4;
this.mnuCopy.Text = "Cop&y";
this.mnuCopy.Click += new System.EventHandler(this.mnuCopy_Click);
//
// mnuPaste
//
this.mnuPaste.Index = 5;
this.mnuPaste.Text = "Paste";
this.mnuPaste.Click += new System.EventHandler(this.mnuPaste_Click);
//
// mnuDelete
//
this.mnuDelete.Index = 6;
this.mnuDelete.Text = "&Delete";
this.mnuDelete.Click += new System.EventHandler(this.mnuDelete_Click);
//
// menuItem11
//
this.menuItem11.Index = 7;
this.menuItem11.Text = "-";
//
// mnuSize
//
this.mnuSize.Index = 8;
this.mnuSize.Text = "&Size";
this.mnuSize.Click += new System.EventHandler(this.mnuSize_Click);
//
// mnuAdd
//
this.mnuAdd.Index = 9;
this.mnuAdd.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuRectangle,
this.mnuElipse,
this.mnuRectangleNode,
this.mnuElipseNode});
this.mnuAdd.Text = "&Add";
//
// mnuRectangle
//
this.mnuRectangle.Index = 0;
this.mnuRectangle.Text = "&Rectangle";
this.mnuRectangle.Click += new System.EventHandler(this.mnuRectangle_Click);
//
// mnuElipse
//
this.mnuElipse.Index = 1;
this.mnuElipse.Text = "&Elipse";
this.mnuElipse.Click += new System.EventHandler(this.mnuElipse_Click);
//
// mnuRectangleNode
//
this.mnuRectangleNode.Index = 2;
this.mnuRectangleNode.Text = "&Node Rectangle";
this.mnuRectangleNode.Click += new System.EventHandler(this.mnuRectangleNode_Click);
//
// mnuElipseNode
//
this.mnuElipseNode.Index = 3;
this.mnuElipseNode.Text = "N&ode Elipse";
this.mnuElipseNode.Click += new System.EventHandler(this.mnuElipseNode_Click);
//
// mnuConnect
//
this.mnuConnect.Index = 10;
this.mnuConnect.Text = "&Connect";
this.mnuConnect.Click += new System.EventHandler(this.mnuConnect_Click);
//
// menuItem20
//
this.menuItem20.Index = 11;
this.menuItem20.Text = "-";
//
// mnuOrder
//
this.mnuOrder.Index = 12;
this.mnuOrder.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuBringToFront,
this.mnuSendToBack,
this.mnuMoveUp,
this.mnuMoveDown});
this.mnuOrder.Text = "&Order";
//
// mnuBringToFront
//
this.mnuBringToFront.Index = 0;
this.mnuBringToFront.Text = "&Bring to Front";
this.mnuBringToFront.Click += new System.EventHandler(this.mnuBringToFront_Click);
//
// mnuSendToBack
//
this.mnuSendToBack.Index = 1;
this.mnuSendToBack.Text = "Send to &Back";
this.mnuSendToBack.Click += new System.EventHandler(this.mnuSendToBack_Click);
//
// mnuMoveUp
//
this.mnuMoveUp.Index = 2;
this.mnuMoveUp.Text = "Move &Up";
this.mnuMoveUp.Click += new System.EventHandler(this.mnuMoveUp_Click);
//
// mnuMoveDown
//
this.mnuMoveDown.Index = 3;
this.mnuMoveDown.Text = "Move &Down";
this.mnuMoveDown.Click += new System.EventHandler(this.mnuMoveDown_Click);
//
// mnuHelp
//
this.mnuHelp.Index = 2;
this.mnuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuShowDebugLog,
this.menuItem1,
this.mnuAbout});
this.mnuHelp.Text = "&Help";
//
// mnuShowDebugLog
//
this.mnuShowDebugLog.Index = 0;
this.mnuShowDebugLog.Text = "&Show Debug Log...";
this.mnuShowDebugLog.Click += new System.EventHandler(this.mnuShowDebugLog_Click);
//
// menuItem1
//
this.menuItem1.Index = 1;
this.menuItem1.Text = "-";
//
// mnuAbout
//
this.mnuAbout.Index = 2;
this.mnuAbout.Text = "&About...";
this.mnuAbout.Click += new System.EventHandler(this.mnuAbout_Click);
//
// panel1
//
this.panel1.Controls.Add(this.designer1);
this.panel1.Controls.Add(this.splitter2);
this.panel1.Controls.Add(this.txtLog);
this.panel1.Controls.Add(this.splitter1);
this.panel1.Controls.Add(this.propertyGrid1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 26);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(696, 359);
this.panel1.TabIndex = 2;
//
// designer1
//
this.designer1.AutoScroll = true;
this.designer1.AutoScrollMinSize = new System.Drawing.Size(100, 100);
this.designer1.BackColor = System.Drawing.SystemColors.Window;
this.designer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.designer1.Location = new System.Drawing.Point(0, 0);
this.designer1.Name = "designer1";
this.designer1.Size = new System.Drawing.Size(468, 252);
this.designer1.TabIndex = 6;
this.designer1.ElementClick += new Dalssoft.DiagramNet.Designer.ElementEventHandler(this.designer1_ElementClick);
this.designer1.ElementMouseDown += new Dalssoft.DiagramNet.Designer.ElementMouseEventHandler(this.designer1_ElementMouseDown);
this.designer1.ElementMouseUp += new Dalssoft.DiagramNet.Designer.ElementMouseEventHandler(this.designer1_ElementMouseUp);
this.designer1.ElementMoving += new Dalssoft.DiagramNet.Designer.ElementEventHandler(this.designer1_ElementMoving);
this.designer1.ElementMoved += new Dalssoft.DiagramNet.Designer.ElementEventHandler(this.designer1_ElementMoved);
this.designer1.ElementResizing += new Dalssoft.DiagramNet.Designer.ElementEventHandler(this.designer1_ElementResizing);
this.designer1.ElementResized += new Dalssoft.DiagramNet.Designer.ElementEventHandler(this.designer1_ElementResized);
this.designer1.ElementConnecting += new Dalssoft.DiagramNet.Designer.ElementConnectEventHandler(this.designer1_ElementConnecting);
this.designer1.ElementConnected += new Dalssoft.DiagramNet.Designer.ElementConnectEventHandler(this.designer1_ElementConnected);
this.designer1.ElementSelection += new Dalssoft.DiagramNet.Designer.ElementSelectionEventHandler(this.designer1_ElementSelection);
this.designer1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.designer1_MouseUp);
//
// splitter2
//
this.splitter2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.splitter2.Location = new System.Drawing.Point(0, 252);
this.splitter2.Name = "splitter2";
this.splitter2.Size = new System.Drawing.Size(468, 3);
this.splitter2.TabIndex = 5;
this.splitter2.TabStop = false;
//
// txtLog
//
this.txtLog.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtLog.Dock = System.Windows.Forms.DockStyle.Bottom;
this.txtLog.Location = new System.Drawing.Point(0, 255);
this.txtLog.Multiline = true;
this.txtLog.Name = "txtLog";
this.txtLog.ReadOnly = true;
this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtLog.Size = new System.Drawing.Size(468, 104);
this.txtLog.TabIndex = 4;
this.txtLog.Text = "Log:";
this.txtLog.Visible = false;
//
// splitter1
//
this.splitter1.Dock = System.Windows.Forms.DockStyle.Right;
this.splitter1.Location = new System.Drawing.Point(468, 0);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(4, 359);
this.splitter1.TabIndex = 1;
this.splitter1.TabStop = false;
//
// propertyGrid1
//
this.propertyGrid1.Dock = System.Windows.Forms.DockStyle.Right;
this.propertyGrid1.LineColor = System.Drawing.SystemColors.ScrollBar;
this.propertyGrid1.Location = new System.Drawing.Point(472, 0);
this.propertyGrid1.Name = "propertyGrid1";
this.propertyGrid1.Size = new System.Drawing.Size(224, 359);
this.propertyGrid1.TabIndex = 0;
//
// openFileDialog1
//
this.openFileDialog1.DefaultExt = "*.dgn";
this.openFileDialog1.RestoreDirectory = true;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(696, 385);
this.Controls.Add(this.panel1);
this.Controls.Add(this.toolBar1);
this.Menu = this.mainMenu1;
this.Name = "Form1";
this.Text = "Diagram.NET Test Form";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.Form1_Load);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.DoEvents();
Application.Run(new Form1());
}
#region Functions
private void Edit_UpdateUndoRedoEnable()
{
mnuUndo.Enabled = designer1.CanUndo;
btnUndo.Enabled = designer1.CanUndo;
mnuRedo.Enabled = designer1.CanRedo;
btnRedo.Enabled = designer1.CanRedo;
}
private void Edit_Undo()
{
if (designer1.CanUndo)
designer1.Undo();
Edit_UpdateUndoRedoEnable();
}
private void Edit_Redo()
{
if (designer1.CanRedo)
designer1.Redo();
Edit_UpdateUndoRedoEnable();
}
private void Action_None()
{
mnuSize.Checked = false;
mnuAdd.Checked = false;
mnuDelete.Checked = false;
mnuConnect.Checked = false;
btnSize.Pushed = false;
btnAdd.Pushed = false;
btnDelete.Pushed = false;
btnConnect.Pushed = false;
mnuRectangle.Checked = false;
mnuTbRectangle.Checked = false;
mnuElipse.Checked = false;
mnuTbElipse.Checked = false;
mnuRectangleNode.Checked = false;
mnuTbRectangleNode.Checked = false;
mnuElipseNode.Checked = false;
mnuTbElipseNode.Checked = false;
}
private void Action_Size()
{
Action_None();
mnuSize.Checked = true;
btnSize.Pushed = true;
if (changeDocumentProp)
designer1.Document.Action = DesignerAction.Select;
}
private void Action_Add(ElementType e)
{
Action_None();
btnAdd.Pushed = true;
switch(e)
{
case ElementType.Rectangle:
mnuRectangle.Checked = true;
mnuTbRectangle.Checked = true;
break;
case ElementType.Elipse:
mnuElipse.Checked = true;
mnuTbElipse.Checked = true;
break;
case ElementType.RectangleNode:
mnuRectangleNode.Checked = true;
mnuTbRectangleNode.Checked = true;
break;
case ElementType.ElipseNode:
mnuElipseNode.Checked = true;
mnuTbElipseNode.Checked = true;
break;
}
if (changeDocumentProp)
{
designer1.Document.Action = DesignerAction.Add;
designer1.Document.ElementType = e;
}
}
private void Action_Delete()
{
Action_None();
mnuDelete.Checked = true;
btnDelete.Pushed = true;
if (changeDocumentProp)
designer1.Document.DeleteSelectedElements();
Action_None();
}
private void Action_Connect()
{
Action_None();
mnuConnect.Checked = true;
btnConnect.Pushed = true;
if (changeDocumentProp)
designer1.Document.Action = DesignerAction.Connect;
}
private void Action_Connector(LinkType lt)
{
Action_None();
switch(lt)
{
case LinkType.Straight:
mnuTbStraightLink.Checked = true;
mnuTbRightAngleLink.Checked = false;
break;
case LinkType.RightAngle:
mnuTbStraightLink.Checked = false;
mnuTbRightAngleLink.Checked = true;
break;
}
designer1.Document.LinkType = lt;
Action_Connect();
}
private void Action_Zoom(float zoom)
{
designer1.Document.Zoom = zoom;
}
private void File_Open()
{
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
designer1.Open(openFileDialog1.FileName);
}
}
private void File_Save()
{
if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
{
designer1.Save(saveFileDialog1.FileName);
}
}
private void Order_BringToFront()
{
if (designer1.Document.SelectedElements.Count == 1)
{
designer1.Document.BringToFrontElement(designer1.Document.SelectedElements[0]);
designer1.Refresh();
}
}
private void Order_SendToBack()
{
if (designer1.Document.SelectedElements.Count == 1)
{
designer1.Document.SendToBackElement(designer1.Document.SelectedElements[0]);
designer1.Refresh();
}
}
private void Order_MoveUp()
{
if (designer1.Document.SelectedElements.Count == 1)
{
designer1.Document.MoveUpElement(designer1.Document.SelectedElements[0]);
designer1.Refresh();
}
}
private void Order_MoveDown()
{
if (designer1.Document.SelectedElements.Count == 1)
{
designer1.Document.MoveDownElement(designer1.Document.SelectedElements[0]);
designer1.Refresh();
}
}
private void Clipboard_Cut()
{
designer1.Cut();
}
private void Clipboard_Copy()
{
designer1.Copy();
}
private void Clipboard_Paste()
{
designer1.Paste();
}
#endregion
#region Menu Events
private void mnuUndo_Click(object sender, System.EventArgs e)
{
Edit_Undo();
}
private void mnuRedo_Click(object sender, System.EventArgs e)
{
Edit_Redo();
}
private void mnuSize_Click(object sender, System.EventArgs e)
{
Action_Size();
}
private void mnuRectangle_Click(object sender, System.EventArgs e)
{
Action_Add(ElementType.Rectangle);
}
private void mnuElipse_Click(object sender, System.EventArgs e)
{
Action_Add(ElementType.Elipse);
}
private void mnuRectangleNode_Click(object sender, System.EventArgs e)
{
Action_Add(ElementType.RectangleNode);
}
private void mnuElipseNode_Click(object sender, System.EventArgs e)
{
Action_Add(ElementType.ElipseNode);
}
private void mnuDelete_Click(object sender, System.EventArgs e)
{
Action_Delete();
}
private void mnuCut_Click(object sender, System.EventArgs e)
{
Clipboard_Cut();
}
private void mnuCopy_Click(object sender, System.EventArgs e)
{
Clipboard_Copy();
}
private void mnuPaste_Click(object sender, System.EventArgs e)
{
Clipboard_Paste();
}
private void mnuConnect_Click(object sender, System.EventArgs e)
{
Action_Connect();
}
private void mnuBringToFront_Click(object sender, System.EventArgs e)
{
Order_BringToFront();
}
private void mnuSendToBack_Click(object sender, System.EventArgs e)
{
Order_SendToBack();
}
private void mnuMoveUp_Click(object sender, System.EventArgs e)
{
Order_MoveUp();
}
private void mnuMoveDown_Click(object sender, System.EventArgs e)
{
Order_MoveDown();
}
private void mnuOpen_Click(object sender, System.EventArgs e)
{
File_Open();
}
private void mnuSave_Click(object sender, System.EventArgs e)
{
File_Save();
}
private void mnuExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void mnuAbout_Click(object sender, System.EventArgs e)
{
About about = new About();
about.ShowDialog(this);
}
#endregion
#region Toolbar Events
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
string btn = (string) e.Button.Tag;
if (btn == "Open") File_Open();
if (btn == "Save") File_Save();
if (btn == "Size") Action_Size();
//if (btn == "Add")
if (btn == "Delete") Action_Delete();
if (btn == "Connect") Action_Connect();
if (btn == "Undo") Edit_Undo();
if (btn == "Redo") Edit_Redo();
if (btn == "Front") Order_BringToFront();
if (btn == "Back") Order_SendToBack();
if (btn == "MoveUp") Order_MoveUp();
if (btn == "MoveDown") Order_MoveDown();
if (btn == "Cut") Clipboard_Cut();
if (btn == "Copy") Clipboard_Copy();
if (btn == "Paste") Clipboard_Paste();
}
private void mnuTbRectangle_Click(object sender, System.EventArgs e)
{
Action_Add(ElementType.Rectangle);
}
private void mnuTbElipse_Click(object sender, System.EventArgs e)
{
Action_Add(ElementType.Elipse);
}
private void mnuTbRectangleNode_Click(object sender, System.EventArgs e)
{
Action_Add(ElementType.RectangleNode);
}
private void mnuTbElipseNode_Click(object sender, System.EventArgs e)
{
Action_Add(ElementType.ElipseNode);
}
private void TbCommentBox_Click(object sender, System.EventArgs e)
{
Action_Add(ElementType.CommentBox);
}
private void mnuTbStraightLink_Click(object sender, System.EventArgs e)
{
Action_Connector(LinkType.Straight);
}
private void mnuTbRightAngleLink_Click(object sender, System.EventArgs e)
{
Action_Connector(LinkType.RightAngle);
}
#endregion
private void Form1_Load(object sender, System.EventArgs e)
{
Edit_UpdateUndoRedoEnable();
//Events
designer1.Document.PropertyChanged+=new EventHandler(Document_PropertyChanged);
}
private void Document_PropertyChanged(object sender, EventArgs e)
{
changeDocumentProp = false;
Action_None();
switch(designer1.Document.Action)
{
case DesignerAction.Select:
Action_Size();
break;
case DesignerAction.Delete:
Action_Delete();
break;
case DesignerAction.Connect:
Action_Connect();
break;
case DesignerAction.Add:
Action_Add(designer1.Document.ElementType);
break;
}
Edit_UpdateUndoRedoEnable();
changeDocumentProp = true;
}
private void mnuZoom_10_Click(object sender, System.EventArgs e)
{
Action_Zoom(0.1f);
}
private void mnuZoom_25_Click(object sender, System.EventArgs e)
{
Action_Zoom(0.25f);
}
private void mnuZoom_50_Click(object sender, System.EventArgs e)
{
Action_Zoom(0.5f);
}
private void mnuZoom_75_Click(object sender, System.EventArgs e)
{
Action_Zoom(0.75f);
}
private void mnuZoom_100_Click(object sender, System.EventArgs e)
{
Action_Zoom(1f);
}
private void mnuZoom_150_Click(object sender, System.EventArgs e)
{
Action_Zoom(1.5f);
}
private void mnuZoom_200_Click(object sender, System.EventArgs e)
{
Action_Zoom(2.0f);
}
private void mnuShowDebugLog_Click(object sender, System.EventArgs e)
{
mnuShowDebugLog.Checked = !mnuShowDebugLog.Checked;
txtLog.Visible = mnuShowDebugLog.Checked;
}
#region Events Handling
private void designer1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
AppendLog("designer1_MouseUp: {0}", e.ToString());
propertyGrid1.SelectedObject = null;
if (designer1.Document.SelectedElements.Count == 1)
{
propertyGrid1.SelectedObject = designer1.Document.SelectedElements[0];
}
else if (designer1.Document.SelectedElements.Count > 1)
{
propertyGrid1.SelectedObjects = designer1.Document.SelectedElements.GetArray();
}
else if (designer1.Document.SelectedElements.Count == 0)
{
propertyGrid1.SelectedObject = designer1.Document;
}
}
private void designer1_ElementClick(object sender, ElementEventArgs e)
{
AppendLog("designer1_ElementClick: {0}", e.ToString());
}
private void designer1_ElementMouseDown(object sender, ElementMouseEventArgs e)
{
AppendLog("designer1_ElementMouseDown: {0}", e.ToString());
}
private void designer1_ElementMouseUp(object sender, ElementMouseEventArgs e)
{
AppendLog("designer1_ElementMouseUp: {0}", e.ToString());
}
private void designer1_ElementMoved(object sender, ElementEventArgs e)
{
AppendLog("designer1_ElementMoved: {0}", e.ToString());
}
private void designer1_ElementMoving(object sender, ElementEventArgs e)
{
AppendLog("designer1_ElementMoving: {0}", e.ToString());
}
private void designer1_ElementResized(object sender, ElementEventArgs e)
{
AppendLog("designer1_ElementResized: {0}", e.ToString());
}
private void designer1_ElementResizing(object sender, ElementEventArgs e)
{
AppendLog("designer1_ElementResizing: {0}", e.ToString());
}
private void designer1_ElementConnected(object sender, ElementConnectEventArgs e)
{
AppendLog("designer1_ElementConnected: {0}", e.ToString());
}
private void designer1_ElementConnecting(object sender, ElementConnectEventArgs e)
{
AppendLog("designer1_ElementConnecting: {0}", e.ToString());
}
private void designer1_ElementSelection(object sender, ElementSelectionEventArgs e)
{
AppendLog("designer1_ElementSelection: {0}", e.ToString());
}
#endregion
private void AppendLog(string log)
{
AppendLog(log, "");
}
private void AppendLog(string log, params object[] args)
{
if (mnuShowDebugLog.Checked)
txtLog.AppendText(String.Format(log, args) + "\r\n");
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
internal unsafe sealed class RuntimePropertyInfo : PropertyInfo
{
#region Private Data Members
private int m_token;
private string m_name;
private void* m_utf8name;
private PropertyAttributes m_flags;
private RuntimeTypeCache m_reflectedTypeCache;
private RuntimeMethodInfo m_getterMethod;
private RuntimeMethodInfo m_setterMethod;
private MethodInfo[] m_otherMethod;
private RuntimeType m_declaringType;
private BindingFlags m_bindingFlags;
private Signature m_signature;
private ParameterInfo[] m_parameters;
#endregion
#region Constructor
internal RuntimePropertyInfo(
int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
{
Contract.Requires(declaredType != null);
Contract.Requires(reflectedTypeCache != null);
Debug.Assert(!reflectedTypeCache.IsGlobal);
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
m_token = tkProperty;
m_reflectedTypeCache = reflectedTypeCache;
m_declaringType = declaredType;
ConstArray sig;
scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig);
RuntimeMethodInfo dummy;
Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(),
out dummy, out dummy, out dummy,
out m_getterMethod, out m_setterMethod, out m_otherMethod,
out isPrivate, out m_bindingFlags);
}
#endregion
#region Internal Members
internal override bool CacheEquals(object o)
{
RuntimePropertyInfo m = o as RuntimePropertyInfo;
if ((object)m == null)
return false;
return m.m_token == m_token &&
RuntimeTypeHandle.GetModule(m_declaringType).Equals(
RuntimeTypeHandle.GetModule(m.m_declaringType));
}
internal Signature Signature
{
get
{
if (m_signature == null)
{
PropertyAttributes flags;
ConstArray sig;
void* name;
GetRuntimeModule().MetadataImport.GetPropertyProps(
m_token, out name, out flags, out sig);
m_signature = new Signature(sig.Signature.ToPointer(), (int)sig.Length, m_declaringType);
}
return m_signature;
}
}
internal bool EqualsSig(RuntimePropertyInfo target)
{
//@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties.
// The comparison is done by name and by sig. The EqualsSig comparison is expensive
// but forutnetly it is only called when an inherited property is hidden by name or
// when an interfaces declare properies with the same signature.
// Note that we intentionally don't resolve generic arguments so that we don't treat
// signatures that only match in certain instantiations as duplicates. This has the
// down side of treating overriding and overriden properties as different properties
// in some cases. But PopulateProperties in rttype.cs should have taken care of that
// by comparing VTable slots.
//
// Class C1(Of T, Y)
// Property Prop1(ByVal t1 As T) As Integer
// Get
// ... ...
// End Get
// End Property
// Property Prop1(ByVal y1 As Y) As Integer
// Get
// ... ...
// End Get
// End Property
// End Class
//
Contract.Requires(Name.Equals(target.Name));
Contract.Requires(this != target);
Contract.Requires(this.ReflectedType == target.ReflectedType);
return Signature.CompareSig(this.Signature, target.Signature);
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
#endregion
#region Object Overrides
public override String ToString()
{
return FormatNameAndSig(false);
}
private string FormatNameAndSig(bool serialization)
{
StringBuilder sbName = new StringBuilder(PropertyType.FormatTypeName(serialization));
sbName.Append(" ");
sbName.Append(Name);
RuntimeType[] arguments = Signature.Arguments;
if (arguments.Length > 0)
{
sbName.Append(" [");
sbName.Append(MethodBase.ConstructParameters(arguments, Signature.CallingConvention, serialization));
sbName.Append("]");
}
return sbName.ToString();
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Property; } }
public override String Name
{
get
{
if (m_name == null)
m_name = new Utf8String(m_utf8name).ToString();
return m_name;
}
}
public override Type DeclaringType
{
get
{
return m_declaringType;
}
}
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimePropertyInfo>(other);
public override Type ReflectedType
{
get
{
return ReflectedTypeInternal;
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override int MetadataToken { get { return m_token; } }
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
#endregion
#region PropertyInfo Overrides
#region Non Dynamic
public override Type[] GetRequiredCustomModifiers()
{
return Signature.GetCustomModifiers(0, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return Signature.GetCustomModifiers(0, false);
}
internal object GetConstantValue(bool raw)
{
Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);
if (defaultValue == DBNull.Value)
// Arg_EnumLitValueNotFound -> "Literal value was not found."
throw new InvalidOperationException(SR.Arg_EnumLitValueNotFound);
return defaultValue;
}
public override object GetConstantValue() { return GetConstantValue(false); }
public override object GetRawConstantValue() { return GetConstantValue(true); }
public override MethodInfo[] GetAccessors(bool nonPublic)
{
List<MethodInfo> accessorList = new List<MethodInfo>();
if (Associates.IncludeAccessor(m_getterMethod, nonPublic))
accessorList.Add(m_getterMethod);
if (Associates.IncludeAccessor(m_setterMethod, nonPublic))
accessorList.Add(m_setterMethod);
if ((object)m_otherMethod != null)
{
for (int i = 0; i < m_otherMethod.Length; i++)
{
if (Associates.IncludeAccessor(m_otherMethod[i] as MethodInfo, nonPublic))
accessorList.Add(m_otherMethod[i]);
}
}
return accessorList.ToArray();
}
public override Type PropertyType
{
get { return Signature.ReturnType; }
}
public override MethodInfo GetGetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_getterMethod, nonPublic))
return null;
return m_getterMethod;
}
public override MethodInfo GetSetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_setterMethod, nonPublic))
return null;
return m_setterMethod;
}
public override ParameterInfo[] GetIndexParameters()
{
ParameterInfo[] indexParams = GetIndexParametersNoCopy();
int numParams = indexParams.Length;
if (numParams == 0)
return indexParams;
ParameterInfo[] ret = new ParameterInfo[numParams];
Array.Copy(indexParams, ret, numParams);
return ret;
}
internal ParameterInfo[] GetIndexParametersNoCopy()
{
// @History - Logic ported from RTM
// No need to lock because we don't guarantee the uniqueness of ParameterInfo objects
if (m_parameters == null)
{
int numParams = 0;
ParameterInfo[] methParams = null;
// First try to get the Get method.
MethodInfo m = GetGetMethod(true);
if (m != null)
{
// There is a Get method so use it.
methParams = m.GetParametersNoCopy();
numParams = methParams.Length;
}
else
{
// If there is no Get method then use the Set method.
m = GetSetMethod(true);
if (m != null)
{
methParams = m.GetParametersNoCopy();
numParams = methParams.Length - 1;
}
}
// Now copy over the parameter info's and change their
// owning member info to the current property info.
ParameterInfo[] propParams = new ParameterInfo[numParams];
for (int i = 0; i < numParams; i++)
propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams[i], this);
m_parameters = propParams;
}
return m_parameters;
}
public override PropertyAttributes Attributes
{
get
{
return m_flags;
}
}
public override bool CanRead
{
get
{
return m_getterMethod != null;
}
}
public override bool CanWrite
{
get
{
return m_setterMethod != null;
}
}
#endregion
#region Dynamic
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValue(Object obj, Object[] index)
{
return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
MethodInfo m = GetGetMethod(true);
if (m == null)
throw new ArgumentException(System.SR.Arg_GetMethNotFnd);
return m.Invoke(obj, invokeAttr, binder, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, Object[] index)
{
SetValue(obj,
value,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null,
index,
null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
MethodInfo m = GetSetMethod(true);
if (m == null)
throw new ArgumentException(System.SR.Arg_SetMethNotFnd);
Object[] args = null;
if (index != null)
{
args = new Object[index.Length + 1];
for (int i = 0; i < index.Length; i++)
args[i] = index[i];
args[index.Length] = value;
}
else
{
args = new Object[1];
args[0] = value;
}
m.Invoke(obj, invokeAttr, binder, args, culture);
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Caching;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using umbraco.BasePages;
using Umbraco.Core.Services;
using File = System.IO.File;
using User = umbraco.BusinessLogic.User;
namespace umbraco
{
//TODO: Make the User overloads obsolete, then publicize the IUser object
/// <summary>
/// The ui class handles the multilingual text in the umbraco back-end.
/// Provides access to language settings and language files used in the umbraco back-end.
/// </summary>
[Obsolete("Use the ILocalizedTextService instead which is on the ApplicationContext.Services.TextService")]
public class ui
{
private static readonly string UmbracoDefaultUiLanguage = GlobalSettings.DefaultUILanguage;
private static readonly string UmbracoPath = SystemDirectories.Umbraco;
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Get the current culture/language from the currently logged in IUser, the IUser object is available on most Umbraco base classes and on the UmbracoContext")]
public static string Culture(User u)
{
if (ApplicationContext.Current == null) return string.Empty;
var found = UserExtensions.GetUserCulture(u.Language, ApplicationContext.Current.Services.TextService);
return found == null ? string.Empty : found.Name;
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Get the current culture/language from the currently logged in IUser, the IUser object is available on most Umbraco base classes and on the UmbracoContext")]
internal static string Culture(IUser u)
{
if (ApplicationContext.Current == null) return string.Empty;
var found = u.GetUserCulture(ApplicationContext.Current.Services.TextService);
return found == null ? string.Empty : found.Name;
}
private static string GetLanguage()
{
var user = UmbracoEnsuredPage.CurrentUser;
return GetLanguage(user);
}
private static string GetLanguage(User u)
{
if (u != null)
{
return u.Language;
}
return GetLanguage("");
}
private static string GetLanguage(IUser u)
{
if (u != null)
{
return u.Language;
}
return GetLanguage("");
}
private static string GetLanguage(string userLanguage)
{
if (userLanguage.IsNullOrWhiteSpace() == false)
{
return userLanguage;
}
var language = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
if (string.IsNullOrEmpty(language))
language = UmbracoDefaultUiLanguage;
return language;
}
/// <summary>
/// Returns translated UI text with a specific key based on the specified user's language settings
/// </summary>
/// <param name="Key">The key.</param>
/// <param name="u">The user.</param>
/// <returns></returns>
public static string Text(string Key, User u)
{
if (ApplicationContext.Current == null) return "[" + Key + "]";
return ApplicationContext.Current.Services.TextService.Localize(Key, GetCultureFromUserLanguage(GetLanguage(u)));
}
internal static string Text(string key, IUser u)
{
if (ApplicationContext.Current == null) return "[" + key + "]";
return ApplicationContext.Current.Services.TextService.Localize(key, GetCultureFromUserLanguage(GetLanguage(u)));
}
/// <summary>
/// Returns translated UI text with a specific key based on the logged-in user's language settings
/// </summary>
/// <param name="Key">The key.</param>
/// <returns></returns>
public static string Text(string Key)
{
if (ApplicationContext.Current == null) return "[" + Key + "]";
return ApplicationContext.Current.Services.TextService.Localize(Key, GetCultureFromUserLanguage(GetLanguage()));
}
/// <summary>
/// Returns translated UI text with a specific key and area, based on the specified users language settings
/// </summary>
/// <param name="Area">The area.</param>
/// <param name="Key">The key.</param>
/// <param name="u">The user.</param>
/// <returns></returns>
public static string Text(string Area, string Key, User u)
{
if (ApplicationContext.Current == null) return "[" + Key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", Area, Key),
GetCultureFromUserLanguage(GetLanguage(u)));
}
public static string Text(string area, string key, IUser u)
{
if (ApplicationContext.Current == null) return "[" + key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", area, key),
GetCultureFromUserLanguage(GetLanguage(u)));
}
/// <summary>
/// Returns translated UI text with a specific key and area, based on the logged-in users language settings
/// </summary>
/// <param name="Area">The area.</param>
/// <param name="Key">The key.</param>
/// <returns></returns>
public static string Text(string Area, string Key)
{
if (ApplicationContext.Current == null) return "[" + Key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", Area, Key),
GetCultureFromUserLanguage(GetLanguage()));
}
/// <summary>
/// Returns translated UI text with a specific area and key. based on the specified users language settings and variables array passed to the method
/// </summary>
/// <param name="Area">The area.</param>
/// <param name="Key">The key.</param>
/// <param name="Variables">The variables array.</param>
/// <param name="u">The user.</param>
/// <returns></returns>
public static string Text(string Area, string Key, string[] Variables, User u)
{
if (ApplicationContext.Current == null) return "[" + Key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", Area, Key),
GetCultureFromUserLanguage(GetLanguage(u)),
ConvertToDictionaryVars(Variables));
}
internal static string Text(string area, string key, string[] variables)
{
if (ApplicationContext.Current == null) return "[" + key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", area, key),
GetCultureFromUserLanguage(GetLanguage()),
ConvertToDictionaryVars(variables));
}
internal static string Text(string area, string key, string[] variables, IUser u)
{
if (ApplicationContext.Current == null) return "[" + key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", area, key),
GetCultureFromUserLanguage(GetLanguage(u)),
ConvertToDictionaryVars(variables));
}
/// <summary>
/// Returns translated UI text with a specific key and area based on the specified users language settings and single variable passed to the method
/// </summary>
/// <param name="Area">The area.</param>
/// <param name="Key">The key.</param>
/// <param name="Variable">The variable.</param>
/// <param name="u">The u.</param>
/// <returns></returns>
public static string Text(string Area, string Key, string Variable, User u)
{
if (ApplicationContext.Current == null) return "[" + Key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", Area, Key),
GetCultureFromUserLanguage(GetLanguage(u)),
ConvertToDictionaryVars(new[] { Variable }));
}
internal static string Text(string area, string key, string variable)
{
if (ApplicationContext.Current == null) return "[" + key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", area, key),
GetCultureFromUserLanguage(GetLanguage()),
ConvertToDictionaryVars(new[] { variable }));
}
internal static string Text(string area, string key, string variable, IUser u)
{
if (ApplicationContext.Current == null) return "[" + key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", area, key),
GetCultureFromUserLanguage(GetLanguage(u)),
ConvertToDictionaryVars(new[] { variable }));
}
/// <summary>
/// Returns translated UI text with a specific key based on the logged-in user's language settings
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public static string GetText(string key)
{
return ApplicationContext.Current.Services.TextService.Localize(key, GetCultureFromUserLanguage(GetLanguage()));
}
/// <summary>
/// Returns translated UI text with a specific key and area based on the logged-in users language settings
/// </summary>
/// <param name="area">The area.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
public static string GetText(string area, string key)
{
if (ApplicationContext.Current == null) return "[" + key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", area, key),
GetCultureFromUserLanguage(GetLanguage()));
}
/// <summary>
/// Returns translated UI text with a specific key and area based on the logged-in users language settings and variables array send to the method.
/// </summary>
/// <param name="area">The area.</param>
/// <param name="key">The key.</param>
/// <param name="variables">The variables.</param>
/// <returns></returns>
public static string GetText(string area, string key, string[] variables)
{
if (ApplicationContext.Current == null) return "[" + key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", area, key),
GetCultureFromUserLanguage(GetLanguage()),
ConvertToDictionaryVars(variables));
}
/// <summary>
/// Returns translated UI text with a specific key and area matching the variable send to the method.
/// </summary>
/// <param name="area">The area.</param>
/// <param name="key">The key.</param>
/// <param name="variable">The variable.</param>
/// <returns></returns>
public static string GetText(string area, string key, string variable)
{
if (ApplicationContext.Current == null) return "[" + key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", area, key),
GetCultureFromUserLanguage(GetLanguage()),
ConvertToDictionaryVars(new[] { variable }));
}
/// <summary>
/// Returns translated UI text with a specific key, area and language matching the variables send to the method.
/// </summary>
/// <param name="area">The area (Optional)</param>
/// <param name="key">The key (Required)</param>
/// <param name="variables">The variables (Optional)</param>
/// <param name="language">The language (Optional)</param>
/// <returns></returns>
/// <remarks>This is the underlying call for all Text/GetText method calls</remarks>
public static string GetText(string area, string key, string[] variables, string language)
{
if (ApplicationContext.Current == null) return "[" + key + "]";
return ApplicationContext.Current.Services.TextService.Localize(
string.Format("{0}/{1}", area, key),
GetCultureFromUserLanguage(GetLanguage()),
ConvertToDictionaryVars(variables));
}
/// <summary>
/// Gets the language file as a xml document.
/// </summary>
/// <param name="language">The language.</param>
/// <returns></returns>
[Obsolete("This is no longer used and will be removed from the codebase in future versions, to get the contents of language text use ILocalizedTextService.GetAllStoredValues")]
public static XmlDocument getLanguageFile(string language)
{
var cacheKey = "uitext_" + language;
var file = IOHelper.MapPath(UmbracoPath + "/config/lang/" + language + ".xml");
if (File.Exists(file))
{
return ApplicationContext.Current.ApplicationCache.GetCacheItem(
cacheKey,
CacheItemPriority.Default,
new CacheDependency(IOHelper.MapPath(UmbracoPath + "/config/lang/" + language + ".xml")),
() =>
{
using (var langReader = new XmlTextReader(IOHelper.MapPath(UmbracoPath + "/config/lang/" + language + ".xml")))
{
try
{
var langFile = new XmlDocument();
langFile.Load(langReader);
return langFile;
}
catch (Exception e)
{
LogHelper.Error<ui>("Error reading umbraco language xml source (" + language + ")", e);
return null;
}
}
});
}
else
{
return null;
}
}
/// <summary>
/// Convert an array of strings to a dictionary of indicies -> values
/// </summary>
/// <param name="variables"></param>
/// <returns></returns>
internal static IDictionary<string, string> ConvertToDictionaryVars(string[] variables)
{
if (variables == null) return null;
if (variables.Any() == false) return null;
return variables.Select((s, i) => new {index = i.ToString(CultureInfo.InvariantCulture), value = s})
.ToDictionary(keyvals => keyvals.index, keyvals => keyvals.value);
}
private static CultureInfo GetCultureFromUserLanguage(string userLang)
{
return CultureInfo.GetCultureInfo(userLang.Replace("_", "-"));
}
}
}
| |
//
// NRefactoryExpressionEvaluator.cs
//
// Authors: Lluis Sanchez Gual <lluis@novell.com>
// Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2008 Novell, Inc (http://www.novell.com)
// Copyright (c) 2012 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Collections.Generic;
using Mono.Debugging.Client;
using ICSharpCode.NRefactory.CSharp;
namespace Mono.Debugging.Evaluation
{
public class NRefactoryExpressionEvaluator : ExpressionEvaluator
{
readonly Dictionary<string, ValueReference> userVariables = new Dictionary<string, ValueReference> ();
public override ValueReference Evaluate (EvaluationContext ctx, string expression, object expectedType)
{
expression = expression.Trim ();
if (expression.Length > 0 && expression[0] == '?')
expression = expression.Substring (1).TrimStart ();
if (expression.Length > 3 && expression.StartsWith ("var", StringComparison.Ordinal) && char.IsWhiteSpace (expression[3])) {
expression = expression.Substring (4).TrimStart ();
string variable = null;
for (int n = 0; n < expression.Length; n++) {
if (!char.IsLetterOrDigit (expression[n]) && expression[n] != '_') {
variable = expression.Substring (0, n);
if (!expression.Substring (n).TrimStart ().StartsWith ("=", StringComparison.Ordinal))
variable = null;
break;
}
if (n == expression.Length - 1) {
variable = expression;
expression = null;
break;
}
}
if (!string.IsNullOrEmpty (variable))
userVariables[variable] = new UserVariableReference (ctx, variable);
if (expression == null)
return null;
}
expression = ReplaceExceptionTag (expression, ctx.Options.CurrentExceptionTag);
var expr = new CSharpParser ().ParseExpression (expression);
if (expr == null)
throw new EvaluatorException ("Could not parse expression '{0}'", expression);
var evaluator = new NRefactoryExpressionEvaluatorVisitor (ctx, expression, expectedType, userVariables);
return expr.AcceptVisitor (evaluator);
}
public override string Resolve (DebuggerSession session, SourceLocation location, string exp)
{
return Resolve (session, location, exp, false);
}
string Resolve (DebuggerSession session, SourceLocation location, string expression, bool tryTypeOf)
{
expression = expression.Trim ();
if (expression.Length > 0 && expression[0] == '?')
return "?" + Resolve (session, location, expression.Substring (1).Trim ());
if (expression.Length > 3 && expression.StartsWith ("var", StringComparison.Ordinal) && char.IsWhiteSpace (expression[3]))
return "var " + Resolve (session, location, expression.Substring (4).Trim (' ', '\t'));
expression = ReplaceExceptionTag (expression, session.Options.EvaluationOptions.CurrentExceptionTag);
var expr = new CSharpParser ().ParseExpression (expression);
if (expr == null)
return expression;
var resolver = new NRefactoryExpressionResolverVisitor (session, location, expression);
expr.AcceptVisitor (resolver);
string resolved = resolver.GetResolvedExpression ();
if (resolved == expression && !tryTypeOf && (expr is BinaryOperatorExpression) && IsTypeName (expression)) {
// This is a hack to be able to parse expressions such as "List<string>". The NRefactory parser
// can parse a single type name, so a solution is to wrap it around a typeof(). We do it if
// the evaluation fails.
string res = Resolve (session, location, "typeof(" + expression + ")", true);
return res.Substring (7, res.Length - 8);
}
return resolved;
}
public override ValidationResult ValidateExpression (EvaluationContext ctx, string expression)
{
expression = expression.Trim ();
if (expression.Length > 0 && expression[0] == '?')
expression = expression.Substring (1).TrimStart ();
if (expression.Length > 3 && expression.StartsWith ("var", StringComparison.Ordinal) && char.IsWhiteSpace (expression[3]))
expression = expression.Substring (4).TrimStart ();
expression = ReplaceExceptionTag (expression, ctx.Options.CurrentExceptionTag);
// Required as a workaround for a bug in the parser (it won't parse simple expressions like numbers)
if (!expression.EndsWith (";", StringComparison.Ordinal))
expression += ";";
var parser = new CSharpParser ();
parser.ParseExpression (expression);
if (parser.HasErrors)
return new ValidationResult (false, parser.Errors.First ().Message);
return new ValidationResult (true, null);
}
string ReplaceExceptionTag (string exp, string tag)
{
// FIXME: Don't replace inside string literals
return exp.Replace (tag, "__EXCEPTION_OBJECT__");
}
bool IsTypeName (string name)
{
int pos = 0;
bool res = ParseTypeName (name + "$", ref pos);
return res && pos >= name.Length;
}
bool ParseTypeName (string name, ref int pos)
{
EatSpaces (name, ref pos);
if (!ParseName (name, ref pos))
return false;
EatSpaces (name, ref pos);
if (!ParseGenericArgs (name, ref pos))
return false;
EatSpaces (name, ref pos);
if (!ParseIndexer (name, ref pos))
return false;
EatSpaces (name, ref pos);
return true;
}
void EatSpaces (string name, ref int pos)
{
while (char.IsWhiteSpace (name[pos]))
pos++;
}
bool ParseName (string name, ref int pos)
{
if (name[0] == 'g' && pos < name.Length - 8 && name.Substring (pos, 8) == "global::")
pos += 8;
do {
int oldp = pos;
while (char.IsLetterOrDigit (name[pos]))
pos++;
if (oldp == pos)
return false;
if (name[pos] != '.')
return true;
pos++;
} while (true);
}
bool ParseGenericArgs (string name, ref int pos)
{
if (name [pos] != '<')
return true;
pos++;
EatSpaces (name, ref pos);
while (true) {
if (!ParseTypeName (name, ref pos))
return false;
EatSpaces (name, ref pos);
char c = name [pos++];
if (c == '>')
return true;
if (c == ',')
continue;
return false;
}
}
bool ParseIndexer (string name, ref int pos)
{
if (name [pos] != '[')
return true;
do {
pos++;
EatSpaces (name, ref pos);
} while (name [pos] == ',');
return name [pos++] == ']';
}
}
}
| |
// <copyright file="LUTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Single;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Factorization
{
/// <summary>
/// LU factorization tests for a dense matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class LUTests
{
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var factorLU = matrixI.LU();
// Check lower triangular part.
var matrixL = factorLU.L;
Assert.AreEqual(matrixI.RowCount, matrixL.RowCount);
Assert.AreEqual(matrixI.ColumnCount, matrixL.ColumnCount);
for (var i = 0; i < matrixL.RowCount; i++)
{
for (var j = 0; j < matrixL.ColumnCount; j++)
{
Assert.AreEqual(i == j ? 1.0 : 0.0, matrixL[i, j]);
}
}
// Check upper triangular part.
var matrixU = factorLU.U;
Assert.AreEqual(matrixI.RowCount, matrixU.RowCount);
Assert.AreEqual(matrixI.ColumnCount, matrixU.ColumnCount);
for (var i = 0; i < matrixU.RowCount; i++)
{
for (var j = 0; j < matrixU.ColumnCount; j++)
{
Assert.AreEqual(i == j ? 1.0 : 0.0, matrixU[i, j]);
}
}
}
/// <summary>
/// LU factorization fails with a non-square matrix.
/// </summary>
[Test]
public void LUFailsWithNonSquareMatrix()
{
var matrix = new DenseMatrix(3, 2);
Assert.That(() => matrix.LU(), Throws.ArgumentException);
}
/// <summary>
/// Identity determinant is one.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void IdentityDeterminantIsOne(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var lu = matrixI.LU();
Assert.AreEqual(1.0, lu.Determinant);
}
/// <summary>
/// Can factorize a random square matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanFactorizeRandomMatrix(int order)
{
var matrixX = Matrix<float>.Build.Random(order, order, 1);
var factorLU = matrixX.LU();
var matrixL = factorLU.L;
var matrixU = factorLU.U;
// Make sure the factors have the right dimensions.
Assert.AreEqual(order, matrixL.RowCount);
Assert.AreEqual(order, matrixL.ColumnCount);
Assert.AreEqual(order, matrixU.RowCount);
Assert.AreEqual(order, matrixU.ColumnCount);
// Make sure the L factor is lower triangular.
for (var i = 0; i < matrixL.RowCount; i++)
{
Assert.AreEqual(1.0, matrixL[i, i]);
for (var j = i + 1; j < matrixL.ColumnCount; j++)
{
Assert.AreEqual(0.0, matrixL[i, j]);
}
}
// Make sure the U factor is upper triangular.
for (var i = 0; i < matrixL.RowCount; i++)
{
for (var j = 0; j < i; j++)
{
Assert.AreEqual(0.0, matrixU[i, j]);
}
}
// Make sure the LU factor times it's transpose is the original matrix.
var matrixXfromLU = matrixL * matrixU;
var permutationInverse = factorLU.P.Inverse();
matrixXfromLU.PermuteRows(permutationInverse);
for (var i = 0; i < matrixXfromLU.RowCount; i++)
{
for (var j = 0; j < matrixXfromLU.ColumnCount; j++)
{
Assert.AreEqual(matrixX[i, j], matrixXfromLU[i, j], 1e-4);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<float>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var vectorb = Vector<float>.Build.Random(order, 1);
var resultx = factorLU.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = Matrix<float>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixB = Matrix<float>.Build.Random(order, order, 1);
var matrixX = factorLU.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int order)
{
var matrixA = Matrix<float>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var vectorb = Vector<float>.Build.Random(order, 1);
var vectorbCopy = vectorb.Clone();
var resultx = new DenseVector(order);
factorLU.Solve(vectorb, resultx);
Assert.AreEqual(vectorb.Count, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="order">Matrix row number.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order)
{
var matrixA = Matrix<float>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixB = Matrix<float>.Build.Random(order, order, 1);
var matrixBCopy = matrixB.Clone();
var matrixX = new DenseMatrix(order, order);
factorLU.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
/// <summary>
/// Can inverse a matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanInverse(int order)
{
var matrixA = Matrix<float>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixAInverse = factorLU.Inverse();
// The inverse dimension is equal A
Assert.AreEqual(matrixAInverse.RowCount, matrixAInverse.RowCount);
Assert.AreEqual(matrixAInverse.ColumnCount, matrixAInverse.ColumnCount);
var matrixIdentity = matrixA * matrixAInverse;
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Check if multiplication of A and AI produced identity matrix.
for (var i = 0; i < matrixIdentity.RowCount; i++)
{
Assert.AreEqual(matrixIdentity[i, i], 1.0, 1e-4);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// C# implementation of the proposed SHA-256 hash algorithm
//
namespace System.Security.Cryptography {
using System;
using System.Security;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public class SHA256Managed : SHA256
{
private byte[] _buffer;
private long _count; // Number of bytes in the hashed message
private UInt32[] _stateSHA256;
private UInt32[] _W;
//
// public constructors
//
public SHA256Managed()
{
#if FEATURE_CRYPTO
if (CryptoConfig.AllowOnlyFipsAlgorithms)
throw new InvalidOperationException(Environment.GetResourceString("Cryptography_NonCompliantFIPSAlgorithm"));
Contract.EndContractBlock();
#endif // FEATURE_CRYPTO
_stateSHA256 = new UInt32[8];
_buffer = new byte[64];
_W = new UInt32[64];
InitializeState();
}
//
// public methods
//
public override void Initialize() {
InitializeState();
// Zeroize potentially sensitive information.
Array.Clear(_buffer, 0, _buffer.Length);
Array.Clear(_W, 0, _W.Length);
}
protected override void HashCore(byte[] rgb, int ibStart, int cbSize) {
_HashData(rgb, ibStart, cbSize);
}
protected override byte[] HashFinal() {
return _EndHash();
}
//
// private methods
//
private void InitializeState() {
_count = 0;
_stateSHA256[0] = 0x6a09e667;
_stateSHA256[1] = 0xbb67ae85;
_stateSHA256[2] = 0x3c6ef372;
_stateSHA256[3] = 0xa54ff53a;
_stateSHA256[4] = 0x510e527f;
_stateSHA256[5] = 0x9b05688c;
_stateSHA256[6] = 0x1f83d9ab;
_stateSHA256[7] = 0x5be0cd19;
}
/* SHA256 block update operation. Continues an SHA message-digest
operation, processing another message block, and updating the
context.
*/
[System.Security.SecuritySafeCritical] // auto-generated
private unsafe void _HashData(byte[] partIn, int ibStart, int cbSize)
{
int bufferLen;
int partInLen = cbSize;
int partInBase = ibStart;
/* Compute length of buffer */
bufferLen = (int) (_count & 0x3f);
/* Update number of bytes */
_count += partInLen;
fixed (uint* stateSHA256 = _stateSHA256) {
fixed (byte* buffer = _buffer) {
fixed (uint* expandedBuffer = _W) {
if ((bufferLen > 0) && (bufferLen + partInLen >= 64)) {
Buffer.InternalBlockCopy(partIn, partInBase, _buffer, bufferLen, 64 - bufferLen);
partInBase += (64 - bufferLen);
partInLen -= (64 - bufferLen);
SHATransform(expandedBuffer, stateSHA256, buffer);
bufferLen = 0;
}
/* Copy input to temporary buffer and hash */
while (partInLen >= 64) {
Buffer.InternalBlockCopy(partIn, partInBase, _buffer, 0, 64);
partInBase += 64;
partInLen -= 64;
SHATransform(expandedBuffer, stateSHA256, buffer);
}
if (partInLen > 0) {
Buffer.InternalBlockCopy(partIn, partInBase, _buffer, bufferLen, partInLen);
}
}
}
}
}
/* SHA256 finalization. Ends an SHA256 message-digest operation, writing
the message digest.
*/
private byte[] _EndHash()
{
byte[] pad;
int padLen;
long bitCount;
byte[] hash = new byte[32]; // HashSizeValue = 256
/* Compute padding: 80 00 00 ... 00 00 <bit count>
*/
padLen = 64 - (int)(_count & 0x3f);
if (padLen <= 8)
padLen += 64;
pad = new byte[padLen];
pad[0] = 0x80;
// Convert count to bit count
bitCount = _count * 8;
pad[padLen-8] = (byte) ((bitCount >> 56) & 0xff);
pad[padLen-7] = (byte) ((bitCount >> 48) & 0xff);
pad[padLen-6] = (byte) ((bitCount >> 40) & 0xff);
pad[padLen-5] = (byte) ((bitCount >> 32) & 0xff);
pad[padLen-4] = (byte) ((bitCount >> 24) & 0xff);
pad[padLen-3] = (byte) ((bitCount >> 16) & 0xff);
pad[padLen-2] = (byte) ((bitCount >> 8) & 0xff);
pad[padLen-1] = (byte) ((bitCount >> 0) & 0xff);
/* Digest padding */
_HashData(pad, 0, pad.Length);
/* Store digest */
Utils.DWORDToBigEndian (hash, _stateSHA256, 8);
HashValue = hash;
return hash;
}
private readonly static UInt32[] _K = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
[System.Security.SecurityCritical] // auto-generated
private static unsafe void SHATransform (uint* expandedBuffer, uint* state, byte* block)
{
UInt32 a, b, c, d, e, f, h, g;
UInt32 aa, bb, cc, dd, ee, ff, hh, gg;
UInt32 T1;
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
f = state[5];
g = state[6];
h = state[7];
// fill in the first 16 bytes of W.
Utils.DWORDFromBigEndian(expandedBuffer, 16, block);
SHA256Expand(expandedBuffer);
/* Apply the SHA256 compression function */
// We are trying to be smart here and avoid as many copies as we can
// The perf gain with this method over the straightforward modify and shift
// forward is >= 20%, so it's worth the pain
for (int j=0; j<64; ) {
T1 = h + Sigma_1(e) + Ch(e,f,g) + _K[j] + expandedBuffer[j];
ee = d + T1;
aa = T1 + Sigma_0(a) + Maj(a,b,c);
j++;
T1 = g + Sigma_1(ee) + Ch(ee,e,f) + _K[j] + expandedBuffer[j];
ff = c + T1;
bb = T1 + Sigma_0(aa) + Maj(aa,a,b);
j++;
T1 = f + Sigma_1(ff) + Ch(ff,ee,e) + _K[j] + expandedBuffer[j];
gg = b + T1;
cc = T1 + Sigma_0(bb) + Maj(bb,aa,a);
j++;
T1 = e + Sigma_1(gg) + Ch(gg,ff,ee) + _K[j] + expandedBuffer[j];
hh = a + T1;
dd = T1 + Sigma_0(cc) + Maj(cc,bb,aa);
j++;
T1 = ee + Sigma_1(hh) + Ch(hh,gg,ff) + _K[j] + expandedBuffer[j];
h = aa + T1;
d = T1 + Sigma_0(dd) + Maj(dd,cc,bb);
j++;
T1 = ff + Sigma_1(h) + Ch(h,hh,gg) + _K[j] + expandedBuffer[j];
g = bb + T1;
c = T1 + Sigma_0(d) + Maj(d,dd,cc);
j++;
T1 = gg + Sigma_1(g) + Ch(g,h,hh) + _K[j] + expandedBuffer[j];
f = cc + T1;
b = T1 + Sigma_0(c) + Maj(c,d,dd);
j++;
T1 = hh + Sigma_1(f) + Ch(f,g,h) + _K[j] + expandedBuffer[j];
e = dd + T1;
a = T1 + Sigma_0(b) + Maj(b,c,d);
j++;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
}
private static UInt32 RotateRight(UInt32 x, int n) {
return (((x) >> (n)) | ((x) << (32-(n))));
}
private static UInt32 Ch(UInt32 x, UInt32 y, UInt32 z) {
return ((x & y) ^ ((x ^ 0xffffffff) & z));
}
private static UInt32 Maj(UInt32 x, UInt32 y, UInt32 z) {
return ((x & y) ^ (x & z) ^ (y & z));
}
private static UInt32 sigma_0(UInt32 x) {
return (RotateRight(x,7) ^ RotateRight(x,18) ^ (x >> 3));
}
private static UInt32 sigma_1(UInt32 x) {
return (RotateRight(x,17) ^ RotateRight(x,19) ^ (x >> 10));
}
private static UInt32 Sigma_0(UInt32 x) {
return (RotateRight(x,2) ^ RotateRight(x,13) ^ RotateRight(x,22));
}
private static UInt32 Sigma_1(UInt32 x) {
return (RotateRight(x,6) ^ RotateRight(x,11) ^ RotateRight(x,25));
}
/* This function creates W_16,...,W_63 according to the formula
W_j <- sigma_1(W_{j-2}) + W_{j-7} + sigma_0(W_{j-15}) + W_{j-16};
*/
[System.Security.SecurityCritical] // auto-generated
private static unsafe void SHA256Expand (uint* x)
{
for (int i = 16; i < 64; i++) {
x[i] = sigma_1(x[i-2]) + x[i-7] + sigma_0(x[i-15]) + x[i-16];
}
}
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractByte()
{
var test = new SimpleBinaryOpTest__SubtractByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Byte> _fld1;
public Vector256<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SubtractByte testClass)
{
var result = Avx2.Subtract(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractByte testClass)
{
fixed (Vector256<Byte>* pFld1 = &_fld1)
fixed (Vector256<Byte>* pFld2 = &_fld2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((Byte*)(pFld1)),
Avx.LoadVector256((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector256<Byte> _clsVar2;
private Vector256<Byte> _fld1;
private Vector256<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SubtractByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
}
public SimpleBinaryOpTest__SubtractByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Subtract(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Subtract(
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Subtract(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector256<Byte>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((Byte*)(pClsVar1)),
Avx.LoadVector256((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr);
var result = Avx2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SubtractByte();
var result = Avx2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__SubtractByte();
fixed (Vector256<Byte>* pFld1 = &test._fld1)
fixed (Vector256<Byte>* pFld2 = &test._fld2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((Byte*)(pFld1)),
Avx.LoadVector256((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Byte>* pFld1 = &_fld1)
fixed (Vector256<Byte>* pFld2 = &_fld2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((Byte*)(pFld1)),
Avx.LoadVector256((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Subtract(
Avx.LoadVector256((Byte*)(&test._fld1)),
Avx.LoadVector256((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Byte> op1, Vector256<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((byte)(left[0] - right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((byte)(left[i] - right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="BasicExpressionVisitor.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Common.CommandTrees
{
using System.Collections.Generic;
using System.Diagnostics;
/// <summary>
/// An abstract base type for types that implement the IExpressionVisitor interface to derive from.
/// </summary>
/*CQT_PUBLIC_API(*/internal/*)*/ abstract class BasicExpressionVisitor : DbExpressionVisitor
{
#region protected API, may be overridden to add functionality at specific points in the traversal
/// <summary>
/// Convenience method to visit the specified <see cref="DbUnaryExpression"/>.
/// </summary>
/// <param name="expression">The DbUnaryExpression to visit.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
protected virtual void VisitUnaryExpression(DbUnaryExpression expression)
{
VisitExpression(EntityUtil.CheckArgumentNull(expression, "expression").Argument);
}
/// <summary>
/// Convenience method to visit the specified <see cref="DbBinaryExpression"/>.
/// </summary>
/// <param name="expression">The DbBinaryExpression to visit.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
protected virtual void VisitBinaryExpression(DbBinaryExpression expression)
{
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpression(expression.Left);
VisitExpression(expression.Right);
}
/// <summary>
/// Convenience method to visit the specified <see cref="DbExpressionBinding"/>.
/// </summary>
/// <param name="binding">The DbExpressionBinding to visit.</param>
/// <exception cref="ArgumentNullException"><paramref name="binding"/> is null</exception>
protected virtual void VisitExpressionBindingPre(DbExpressionBinding binding)
{
EntityUtil.CheckArgumentNull(binding, "binding");
VisitExpression(binding.Expression);
}
/// <summary>
/// Convenience method for post-processing after a DbExpressionBinding has been visited.
/// </summary>
/// <param name="binding">The previously visited DbExpressionBinding.</param>
protected virtual void VisitExpressionBindingPost(DbExpressionBinding binding)
{
}
/// <summary>
/// Convenience method to visit the specified <see cref="DbGroupExpressionBinding"/>.
/// </summary>
/// <param name="binding">The DbGroupExpressionBinding to visit.</param>
/// <exception cref="ArgumentNullException"><paramref name="binding"/> is null</exception>
protected virtual void VisitGroupExpressionBindingPre(DbGroupExpressionBinding binding)
{
EntityUtil.CheckArgumentNull(binding, "binding");
VisitExpression(binding.Expression);
}
/// <summary>
/// Convenience method indicating that the grouping keys of a <see cref="DbGroupByExpression"/> have been visited and the aggregates are now about to be visited.
/// </summary>
/// <param name="binding">The DbGroupExpressionBinding of the DbGroupByExpression</param>
protected virtual void VisitGroupExpressionBindingMid(DbGroupExpressionBinding binding)
{
}
/// <summary>
/// Convenience method for post-processing after a DbGroupExpressionBinding has been visited.
/// </summary>
/// <param name="binding">The previously visited DbGroupExpressionBinding.</param>
protected virtual void VisitGroupExpressionBindingPost(DbGroupExpressionBinding binding)
{
}
/// <summary>
/// Convenience method indicating that the body of a Lambda <see cref="DbFunctionExpression"/> is now about to be visited.
/// </summary>
/// <param name="lambda">The DbLambda that is about to be visited</param>
/// <exception cref="ArgumentNullException"><paramref name="lambda"/> is null</exception>
protected virtual void VisitLambdaPre(DbLambda lambda)
{
EntityUtil.CheckArgumentNull(lambda, "lambda");
}
/// <summary>
/// Convenience method for post-processing after a DbLambda has been visited.
/// </summary>
/// <param name="lambda">The previously visited DbLambda.</param>
protected virtual void VisitLambdaPost(DbLambda lambda)
{
}
#endregion
#region public convenience API
/// <summary>
/// Convenience method to visit the specified <see cref="DbExpression"/>, if non-null.
/// </summary>
/// <param name="expression">The expression to visit.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public virtual void VisitExpression(DbExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression").Accept(this);
}
/// <summary>
/// Convenience method to visit each <see cref="DbExpression"/> in the given list, if the list is non-null.
/// </summary>
/// <param name="expressionList">The list of expressions to visit.</param>
/// <exception cref="ArgumentNullException"><paramref name="expressionList"/> is null</exception>
public virtual void VisitExpressionList(IList<DbExpression> expressionList)
{
EntityUtil.CheckArgumentNull(expressionList, "expressionList");
for(int idx = 0; idx < expressionList.Count; idx++)
{
VisitExpression(expressionList[idx]);
}
}
/// <summary>
/// Convenience method to visit each <see cref="DbAggregate"/> in the list, if the list is non-null.
/// </summary>
/// <param name="aggregates">The list of aggregates to visit.</param>
/// <exception cref="ArgumentNullException"><paramref name="aggregates"/> is null</exception>
public virtual void VisitAggregateList(IList<DbAggregate> aggregates)
{
EntityUtil.CheckArgumentNull(aggregates, "aggregates");
for(int idx = 0; idx < aggregates.Count; idx++)
{
VisitAggregate(aggregates[idx]);
}
}
/// <summary>
/// Convenience method to visit the specified <see cref="DbAggregate"/>.
/// </summary>
/// <param name="aggregate">The aggregate to visit.</param>
/// <exception cref="ArgumentNullException"><paramref name="aggregate"/> is null</exception>
public virtual void VisitAggregate(DbAggregate aggregate)
{
// #433613: PreSharp warning 56506: Parameter 'aggregate' to this public method must be validated: A null-dereference can occur here.
VisitExpressionList(EntityUtil.CheckArgumentNull(aggregate, "aggregate").Arguments);
}
internal virtual void VisitRelatedEntityReferenceList(IList<DbRelatedEntityRef> relatedEntityReferences)
{
for (int idx = 0; idx < relatedEntityReferences.Count; idx++)
{
this.VisitRelatedEntityReference(relatedEntityReferences[idx]);
}
}
internal virtual void VisitRelatedEntityReference(DbRelatedEntityRef relatedEntityRef)
{
VisitExpression(relatedEntityRef.TargetEntityReference);
}
#endregion
#region DbExpressionVisitor Members
/// <summary>
/// Called when an <see cref="DbExpression"/> of an otherwise unrecognized type is encountered.
/// </summary>
/// <param name="expression">The expression</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
/// <exception cref="NotSupportedException">Always thrown if this method is called, since it indicates that <paramref name="expression"/> is of an unsupported type</exception>
public override void Visit(DbExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
throw EntityUtil.NotSupported(System.Data.Entity.Strings.Cqt_General_UnsupportedExpression(expression.GetType().FullName));
}
/// <summary>
/// Visitor pattern method for <see cref="DbConstantExpression"/>.
/// </summary>
/// <param name="expression">The DbConstantExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbConstantExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
}
/// <summary>
/// Visitor pattern method for <see cref="DbNullExpression"/>.
/// </summary>
/// <param name="expression">The DbNullExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbNullExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
}
/// <summary>
/// Visitor pattern method for <see cref="DbVariableReferenceExpression"/>.
/// </summary>
/// <param name="expression">The DbVariableReferenceExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbVariableReferenceExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
}
/// <summary>
/// Visitor pattern method for <see cref="DbParameterReferenceExpression"/>.
/// </summary>
/// <param name="expression">The DbParameterReferenceExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbParameterReferenceExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
}
/// <summary>
/// Visitor pattern method for <see cref="DbFunctionExpression"/>.
/// </summary>
/// <param name="expression">The DbFunctionExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbFunctionExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionList(expression.Arguments);
}
/// <summary>
/// Visitor pattern method for <see cref="DbLambdaExpression"/>.
/// </summary>
/// <param name="expression">The DbLambdaExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbLambdaExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionList(expression.Arguments);
VisitLambdaPre(expression.Lambda);
VisitExpression(expression.Lambda.Body);
VisitLambdaPost(expression.Lambda);
}
#if METHOD_EXPRESSION
/// <summary>
/// Visitor pattern method for <see cref="MethodExpression"/>.
/// </summary>
/// <param name="expression">The MethodExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(MethodExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
if (expression.Instance != null)
{
VisitExpression(expression.Instance);
}
VisitExpressionList(expression.Arguments);
}
#endif
/// <summary>
/// Visitor pattern method for <see cref="DbPropertyExpression"/>.
/// </summary>
/// <param name="expression">The DbPropertyExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbPropertyExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
if(expression.Instance != null)
{
VisitExpression(expression.Instance);
}
}
/// <summary>
/// Visitor pattern method for <see cref="DbComparisonExpression"/>.
/// </summary>
/// <param name="expression">The DbComparisonExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbComparisonExpression expression)
{
VisitBinaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbLikeExpression"/>.
/// </summary>
/// <param name="expression">The DbLikeExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbLikeExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpression(expression.Argument);
VisitExpression(expression.Pattern);
VisitExpression(expression.Escape);
}
/// <summary>
/// Visitor pattern method for <see cref="DbLimitExpression"/>.
/// </summary>
/// <param name="expression">The DbLimitExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbLimitExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpression(expression.Argument);
VisitExpression(expression.Limit);
}
/// <summary>
/// Visitor pattern method for <see cref="DbIsNullExpression"/>.
/// </summary>
/// <param name="expression">The DbIsNullExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbIsNullExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbArithmeticExpression"/>.
/// </summary>
/// <param name="expression">The DbArithmeticExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbArithmeticExpression expression)
{
VisitExpressionList(EntityUtil.CheckArgumentNull(expression, "expression").Arguments);
}
/// <summary>
/// Visitor pattern method for <see cref="DbAndExpression"/>.
/// </summary>
/// <param name="expression">The DbAndExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbAndExpression expression)
{
VisitBinaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbOrExpression"/>.
/// </summary>
/// <param name="expression">The DbOrExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbOrExpression expression)
{
VisitBinaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbNotExpression"/>.
/// </summary>
/// <param name="expression">The DbNotExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbNotExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbDistinctExpression"/>.
/// </summary>
/// <param name="expression">The DbDistinctExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbDistinctExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbElementExpression"/>.
/// </summary>
/// <param name="expression">The DbElementExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbElementExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbIsEmptyExpression"/>.
/// </summary>
/// <param name="expression">The DbIsEmptyExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbIsEmptyExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbUnionAllExpression"/>.
/// </summary>
/// <param name="expression">The DbUnionAllExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbUnionAllExpression expression)
{
VisitBinaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbIntersectExpression"/>.
/// </summary>
/// <param name="expression">The DbIntersectExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbIntersectExpression expression)
{
VisitBinaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbExceptExpression"/>.
/// </summary>
/// <param name="expression">The DbExceptExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbExceptExpression expression)
{
VisitBinaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbOfTypeExpression"/>.
/// </summary>
/// <param name="expression">The DbOfTypeExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbOfTypeExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbTreatExpression"/>.
/// </summary>
/// <param name="expression">The DbTreatExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbTreatExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbCastExpression"/>.
/// </summary>
/// <param name="expression">The DbCastExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbCastExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbIsOfExpression"/>.
/// </summary>
/// <param name="expression">The DbIsOfExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbIsOfExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbCaseExpression"/>.
/// </summary>
/// <param name="expression">The DbCaseExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbCaseExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionList(expression.When);
VisitExpressionList(expression.Then);
VisitExpression(expression.Else);
}
/// <summary>
/// Visitor pattern method for <see cref="DbNewInstanceExpression"/>.
/// </summary>
/// <param name="expression">The DbNewInstanceExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbNewInstanceExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionList(expression.Arguments);
if (expression.HasRelatedEntityReferences)
{
Debug.Assert(expression.RelatedEntityReferences != null, "HasRelatedEntityReferences returned true for null RelatedEntityReferences list?");
this.VisitRelatedEntityReferenceList(expression.RelatedEntityReferences);
}
}
/// <summary>
/// Visitor pattern method for <see cref="DbRefExpression"/>.
/// </summary>
/// <param name="expression">The DbRefExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbRefExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbRelationshipNavigationExpression"/>.
/// </summary>
/// <param name="expression">The DbRelationshipNavigationExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbRelationshipNavigationExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
VisitExpression(EntityUtil.CheckArgumentNull(expression, "expression").NavigationSource);
}
/// <summary>
/// Visitor pattern method for <see cref="DbDerefExpression"/>.
/// </summary>
/// <param name="expression">The DeRefExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbDerefExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbRefKeyExpression"/>.
/// </summary>
/// <param name="expression">The DbRefKeyExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbRefKeyExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbEntityRefExpression"/>.
/// </summary>
/// <param name="expression">The DbEntityRefExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbEntityRefExpression expression)
{
VisitUnaryExpression(expression);
}
/// <summary>
/// Visitor pattern method for <see cref="DbScanExpression"/>.
/// </summary>
/// <param name="expression">The DbScanExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbScanExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
}
/// <summary>
/// Visitor pattern method for <see cref="DbFilterExpression"/>.
/// </summary>
/// <param name="expression">The DbFilterExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbFilterExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionBindingPre(expression.Input);
VisitExpression(expression.Predicate);
VisitExpressionBindingPost(expression.Input);
}
/// <summary>
/// Visitor pattern method for <see cref="DbProjectExpression"/>.
/// </summary>
/// <param name="expression">The DbProjectExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbProjectExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionBindingPre(expression.Input);
VisitExpression(expression.Projection);
VisitExpressionBindingPost(expression.Input);
}
/// <summary>
/// Visitor pattern method for <see cref="DbCrossJoinExpression"/>.
/// </summary>
/// <param name="expression">The DbCrossJoinExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbCrossJoinExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
foreach (DbExpressionBinding b in expression.Inputs)
{
VisitExpressionBindingPre(b);
}
foreach (DbExpressionBinding b in expression.Inputs)
{
VisitExpressionBindingPost(b);
}
}
/// <summary>
/// Visitor pattern method for <see cref="DbJoinExpression"/>.
/// </summary>
/// <param name="expression">The DbJoinExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbJoinExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionBindingPre(expression.Left);
VisitExpressionBindingPre(expression.Right);
VisitExpression(expression.JoinCondition);
VisitExpressionBindingPost(expression.Left);
VisitExpressionBindingPost(expression.Right);
}
/// <summary>
/// Visitor pattern method for <see cref="DbApplyExpression"/>.
/// </summary>
/// <param name="expression">The DbApplyExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbApplyExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionBindingPre(expression.Input);
// #433613: PreSharp warning 56506: Parameter 'expression.Apply' to this public method must be validated: A null-dereference can occur here.
if (expression.Apply != null)
{
VisitExpression(expression.Apply.Expression);
}
VisitExpressionBindingPost(expression.Input);
}
/// <summary>
/// Visitor pattern method for <see cref="DbGroupByExpression"/>.
/// </summary>
/// <param name="expression">The DbExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbGroupByExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitGroupExpressionBindingPre(expression.Input);
VisitExpressionList(expression.Keys);
VisitGroupExpressionBindingMid(expression.Input);
VisitAggregateList(expression.Aggregates);
VisitGroupExpressionBindingPost(expression.Input);
}
/// <summary>
/// Visitor pattern method for <see cref="DbSkipExpression"/>.
/// </summary>
/// <param name="expression">The DbSkipExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbSkipExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionBindingPre(expression.Input);
foreach (DbSortClause sortKey in expression.SortOrder)
{
VisitExpression(sortKey.Expression);
}
VisitExpressionBindingPost(expression.Input);
VisitExpression(expression.Count);
}
/// <summary>
/// Visitor pattern method for <see cref="DbSortExpression"/>.
/// </summary>
/// <param name="expression">The DbSortExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbSortExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionBindingPre(expression.Input);
for(int idx = 0; idx < expression.SortOrder.Count; idx++)
{
VisitExpression(expression.SortOrder[idx].Expression);
}
VisitExpressionBindingPost(expression.Input);
}
/// <summary>
/// Visitor pattern method for <see cref="DbQuantifierExpression"/>.
/// </summary>
/// <param name="expression">The DbQuantifierExpression that is being visited.</param>
/// <exception cref="ArgumentNullException"><paramref name="expression"/> is null</exception>
public override void Visit(DbQuantifierExpression expression)
{
// #433613: PreSharp warning 56506: Parameter 'expression' to this public method must be validated: A null-dereference can occur here.
EntityUtil.CheckArgumentNull(expression, "expression");
VisitExpressionBindingPre(expression.Input);
VisitExpression(expression.Predicate);
VisitExpressionBindingPost(expression.Input);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Logging;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Core.Sync;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Services.Implement
{
/// <summary>
/// Implements <see cref="ICacheInstructionService"/> providing a service for retrieving and saving cache instructions.
/// </summary>
public class CacheInstructionService : RepositoryService, ICacheInstructionService
{
private readonly ICacheInstructionRepository _cacheInstructionRepository;
private readonly IProfilingLogger _profilingLogger;
private readonly ILogger<CacheInstructionService> _logger;
private readonly GlobalSettings _globalSettings;
/// <summary>
/// Initializes a new instance of the <see cref="CacheInstructionService"/> class.
/// </summary>
public CacheInstructionService(
IScopeProvider provider,
ILoggerFactory loggerFactory,
IEventMessagesFactory eventMessagesFactory,
ICacheInstructionRepository cacheInstructionRepository,
IProfilingLogger profilingLogger,
ILogger<CacheInstructionService> logger,
IOptions<GlobalSettings> globalSettings)
: base(provider, loggerFactory, eventMessagesFactory)
{
_cacheInstructionRepository = cacheInstructionRepository;
_profilingLogger = profilingLogger;
_logger = logger;
_globalSettings = globalSettings.Value;
}
/// <inheritdoc/>
public bool IsColdBootRequired(int lastId)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
if (lastId <= 0)
{
var count = _cacheInstructionRepository.CountAll();
// If there are instructions but we haven't synced, then a cold boot is necessary.
if (count > 0)
{
return true;
}
}
else
{
// If the last synced instruction is not found in the db, then a cold boot is necessary.
if (!_cacheInstructionRepository.Exists(lastId))
{
return true;
}
}
return false;
}
}
/// <inheritdoc/>
public bool IsInstructionCountOverLimit(int lastId, int limit, out int count)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
// Check for how many instructions there are to process, each row contains a count of the number of instructions contained in each
// row so we will sum these numbers to get the actual count.
count = _cacheInstructionRepository.CountPendingInstructions(lastId);
return count > limit;
}
}
/// <inheritdoc/>
public int GetMaxInstructionId()
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _cacheInstructionRepository.GetMaxId();
}
}
/// <inheritdoc/>
public void DeliverInstructions(IEnumerable<RefreshInstruction> instructions, string localIdentity)
{
CacheInstruction entity = CreateCacheInstruction(instructions, localIdentity);
using (IScope scope = ScopeProvider.CreateScope())
{
_cacheInstructionRepository.Add(entity);
scope.Complete();
}
}
/// <inheritdoc/>
public void DeliverInstructionsInBatches(IEnumerable<RefreshInstruction> instructions, string localIdentity)
{
// Write the instructions but only create JSON blobs with a max instruction count equal to MaxProcessingInstructionCount.
using (IScope scope = ScopeProvider.CreateScope())
{
foreach (IEnumerable<RefreshInstruction> instructionsBatch in instructions.InGroupsOf(_globalSettings.DatabaseServerMessenger.MaxProcessingInstructionCount))
{
CacheInstruction entity = CreateCacheInstruction(instructionsBatch, localIdentity);
_cacheInstructionRepository.Add(entity);
}
scope.Complete();
}
}
private CacheInstruction CreateCacheInstruction(IEnumerable<RefreshInstruction> instructions, string localIdentity) =>
new CacheInstruction(0, DateTime.UtcNow, JsonConvert.SerializeObject(instructions, Formatting.None), localIdentity, instructions.Sum(x => x.JsonIdCount));
/// <inheritdoc/>
public ProcessInstructionsResult ProcessInstructions(
CacheRefresherCollection cacheRefreshers,
ServerRole serverRole,
CancellationToken cancellationToken,
string localIdentity,
DateTime lastPruned,
int lastId)
{
using (_profilingLogger.DebugDuration<CacheInstructionService>("Syncing from database..."))
using (IScope scope = ScopeProvider.CreateScope())
{
var numberOfInstructionsProcessed = ProcessDatabaseInstructions(cacheRefreshers, cancellationToken, localIdentity, ref lastId);
// Check for pruning throttling.
if (cancellationToken.IsCancellationRequested || (DateTime.UtcNow - lastPruned) <= _globalSettings.DatabaseServerMessenger.TimeBetweenPruneOperations)
{
scope.Complete();
return ProcessInstructionsResult.AsCompleted(numberOfInstructionsProcessed, lastId);
}
var instructionsWerePruned = false;
switch (serverRole)
{
case ServerRole.Single:
case ServerRole.SchedulingPublisher:
PruneOldInstructions();
instructionsWerePruned = true;
break;
}
scope.Complete();
return instructionsWerePruned
? ProcessInstructionsResult.AsCompletedAndPruned(numberOfInstructionsProcessed, lastId)
: ProcessInstructionsResult.AsCompleted(numberOfInstructionsProcessed, lastId);
}
}
/// <summary>
/// Process instructions from the database.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
/// <returns>Number of instructions processed.</returns>
private int ProcessDatabaseInstructions(CacheRefresherCollection cacheRefreshers, CancellationToken cancellationToken, string localIdentity, ref int lastId)
{
// NOTE:
// We 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that
// would be a good idea since instructions could keep getting added and then all other threads will probably get stuck from serving requests
// (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are
// pending requests after being processed, they'll just be processed on the next poll.
//
// TODO: not true if we're running on a background thread, assuming we can?
// Only retrieve the top 100 (just in case there are tons).
// Even though MaxProcessingInstructionCount is by default 1000 we still don't want to process that many
// rows in one request thread since each row can contain a ton of instructions (until 7.5.5 in which case
// a row can only contain MaxProcessingInstructionCount).
const int MaxInstructionsToRetrieve = 100;
// Only process instructions coming from a remote server, and ignore instructions coming from
// the local server as they've already been processed. We should NOT assume that the sequence of
// instructions in the database makes any sense whatsoever, because it's all async.
// Tracks which ones have already been processed to avoid duplicates
var processed = new HashSet<RefreshInstruction>();
var numberOfInstructionsProcessed = 0;
// It would have been nice to do this in a Query instead of Fetch using a data reader to save
// some memory however we cannot do that because inside of this loop the cache refreshers are also
// performing some lookups which cannot be done with an active reader open.
IEnumerable<CacheInstruction> pendingInstructions = _cacheInstructionRepository.GetPendingInstructions(lastId, MaxInstructionsToRetrieve);
lastId = 0;
foreach (CacheInstruction instruction in pendingInstructions)
{
// If this flag gets set it means we're shutting down! In this case, we need to exit asap and cannot
// continue processing anything otherwise we'll hold up the app domain shutdown.
if (cancellationToken.IsCancellationRequested)
{
break;
}
if (instruction.OriginIdentity == localIdentity)
{
// Just skip that local one but update lastId nevertheless.
lastId = instruction.Id;
continue;
}
// Deserialize remote instructions & skip if it fails.
if (!TryDeserializeInstructions(instruction, out JArray jsonInstructions))
{
lastId = instruction.Id; // skip
continue;
}
List<RefreshInstruction> instructionBatch = GetAllInstructions(jsonInstructions);
// Process as per-normal.
var success = ProcessDatabaseInstructions(cacheRefreshers, instructionBatch, instruction, processed, cancellationToken, ref lastId);
// If they couldn't be all processed (i.e. we're shutting down) then exit.
if (success == false)
{
_logger.LogInformation("The current batch of instructions was not processed, app is shutting down");
break;
}
numberOfInstructionsProcessed++;
}
return numberOfInstructionsProcessed;
}
/// <summary>
/// Attempts to deserialize the instructions to a JArray.
/// </summary>
private bool TryDeserializeInstructions(CacheInstruction instruction, out JArray jsonInstructions)
{
try
{
jsonInstructions = JsonConvert.DeserializeObject<JArray>(instruction.Instructions);
return true;
}
catch (JsonException ex)
{
_logger.LogError(ex, "Failed to deserialize instructions ({DtoId}: '{DtoInstructions}').",
instruction.Id,
instruction.Instructions);
jsonInstructions = null;
return false;
}
}
/// <summary>
/// Parses out the individual instructions to be processed.
/// </summary>
private static List<RefreshInstruction> GetAllInstructions(IEnumerable<JToken> jsonInstructions)
{
var result = new List<RefreshInstruction>();
foreach (JToken jsonItem in jsonInstructions)
{
// Could be a JObject in which case we can convert to a RefreshInstruction.
// Otherwise it could be another JArray - in which case we'll iterate that.
if (jsonItem is JObject jsonObj)
{
RefreshInstruction instruction = jsonObj.ToObject<RefreshInstruction>();
result.Add(instruction);
}
else
{
var jsonInnerArray = (JArray)jsonItem;
result.AddRange(GetAllInstructions(jsonInnerArray)); // recurse
}
}
return result;
}
/// <summary>
/// Processes the instruction batch and checks for errors.
/// </summary>
/// <param name="processed">
/// Tracks which instructions have already been processed to avoid duplicates
/// </param>
/// Returns true if all instructions in the batch were processed, otherwise false if they could not be due to the app being shut down
/// </returns>
private bool ProcessDatabaseInstructions(
CacheRefresherCollection cacheRefreshers,
IReadOnlyCollection<RefreshInstruction> instructionBatch,
CacheInstruction instruction,
HashSet<RefreshInstruction> processed,
CancellationToken cancellationToken,
ref int lastId)
{
// Execute remote instructions & update lastId.
try
{
var result = NotifyRefreshers(cacheRefreshers, instructionBatch, processed, cancellationToken);
if (result)
{
// If all instructions were processed, set the last id.
lastId = instruction.Id;
}
return result;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"DISTRIBUTED CACHE IS NOT UPDATED. Failed to execute instructions ({DtoId}: '{DtoInstructions}'). Instruction is being skipped/ignored",
instruction.Id,
instruction.Instructions);
// We cannot throw here because this invalid instruction will just keep getting processed over and over and errors
// will be thrown over and over. The only thing we can do is ignore and move on.
lastId = instruction.Id;
return false;
}
}
/// <summary>
/// Executes the instructions against the cache refresher instances.
/// </summary>
/// <returns>
/// Returns true if all instructions were processed, otherwise false if the processing was interrupted (i.e. by app shutdown).
/// </returns>
private bool NotifyRefreshers(
CacheRefresherCollection cacheRefreshers,
IEnumerable<RefreshInstruction> instructions,
HashSet<RefreshInstruction> processed,
CancellationToken cancellationToken)
{
foreach (RefreshInstruction instruction in instructions)
{
// Check if the app is shutting down, we need to exit if this happens.
if (cancellationToken.IsCancellationRequested)
{
return false;
}
// This has already been processed.
if (processed.Contains(instruction))
{
continue;
}
switch (instruction.RefreshType)
{
case RefreshMethodType.RefreshAll:
RefreshAll(cacheRefreshers, instruction.RefresherId);
break;
case RefreshMethodType.RefreshByGuid:
RefreshByGuid(cacheRefreshers, instruction.RefresherId, instruction.GuidId);
break;
case RefreshMethodType.RefreshById:
RefreshById(cacheRefreshers, instruction.RefresherId, instruction.IntId);
break;
case RefreshMethodType.RefreshByIds:
RefreshByIds(cacheRefreshers, instruction.RefresherId, instruction.JsonIds);
break;
case RefreshMethodType.RefreshByJson:
RefreshByJson(cacheRefreshers, instruction.RefresherId, instruction.JsonPayload);
break;
case RefreshMethodType.RemoveById:
RemoveById(cacheRefreshers, instruction.RefresherId, instruction.IntId);
break;
}
processed.Add(instruction);
}
return true;
}
private void RefreshAll(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier)
{
ICacheRefresher refresher = GetRefresher(cacheRefreshers, uniqueIdentifier);
refresher.RefreshAll();
}
private void RefreshByGuid(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, Guid id)
{
ICacheRefresher refresher = GetRefresher(cacheRefreshers, uniqueIdentifier);
refresher.Refresh(id);
}
private void RefreshById(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, int id)
{
ICacheRefresher refresher = GetRefresher(cacheRefreshers, uniqueIdentifier);
refresher.Refresh(id);
}
private void RefreshByIds(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, string jsonIds)
{
ICacheRefresher refresher = GetRefresher(cacheRefreshers, uniqueIdentifier);
foreach (var id in JsonConvert.DeserializeObject<int[]>(jsonIds))
{
refresher.Refresh(id);
}
}
private void RefreshByJson(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, string jsonPayload)
{
IJsonCacheRefresher refresher = GetJsonRefresher(cacheRefreshers, uniqueIdentifier);
refresher.Refresh(jsonPayload);
}
private void RemoveById(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, int id)
{
ICacheRefresher refresher = GetRefresher(cacheRefreshers, uniqueIdentifier);
refresher.Remove(id);
}
private ICacheRefresher GetRefresher(CacheRefresherCollection cacheRefreshers, Guid id)
{
ICacheRefresher refresher = cacheRefreshers[id];
if (refresher == null)
{
throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist.");
}
return refresher;
}
private IJsonCacheRefresher GetJsonRefresher(CacheRefresherCollection cacheRefreshers, Guid id) => GetJsonRefresher(GetRefresher(cacheRefreshers, id));
private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher)
{
if (refresher is not IJsonCacheRefresher jsonRefresher)
{
throw new InvalidOperationException("Cache refresher with ID \"" + refresher.RefresherUniqueId + "\" does not implement " + typeof(IJsonCacheRefresher) + ".");
}
return jsonRefresher;
}
/// <summary>
/// Remove old instructions from the database
/// </summary>
/// <remarks>
/// Always leave the last (most recent) record in the db table, this is so that not all instructions are removed which would cause
/// the site to cold boot if there's been no instruction activity for more than TimeToRetainInstructions.
/// See: http://issues.umbraco.org/issue/U4-7643#comment=67-25085
/// </remarks>
private void PruneOldInstructions()
{
DateTime pruneDate = DateTime.UtcNow - _globalSettings.DatabaseServerMessenger.TimeToRetainInstructions;
_cacheInstructionRepository.DeleteInstructionsOlderThan(pruneDate);
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
namespace System.Net.Tests
{
public partial class WebHeaderCollectionTest
{
[Fact]
public void Ctor_Success()
{
new WebHeaderCollection();
}
[Fact]
public void DefaultPropertyValues_ReturnEmptyAfterConstruction_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
Assert.Equal(0, w.AllKeys.Length);
Assert.Equal(0, w.Count);
Assert.Equal("\r\n", w.ToString());
Assert.Empty(w);
Assert.Empty(w.AllKeys);
}
[Fact]
public void HttpRequestHeader_Add_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w[HttpRequestHeader.Connection] = "keep-alive";
Assert.Equal(1, w.Count);
Assert.Equal("keep-alive", w[HttpRequestHeader.Connection]);
Assert.Equal("Connection", w.AllKeys[0]);
}
[Theory]
[InlineData((HttpRequestHeader)int.MinValue)]
[InlineData((HttpRequestHeader)(-1))]
[InlineData((HttpRequestHeader)int.MaxValue)]
public void HttpRequestHeader_AddInvalid_Throws(HttpRequestHeader header)
{
WebHeaderCollection w = new WebHeaderCollection();
Assert.Throws<IndexOutOfRangeException>(() => w[header] = "foo");
}
[Theory]
[InlineData((HttpResponseHeader)int.MinValue)]
[InlineData((HttpResponseHeader)(-1))]
[InlineData((HttpResponseHeader)int.MaxValue)]
public void HttpResponseHeader_AddInvalid_Throws(HttpResponseHeader header)
{
WebHeaderCollection w = new WebHeaderCollection();
Assert.Throws<IndexOutOfRangeException>(() => w[header] = "foo");
}
[Fact]
public void CustomHeader_AddQuery_Success()
{
string customHeader = "Custom-Header";
string customValue = "Custom;.-Value";
WebHeaderCollection w = new WebHeaderCollection();
w[customHeader] = customValue;
Assert.Equal(1, w.Count);
Assert.Equal(customValue, w[customHeader]);
Assert.Equal(customHeader, w.AllKeys[0]);
}
[Fact]
public void HttpResponseHeader_AddQuery_CommonHeader_Success()
{
string headerValue = "value123";
WebHeaderCollection w = new WebHeaderCollection();
w[HttpResponseHeader.ProxyAuthenticate] = headerValue;
w[HttpResponseHeader.WwwAuthenticate] = headerValue;
Assert.Equal(headerValue, w[HttpResponseHeader.ProxyAuthenticate]);
Assert.Equal(headerValue, w[HttpResponseHeader.WwwAuthenticate]);
}
[Fact]
public void HttpRequest_AddQuery_CommonHeader_Success()
{
string headerValue = "value123";
WebHeaderCollection w = new WebHeaderCollection();
w[HttpRequestHeader.Accept] = headerValue;
Assert.Equal(headerValue, w[HttpRequestHeader.Accept]);
}
[Fact]
public void RequestThenResponseHeaders_Add_Throws()
{
WebHeaderCollection w = new WebHeaderCollection();
w[HttpRequestHeader.Accept] = "text/json";
Assert.Throws<InvalidOperationException>(() => w[HttpResponseHeader.ContentLength] = "123");
}
[Fact]
public void ResponseThenRequestHeaders_Add_Throws()
{
WebHeaderCollection w = new WebHeaderCollection();
w[HttpResponseHeader.ContentLength] = "123";
Assert.Throws<InvalidOperationException>(() => w[HttpRequestHeader.Accept] = "text/json");
}
[Fact]
public void ResponseHeader_QueryRequest_Throws()
{
WebHeaderCollection w = new WebHeaderCollection();
w[HttpResponseHeader.ContentLength] = "123";
Assert.Throws<InvalidOperationException>(() => w[HttpRequestHeader.Accept]);
}
[Fact]
public void RequestHeader_QueryResponse_Throws()
{
WebHeaderCollection w = new WebHeaderCollection();
w[HttpRequestHeader.Accept] = "text/json";
Assert.Throws<InvalidOperationException>(() => w[HttpResponseHeader.ContentLength]);
}
[Fact]
public void Setter_ValidName_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w["Accept"] = "text/json";
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Setter_NullOrEmptyName_Throws(string name)
{
WebHeaderCollection w = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentNullException>("name", () => w[name] = "test");
}
public static object[][] InvalidNames = {
new object[] { "(" },
new object[] { "\u1234" },
new object[] { "\u0019" }
};
[Theory, MemberData(nameof(InvalidNames))]
public void Setter_InvalidName_Throws(string name)
{
WebHeaderCollection w = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("name", () => w[name] = "test");
}
public static object[][] InvalidValues = {
new object[] { "value1\rvalue2\r" },
new object[] { "value1\nvalue2\r" },
new object[] { "value1\u007fvalue2" },
new object[] { "value1\r\nvalue2" },
new object[] { "value1\u0019value2" }
};
[Theory, MemberData(nameof(InvalidValues))]
public void Setter_InvalidValue_Throws(string value)
{
WebHeaderCollection w = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("value", () => w["custom"] = value);
}
public static object[][] ValidValues = {
new object[] { null },
new object[] { "" },
new object[] { "value1\r\n" },
new object[] { "value1\tvalue2" },
new object[] { "value1\r\n\tvalue2" },
new object[] { "value1\r\n value2" }
};
[Theory, MemberData(nameof(ValidValues))]
public void Setter_ValidValue_Success(string value)
{
WebHeaderCollection w = new WebHeaderCollection();
w["custom"] = value;
}
[Theory]
[InlineData("name", "name")]
[InlineData("name", "NaMe")]
[InlineData("nAmE", "name")]
public void Setter_SameHeaderTwice_Success(string firstName, string secondName)
{
WebHeaderCollection w = new WebHeaderCollection();
w[firstName] = "first";
w[secondName] = "second";
Assert.Equal(1, w.Count);
Assert.NotEmpty(w);
Assert.NotEmpty(w.AllKeys);
Assert.Equal(new[] { firstName }, w.AllKeys);
Assert.Equal("second", w[firstName]);
Assert.Equal("second", w[secondName]);
}
[Theory]
[InlineData("name")]
[InlineData("nAMe")]
public void Remove_HeaderExists_RemovesFromCollection(string name)
{
var headers = new WebHeaderCollection()
{
{ "name", "value" }
};
headers.Remove(name);
Assert.Empty(headers);
headers.Remove(name);
Assert.Empty(headers);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Remove_NullOrEmptyHeader_ThrowsArgumentNullException(string name)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentNullException>("name", () => headers.Remove(name));
}
[Theory]
[InlineData(" \r \t \n")]
[InlineData(" name ")]
[MemberData(nameof(InvalidValues))]
public void Remove_InvalidHeader_ThrowsArgumentException(string name)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("name", () => headers.Remove(name));
}
[Fact]
public void Remove_IllegalCharacter_Throws()
{
WebHeaderCollection w = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("name", () => w.Remove("{"));
}
[Fact]
public void Remove_EmptyCollection_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Remove("foo");
Assert.Equal(0, w.Count);
Assert.Empty(w);
Assert.Empty(w.AllKeys);
}
[Theory]
[InlineData("name", "name")]
[InlineData("name", "NaMe")]
public void Remove_SetThenRemove_Success(string setName, string removeName)
{
WebHeaderCollection w = new WebHeaderCollection();
w[setName] = "value";
w.Remove(removeName);
Assert.Equal(0, w.Count);
Assert.Empty(w);
Assert.Empty(w.AllKeys);
}
[Theory]
[InlineData("name", "name")]
[InlineData("name", "NaMe")]
public void Remove_SetTwoThenRemoveOne_Success(string setName, string removeName)
{
WebHeaderCollection w = new WebHeaderCollection();
w[setName] = "value";
w["foo"] = "bar";
w.Remove(removeName);
Assert.Equal(1, w.Count);
Assert.NotEmpty(w);
Assert.NotEmpty(w.AllKeys);
Assert.Equal(new[] { "foo" }, w.AllKeys);
Assert.Equal("bar", w["foo"]);
}
[Fact]
public void Getter_EmptyCollection_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
Assert.Null(w["name"]);
Assert.Equal(0, w.Count);
Assert.Empty(w);
Assert.Empty(w.AllKeys);
}
[Fact]
public void Getter_NonEmptyCollectionNonExistentHeader_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w["name"] = "value";
Assert.Null(w["foo"]);
Assert.Equal(1, w.Count);
Assert.NotEmpty(w);
Assert.NotEmpty(w.AllKeys);
Assert.Equal(new[] { "name" }, w.AllKeys);
Assert.Equal("value", w["name"]);
}
[Fact]
public void Getter_Success()
{
string[] keys = { "Accept", "uPgRaDe", "Custom" };
string[] values = { "text/plain, text/html", " HTTP/2.0 , SHTTP/1.3, , RTA/x11 ", "\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"" };
WebHeaderCollection w = new WebHeaderCollection();
for (int i = 0; i < keys.Length; ++i)
{
string key = keys[i];
string value = values[i];
w[key] = value;
}
for (int i = 0; i < keys.Length; ++i)
{
string key = keys[i];
string expected = values[i].Trim();
Assert.Equal(expected, w[key]);
Assert.Equal(expected, w[key.ToUpperInvariant()]);
Assert.Equal(expected, w[key.ToLowerInvariant()]);
}
}
[Fact]
public void ToString_Empty_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
Assert.Equal("\r\n", w.ToString());
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void ToString_SingleHeaderWithEmptyValue_Success(string value)
{
WebHeaderCollection w = new WebHeaderCollection();
w["name"] = value;
Assert.Equal("name: \r\n\r\n", w.ToString());
}
[Fact]
public void ToString_NotEmpty_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w["Accept"] = "text/plain";
w["Content-Length"] = "123";
Assert.Equal(
"Accept: text/plain\r\nContent-Length: 123\r\n\r\n",
w.ToString());
}
[Fact]
public void IterateCollection_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w["Accept"] = "text/plain";
w["Content-Length"] = "123";
string result = "";
foreach (var item in w)
{
result += item;
}
Assert.Equal("AcceptContent-Length", result);
}
[Fact]
public void Enumerator_Success()
{
string item1 = "Accept";
string item2 = "Content-Length";
string item3 = "Name";
WebHeaderCollection w = new WebHeaderCollection();
w[item1] = "text/plain";
w[item2] = "123";
w[item3] = "value";
IEnumerable collection = w;
IEnumerator e = collection.GetEnumerator();
for (int i = 0; i < 2; i++)
{
// Not started
Assert.Throws<InvalidOperationException>(() => e.Current);
Assert.True(e.MoveNext());
Assert.Same(item1, e.Current);
Assert.True(e.MoveNext());
Assert.Same(item2, e.Current);
Assert.True(e.MoveNext());
Assert.Same(item3, e.Current);
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
// Ended
Assert.Throws<InvalidOperationException>(() => e.Current);
e.Reset();
}
}
public static IEnumerable<object[]> SerializeDeserialize_Roundtrip_MemberData()
{
for (int i = 0; i < 10; i++)
{
var wc = new WebHeaderCollection();
for (int j = 0; j < i; j++)
{
wc[$"header{j}"] = $"value{j}";
}
yield return new object[] { wc };
}
}
public static IEnumerable<object[]> Add_Value_TestData()
{
yield return new object[] { null, string.Empty };
yield return new object[] { string.Empty, string.Empty };
yield return new object[] { "VaLue", "VaLue" };
yield return new object[] { " value ", "value" };
// Documentation says this should fail but it does not.
string longString = new string('a', 65536);
yield return new object[] { longString, longString };
}
[Theory]
[MemberData(nameof(Add_Value_TestData))]
public void Add_ValidValue_Success(string value, string expectedValue)
{
var headers = new WebHeaderCollection
{
{ "name", value }
};
Assert.Equal(expectedValue, headers["name"]);
}
[Fact]
public void Add_HeaderAlreadyExists_AppendsValue()
{
var headers = new WebHeaderCollection
{
{ "name", "value1" },
{ "name", null },
{ "name", "value2" },
{ "NAME", "value3" },
{ "name", "" }
};
Assert.Equal("value1,,value2,value3,", headers["name"]);
}
[Fact]
public void Add_NullName_ThrowsArgumentNullException()
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentNullException>("name", () => headers.Add(null, "value"));
}
[Theory]
[InlineData("")]
[InlineData("(")]
[InlineData("\r \t \n")]
[InlineData(" name ")]
[MemberData(nameof(InvalidValues))]
public void Add_InvalidName_ThrowsArgumentException(string name)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("name", () => headers.Add(name, "value"));
}
[Theory]
[MemberData(nameof(InvalidValues))]
public void Add_InvalidValue_ThrowsArgumentException(string value)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("value", () => headers.Add("name", value));
}
[Fact]
public void Add_ValidHeader_AddsToHeaders()
{
var headers = new WebHeaderCollection()
{
"name:value1",
"name:",
"NaMe:value2",
"name: ",
};
Assert.Equal("value1,,value2,", headers["name"]);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Add_NullHeader_ThrowsArgumentNullException(string header)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentNullException>("header", () => headers.Add(header));
}
[Theory]
[InlineData(" \r \t \n", "header")]
[InlineData("nocolon", "header")]
[InlineData(" :value", "name")]
[InlineData("name :value", "name")]
[InlineData("name:va\rlue", "value")]
public void Add_InvalidHeader_ThrowsArgumentException(string header, string paramName)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>(paramName, () => headers.Add(header));
}
private const string HeaderType = "Set-Cookie";
private const string Cookie1 = "locale=en; path=/; expires=Fri, 05 Oct 2018 06:28:57 -0000";
private const string Cookie2 = "uuid=123abc; path=/; expires=Fri, 05 Oct 2018 06:28:57 -0000; secure; HttpOnly";
private const string Cookie3 = "country=US; path=/; expires=Fri, 05 Oct 2018 06:28:57 -0000";
private const string Cookie4 = "m_session=session1; path=/; expires=Sun, 08 Oct 2017 00:28:57 -0000; secure; HttpOnly";
private const string Cookie1NoAttribute = "locale=en";
private const string Cookie2NoAttribute = "uuid=123abc";
private const string Cookie3NoAttribute = "country=US";
private const string Cookie4NoAttribute = "m_session=session1";
private const string CookieInvalid = "helloWorld";
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Requires fix shipping in .NET 4.7.2")]
public void GetValues_MultipleSetCookieHeadersWithExpiresAttribute_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HeaderType, Cookie1);
w.Add(HeaderType, Cookie2);
w.Add(HeaderType, Cookie3);
w.Add(HeaderType, Cookie4);
string[] values = w.GetValues(HeaderType);
Assert.Equal(4, values.Length);
Assert.Equal(Cookie1, values[0]);
Assert.Equal(Cookie2, values[1]);
Assert.Equal(Cookie3, values[2]);
Assert.Equal(Cookie4, values[3]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Requires fix shipping in .NET 4.7.2")]
public void GetValues_SingleSetCookieHeaderWithMultipleCookiesWithExpiresAttribute_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HeaderType, Cookie1 + "," + Cookie2 + "," + Cookie3 + "," + Cookie4);
string[] values = w.GetValues(HeaderType);
Assert.Equal(4, values.Length);
Assert.Equal(Cookie1, values[0]);
Assert.Equal(Cookie2, values[1]);
Assert.Equal(Cookie3, values[2]);
Assert.Equal(Cookie4, values[3]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Requires fix shipping in .NET 4.7.2")]
public void GetValues_MultipleSetCookieHeadersWithNoAttribute_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HeaderType, Cookie1NoAttribute);
w.Add(HeaderType, Cookie2NoAttribute);
w.Add(HeaderType, Cookie3NoAttribute);
w.Add(HeaderType, Cookie4NoAttribute);
string[] values = w.GetValues(HeaderType);
Assert.Equal(4, values.Length);
Assert.Equal(Cookie1NoAttribute, values[0]);
Assert.Equal(Cookie2NoAttribute, values[1]);
Assert.Equal(Cookie3NoAttribute, values[2]);
Assert.Equal(Cookie4NoAttribute, values[3]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Requires fix shipping in .NET 4.7.2")]
public void GetValues_SingleSetCookieHeaderWithMultipleCookiesWithNoAttribute_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HeaderType, Cookie1NoAttribute + "," + Cookie2NoAttribute + "," + Cookie3NoAttribute + "," + Cookie4NoAttribute);
string[] values = w.GetValues(HeaderType);
Assert.Equal(4, values.Length);
Assert.Equal(Cookie1NoAttribute, values[0]);
Assert.Equal(Cookie2NoAttribute, values[1]);
Assert.Equal(Cookie3NoAttribute, values[2]);
Assert.Equal(Cookie4NoAttribute, values[3]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Requires fix shipping in .NET 4.7.2")]
public void GetValues_InvalidSetCookieHeader_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HeaderType, CookieInvalid);
string[] values = w.GetValues(HeaderType);
Assert.Equal(0, values.Length);
}
[Fact]
public void GetValues_MultipleValuesHeader_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
string headerType = "Accept";
w.Add(headerType, "text/plain, text/html");
string[] values = w.GetValues(headerType);
Assert.Equal(2, values.Length);
Assert.Equal("text/plain", values[0]);
Assert.Equal("text/html", values[1]);
}
[Fact]
public void HttpRequestHeader_Add_Rmemove_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HttpRequestHeader.Warning, "Warning1");
Assert.Equal(1, w.Count);
Assert.Equal("Warning1", w[HttpRequestHeader.Warning]);
Assert.Equal("Warning", w.AllKeys[0]);
w.Remove(HttpRequestHeader.Warning);
Assert.Equal(0, w.Count);
}
[Fact]
public void HttpRequestHeader_Get_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add("header1", "value1");
w.Add("header1", "value2");
string[] values = w.GetValues(0);
Assert.Equal("value1", values[0]);
Assert.Equal("value2", values[1]);
}
[Fact]
public void HttpRequestHeader_ToByteArray_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add("header1", "value1");
w.Add("header1", "value2");
byte[] byteArr = w.ToByteArray();
Assert.NotEmpty(byteArr);
}
[Fact]
public void HttpRequestHeader_GetKey_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add("header1", "value1");
w.Add("header1", "value2");
Assert.NotEmpty(w.GetKey(0));
}
[Fact]
public void HttpRequestHeader_GetValues_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add("header1", "value1");
Assert.Equal("value1", w.GetValues("header1")[0]);
}
[Fact]
public void HttpRequestHeader_Clear_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add("header1", "value1");
w.Add("header1", "value2");
w.Clear();
Assert.Equal(0, w.Count);
}
[Fact]
public void HttpRequestHeader_IsRestricted_Success()
{
Assert.True(WebHeaderCollection.IsRestricted("Accept"));
Assert.False(WebHeaderCollection.IsRestricted("Age"));
Assert.False(WebHeaderCollection.IsRestricted("Accept", true));
}
[Fact]
public void HttpRequestHeader_AddHeader_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HttpRequestHeader.ContentLength, "10");
w.Add(HttpRequestHeader.ContentType, "text/html");
Assert.Equal(2,w.Count);
}
[Fact]
public void WebHeaderCollection_Keys_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HttpRequestHeader.ContentLength, "10");
w.Add(HttpRequestHeader.ContentType, "text/html");
Assert.Equal(2, w.Keys.Count);
}
[Fact]
public void HttpRequestHeader_AddHeader_Failure()
{
WebHeaderCollection w = new WebHeaderCollection();
char[] arr = new char[ushort.MaxValue + 1];
string maxStr = new string(arr);
AssertExtensions.Throws<ArgumentException>("value", () => w.Add(HttpRequestHeader.ContentLength,maxStr));
AssertExtensions.Throws<ArgumentException>("value", () => w.Add("ContentLength", maxStr));
}
[Fact]
public void HttpResponseHeader_Set_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Set(HttpResponseHeader.ProxyAuthenticate, "value123");
Assert.Equal("value123", w[HttpResponseHeader.ProxyAuthenticate]);
}
[Fact]
public void HttpRequestHeader_Set_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Set(HttpRequestHeader.Connection, "keep-alive");
Assert.Equal(1, w.Count);
Assert.Equal("keep-alive", w[HttpRequestHeader.Connection]);
Assert.Equal("Connection", w.AllKeys[0]);
}
[Fact]
public void NameValue_Set_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Set("firstName", "first");
Assert.Equal(1, w.Count);
Assert.NotEmpty(w);
Assert.NotEmpty(w.AllKeys);
Assert.Equal(new[] { "firstName" }, w.AllKeys);
Assert.Equal("first", w["firstName"]);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Aurora.Framework;
using Aurora.Simulation.Base;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Region.Framework.Scenes.Components;
namespace Aurora.ScriptEngine.AuroraDotNetEngine
{
public class ScriptStateSave
{
private string m_componentName = "ScriptState";
private IComponentManager m_manager;
private ScriptEngine m_module;
public void Initialize(ScriptEngine module)
{
m_module = module;
m_manager = module.Worlds[0].RequestModuleInterface<IComponentManager>();
}
public void AddScene(IScene scene)
{
scene.AuroraEventManager.RegisterEventHandler("DeleteToInventory", AuroraEventManager_OnGenericEvent);
}
public void Close()
{
}
private object AuroraEventManager_OnGenericEvent(string FunctionName, object parameters)
{
if (FunctionName == "DeleteToInventory")
{
//Resave all the state saves for this object
ISceneEntity entity = (ISceneEntity)parameters;
foreach (ISceneChildEntity child in entity.ChildrenEntities())
{
m_module.SaveStateSaves(child.UUID);
}
}
return null;
}
public void SaveStateTo(ScriptData script)
{
SaveStateTo(script, false);
}
public void SaveStateTo(ScriptData script, bool forced)
{
SaveStateTo(script, forced, true);
}
public void SaveStateTo(ScriptData script, bool forced, bool saveBackup)
{
if (!forced)
{
if (script.Script == null)
return; //If it didn't compile correctly, this happens
if (!script.Script.NeedsStateSaved)
return; //If it doesn't need a state save, don't save one
}
if (script.Script != null)
script.Script.NeedsStateSaved = false;
if (saveBackup)
script.Part.ParentEntity.HasGroupChanged = true;
StateSave stateSave = new StateSave
{
State = script.State,
ItemID = script.ItemID,
Running = script.Running,
MinEventDelay = script.EventDelayTicks,
Disabled = script.Disabled,
UserInventoryID = script.UserInventoryItemID,
AssemblyName = script.AssemblyName,
Compiled = script.Compiled,
Source = script.Source
};
//Allow for the full path to be put down, not just the assembly name itself
if (script.InventoryItem != null)
{
stateSave.PermsGranter = script.InventoryItem.PermsGranter;
stateSave.PermsMask = script.InventoryItem.PermsMask;
}
else
{
stateSave.PermsGranter = UUID.Zero;
stateSave.PermsMask = 0;
}
stateSave.TargetOmegaWasSet = script.TargetOmegaWasSet;
//Vars
Dictionary<string, Object> vars = new Dictionary<string, object>();
if (script.Script != null)
vars = script.Script.GetStoreVars();
try
{
stateSave.Variables = WebUtils.BuildXmlResponse(vars);
}
catch
{
}
//Plugins
stateSave.Plugins = m_module.GetSerializationData(script.ItemID, script.Part.UUID);
CreateOSDMapForState(script, stateSave);
}
public void Deserialize(ScriptData instance, StateSave save)
{
instance.State = save.State;
instance.Running = save.Running;
instance.EventDelayTicks = (long)save.MinEventDelay;
instance.AssemblyName = save.AssemblyName;
instance.Disabled = save.Disabled;
instance.UserInventoryItemID = save.UserInventoryID;
instance.PluginData = save.Plugins;
m_module.CreateFromData(instance.Part.UUID, instance.ItemID, instance.Part.UUID,
instance.PluginData);
instance.Source = save.Source;
instance.InventoryItem.PermsGranter = save.PermsGranter;
instance.InventoryItem.PermsMask = save.PermsMask;
instance.TargetOmegaWasSet = save.TargetOmegaWasSet;
try
{
Dictionary<string, object> vars = WebUtils.ParseXmlResponse(save.Variables);
if (vars != null && vars.Count != 0 || instance.Script != null)
instance.Script.SetStoreVars(vars);
}
catch
{
}
}
public StateSave FindScriptStateSave(ScriptData script)
{
OSDMap component = m_manager.GetComponentState(script.Part, m_componentName) as OSDMap;
//Attempt to find the state saves we have
if (component != null)
{
OSD o;
//If we have one for this item, deserialize it
if (!component.TryGetValue(script.ItemID.ToString(), out o))
{
if (!component.TryGetValue(script.InventoryItem.OldItemID.ToString(), out o))
{
if (!component.TryGetValue(script.InventoryItem.ItemID.ToString(), out o))
{
return null;
}
}
}
StateSave save = new StateSave();
save.FromOSD((OSDMap)o);
return save;
}
return null;
}
public void DeleteFrom(ScriptData script)
{
OSDMap component = m_manager.GetComponentState(script.Part, m_componentName) as OSDMap;
//Attempt to find the state saves we have
if (component != null)
{
//if we did remove something, resave it
if (component.Remove(script.ItemID.ToString()))
{
if (component.Count == 0)
m_manager.RemoveComponentState(script.Part.UUID, m_componentName);
else
m_manager.SetComponentState(script.Part, m_componentName, component);
script.Part.ParentEntity.HasGroupChanged = true;
}
}
}
public void DeleteFrom(ISceneChildEntity Part, UUID ItemID)
{
OSDMap component = m_manager.GetComponentState(Part, m_componentName) as OSDMap;
//Attempt to find the state saves we have
if (component != null)
{
//if we did remove something, resave it
if (component.Remove(ItemID.ToString()))
{
if (component.Count == 0)
m_manager.RemoveComponentState(Part.UUID, m_componentName);
else
m_manager.SetComponentState(Part, m_componentName, component);
Part.ParentEntity.HasGroupChanged = true;
}
}
}
private void CreateOSDMapForState(ScriptData script, StateSave save)
{
//Get any previous state saves from the component manager
OSDMap component = m_manager.GetComponentState(script.Part, m_componentName) as OSDMap;
if (component == null)
component = new OSDMap();
//Add our state to the list of all scripts in this object
component[script.ItemID.ToString()] = save.ToOSD();
//Now resave it
m_manager.SetComponentState(script.Part, m_componentName, component);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://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 Newtonsoft.Json.Linq;
namespace Avro
{
/// <summary>
/// Represents a message in an Avro protocol.
/// </summary>
public class Message
{
/// <summary>
/// Name of the message
/// </summary>
public string Name { get; set; }
/// <summary>
/// Documentation for the message
/// </summary>
public string Doc { get; set; }
/// <summary>
/// Anonymous record for the list of parameters for the request fields
/// </summary>
public RecordSchema Request { get; set; }
/// <summary>
/// Schema object for the 'response' attribute
/// </summary>
public Schema Response { get; set; }
/// <summary>
/// Union schema object for the 'error' attribute
/// </summary>
public UnionSchema Error { get; set; }
/// <summary>
/// Optional one-way attribute
/// </summary>
public bool? Oneway { get; set; }
/// <summary>
/// Explicitly defined protocol errors plus system added "string" error
/// </summary>
public UnionSchema SupportedErrors { get; set; }
/// <summary>
/// Constructor for Message class
/// </summary>
/// <param name="name">name property</param>
/// <param name="doc">doc property</param>
/// <param name="request">list of parameters</param>
/// <param name="response">response property</param>
/// <param name="error">error union schema</param>
/// <param name="oneway">
/// Indicates that this is a one-way message. This may only be true when
/// <paramref name="response"/> is <see cref="Schema.Type.Null"/> and there are no errors
/// listed.
/// </param>
public Message(string name, string doc, RecordSchema request, Schema response, UnionSchema error, bool? oneway)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name), "name cannot be null.");
this.Request = request;
this.Response = response;
this.Error = error;
this.Name = name;
this.Doc = doc;
this.Oneway = oneway;
if (error != null && error.CanRead(Schema.Parse("string")))
{
this.SupportedErrors = error;
}
else
{
this.SupportedErrors = (UnionSchema) Schema.Parse("[\"string\"]");
if (error != null)
{
for (int i = 0; i < error.Schemas.Count; ++i)
{
this.SupportedErrors.Schemas.Add(error.Schemas[i]);
}
}
}
}
/// <summary>
/// Parses the messages section of a protocol definition
/// </summary>
/// <param name="jmessage">messages JSON object</param>
/// <param name="names">list of parsed names</param>
/// <param name="encspace">enclosing namespace</param>
/// <returns></returns>
internal static Message Parse(JProperty jmessage, SchemaNames names, string encspace)
{
string name = jmessage.Name;
string doc = JsonHelper.GetOptionalString(jmessage.Value, "doc");
bool? oneway = JsonHelper.GetOptionalBoolean(jmessage.Value, "one-way");
PropertyMap props = Schema.GetProperties(jmessage.Value);
RecordSchema schema = RecordSchema.NewInstance(Schema.Type.Record, jmessage.Value as JObject, props, names, encspace);
JToken jresponse = jmessage.Value["response"];
var response = Schema.ParseJson(jresponse, names, encspace);
JToken jerrors = jmessage.Value["errors"];
UnionSchema uerrorSchema = null;
if (null != jerrors)
{
Schema errorSchema = Schema.ParseJson(jerrors, names, encspace);
if (!(errorSchema is UnionSchema))
throw new AvroException($"Not a UnionSchema at {jerrors.Path}");
uerrorSchema = errorSchema as UnionSchema;
}
try
{
return new Message(name, doc, schema, response, uerrorSchema, oneway);
}
catch (Exception e)
{
throw new ProtocolParseException($"Error creating Message at {jmessage.Path}", e);
}
}
/// <summary>
/// Writes the messages section of a protocol definition
/// </summary>
/// <param name="writer">writer</param>
/// <param name="names">list of names written</param>
/// <param name="encspace">enclosing namespace</param>
internal void writeJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
{
writer.WriteStartObject();
JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Doc);
if (null != this.Request)
this.Request.WriteJsonFields(writer, names, null);
if (null != this.Response)
{
writer.WritePropertyName("response");
Response.WriteJson(writer, names, encspace);
}
if (null != this.Error)
{
writer.WritePropertyName("errors");
this.Error.WriteJson(writer, names, encspace);
}
if (null != Oneway)
{
writer.WritePropertyName("one-way");
writer.WriteValue(Oneway);
}
writer.WriteEndObject();
}
/// <summary>
/// Tests equality of this Message object with the passed object
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(Object obj)
{
if (obj == this) return true;
if (!(obj is Message)) return false;
Message that = obj as Message;
return this.Name.Equals(that.Name, StringComparison.Ordinal) &&
this.Request.Equals(that.Request) &&
areEqual(this.Response, that.Response) &&
areEqual(this.Error, that.Error);
}
/// <summary>
/// Returns the hash code of this Message object
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
#pragma warning disable CA1307 // Specify StringComparison
return Name.GetHashCode() +
#pragma warning restore CA1307 // Specify StringComparison
Request.GetHashCode() +
(Response == null ? 0 : Response.GetHashCode()) +
(Error == null ? 0 : Error.GetHashCode());
}
/// <summary>
/// Tests equality of two objects taking null values into account
/// </summary>
/// <param name="o1"></param>
/// <param name="o2"></param>
/// <returns></returns>
protected static bool areEqual(object o1, object o2)
{
return o1 == null ? o2 == null : o1.Equals(o2);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
{
public abstract class AbstractCodeActionTest
{
protected abstract string GetLanguage();
protected abstract ParseOptions GetScriptOptions();
protected abstract TestWorkspace CreateWorkspaceFromFile(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions);
protected abstract object CreateCodeRefactoringProvider(Workspace workspace);
protected virtual void TestMissing(
string initial,
Func<dynamic, dynamic> nodeLocator = null)
{
TestMissing(initial, null, nodeLocator);
TestMissing(initial, GetScriptOptions(), nodeLocator);
}
protected virtual void TestMissing(
string initial,
ParseOptions parseOptions,
Func<dynamic, dynamic> nodeLocator = null)
{
TestMissing(initial, parseOptions, null, nodeLocator);
}
protected void TestMissing(
string initialMarkup,
ParseOptions parseOptions,
CompilationOptions compilationOptions,
Func<dynamic, dynamic> nodeLocator = null)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var codeIssueOrRefactoring = GetCodeRefactoring(workspace, nodeLocator);
Assert.Null(codeIssueOrRefactoring);
}
}
protected void Test(
string initial,
string expected,
int index = 0,
bool compareTokens = true,
Func<dynamic, dynamic> nodeLocator = null,
IDictionary<OptionKey, object> options = null)
{
Test(initial, expected, null, index, compareTokens, nodeLocator, options);
Test(initial, expected, GetScriptOptions(), index, compareTokens, nodeLocator, options);
}
protected void Test(
string initial,
string expected,
ParseOptions parseOptions,
int index = 0,
bool compareTokens = true,
Func<dynamic, dynamic> nodeLocator = null,
IDictionary<OptionKey, object> options = null)
{
Test(initial, expected, parseOptions, null, index, compareTokens, nodeLocator, options);
}
private void ApplyOptionsToWorkspace(Workspace workspace, IDictionary<OptionKey, object> options)
{
var optionService = workspace.Services.GetService<IOptionService>();
var optionSet = optionService.GetOptions();
foreach (var option in options)
{
optionSet = optionSet.WithChangedOption(option.Key, option.Value);
}
optionService.SetOptions(optionSet);
}
protected void Test(
string initialMarkup,
string expectedMarkup,
ParseOptions parseOptions,
CompilationOptions compilationOptions,
int index = 0,
bool compareTokens = true,
Func<dynamic, dynamic> nodeLocator = null,
IDictionary<OptionKey, object> options = null)
{
string expected;
IDictionary<string, IList<TextSpan>> spanMap;
MarkupTestFile.GetSpans(expectedMarkup.NormalizeLineEndings(), out expected, out spanMap);
var conflictSpans = spanMap.GetOrAdd("Conflict", _ => new List<TextSpan>());
var renameSpans = spanMap.GetOrAdd("Rename", _ => new List<TextSpan>());
var warningSpans = spanMap.GetOrAdd("Warning", _ => new List<TextSpan>());
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
if (options != null)
{
ApplyOptionsToWorkspace(workspace, options);
}
var codeIssueOrRefactoring = GetCodeRefactoring(workspace, nodeLocator);
TestActions(
workspace, expected, index,
codeIssueOrRefactoring.Actions.ToList(),
conflictSpans, renameSpans, warningSpans,
compareTokens: compareTokens);
}
}
internal ICodeRefactoring GetCodeRefactoring(
TestWorkspace workspace,
Func<dynamic, dynamic> nodeLocator)
{
return GetCodeRefactorings(workspace, nodeLocator).FirstOrDefault();
}
private IEnumerable<ICodeRefactoring> GetCodeRefactorings(
TestWorkspace workspace,
Func<dynamic, dynamic> nodeLocator)
{
var provider = CreateCodeRefactoringProvider(workspace);
return SpecializedCollections.SingletonEnumerable(
GetCodeRefactoring((CodeRefactoringProvider)provider, workspace));
}
protected virtual IEnumerable<SyntaxNode> GetNodes(SyntaxNode root, TextSpan span)
{
IEnumerable<SyntaxNode> nodes;
nodes = root.FindToken(span.Start, findInsideTrivia: true).GetAncestors<SyntaxNode>().Where(a => span.Contains(a.Span)).Reverse();
return nodes;
}
private CodeRefactoring GetCodeRefactoring(
CodeRefactoringProvider provider,
TestWorkspace workspace)
{
var document = GetDocument(workspace);
var span = workspace.Documents.Single(d => !d.IsLinkFile).SelectedSpans.Single();
var actions = new List<CodeAction>();
var context = new CodeRefactoringContext(document, span, (a) => actions.Add(a), CancellationToken.None);
provider.ComputeRefactoringsAsync(context).Wait();
return actions.Count > 0 ? new CodeRefactoring(provider, actions) : null;
}
protected void TestSmartTagText(
string initialMarkup,
string displayText,
int index = 0,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var refactoring = GetCodeRefactoring(workspace, nodeLocator: null);
Assert.Equal(displayText, refactoring.Actions.ElementAt(index).Title);
}
}
protected void TestExactActionSetOffered(
string initialMarkup,
IEnumerable<string> expectedActionSet,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var codeIssueOrRefactoring = GetCodeRefactoring(workspace, nodeLocator: null);
var actualActionSet = codeIssueOrRefactoring.Actions.Select(a => a.Title);
Assert.True(actualActionSet.SequenceEqual(expectedActionSet),
"Expected: " + string.Join(", ", expectedActionSet) +
"\nActual: " + string.Join(", ", actualActionSet));
}
}
protected void TestActionCount(
string initialMarkup,
int count,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var codeIssueOrRefactoring = GetCodeRefactoring(workspace, nodeLocator: null);
Assert.Equal(count, codeIssueOrRefactoring.Actions.Count());
}
}
protected void TestActions(
TestWorkspace workspace,
string expectedText,
int index,
IList<CodeAction> actions,
IList<TextSpan> expectedConflictSpans = null,
IList<TextSpan> expectedRenameSpans = null,
IList<TextSpan> expectedWarningSpans = null,
string expectedPreviewContents = null,
bool compareTokens = true,
bool compareExpectedTextAfterApply = false)
{
var operations = VerifyInputsAndGetOperations(index, actions);
VerifyPreviewContents(workspace, expectedPreviewContents, operations);
// Test annotations from the operation's new solution
var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
var oldSolution = workspace.CurrentSolution;
var newSolutionFromOperation = applyChangesOperation.ChangedSolution;
var documentFromOperation = SolutionUtilities.GetSingleChangedDocument(oldSolution, newSolutionFromOperation);
var fixedRootFromOperation = documentFromOperation.GetSyntaxRootAsync().Result;
TestAnnotations(expectedText, expectedConflictSpans, fixedRootFromOperation, ConflictAnnotation.Kind, compareTokens);
TestAnnotations(expectedText, expectedRenameSpans, fixedRootFromOperation, RenameAnnotation.Kind, compareTokens);
TestAnnotations(expectedText, expectedWarningSpans, fixedRootFromOperation, WarningAnnotation.Kind, compareTokens);
// Test final text
string actualText;
if (compareExpectedTextAfterApply)
{
applyChangesOperation.Apply(workspace, CancellationToken.None);
var newSolutionAfterApply = workspace.CurrentSolution;
var documentFromAfterApply = SolutionUtilities.GetSingleChangedDocument(oldSolution, newSolutionAfterApply);
var fixedRootFromAfterApply = documentFromAfterApply.GetSyntaxRootAsync().Result;
actualText = compareTokens ? fixedRootFromAfterApply.ToString() : fixedRootFromAfterApply.ToFullString();
}
else
{
actualText = compareTokens ? fixedRootFromOperation.ToString() : fixedRootFromOperation.ToFullString();
}
if (compareTokens)
{
TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage());
}
else
{
Assert.Equal(expectedText, actualText);
}
}
protected void TestActionsOnLinkedFiles(
TestWorkspace workspace,
string expectedText,
int index,
IList<CodeAction> actions,
string expectedPreviewContents = null,
bool compareTokens = true)
{
var operations = VerifyInputsAndGetOperations(index, actions);
VerifyPreviewContents(workspace, expectedPreviewContents, operations);
var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
applyChangesOperation.Apply(workspace, CancellationToken.None);
foreach (var document in workspace.Documents)
{
var fixedRoot = workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync().Result;
var actualText = compareTokens ? fixedRoot.ToString() : fixedRoot.ToFullString();
if (compareTokens)
{
TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage());
}
else
{
Assert.Equal(expectedText, actualText);
}
}
}
private static IEnumerable<CodeActionOperation> VerifyInputsAndGetOperations(int index, IList<CodeAction> actions)
{
Assert.NotNull(actions);
Assert.InRange(index, 0, actions.Count - 1);
var action = actions[index];
return action.GetOperationsAsync(CancellationToken.None).Result;
}
private static void VerifyPreviewContents(TestWorkspace workspace, string expectedPreviewContents, IEnumerable<CodeActionOperation> operations)
{
if (expectedPreviewContents != null)
{
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
var content = editHandler.GetPreview(workspace, operations, CancellationToken.None);
var diffView = content as IWpfDifferenceViewer;
Assert.NotNull(diffView);
var previewContents = diffView.RightView.TextBuffer.AsTextContainer().CurrentText.ToString();
diffView.Close();
Assert.Equal(expectedPreviewContents, previewContents);
}
}
private void TestAnnotations(
string expectedText,
IList<TextSpan> expectedSpans,
SyntaxNode fixedRoot,
string annotationKind,
bool compareTokens)
{
expectedSpans = expectedSpans ?? new List<TextSpan>();
var annotatedTokens = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).Select(n => (SyntaxToken)n).ToList();
Assert.Equal(expectedSpans.Count, annotatedTokens.Count);
if (expectedSpans.Count > 0)
{
var expectedTokens = TokenUtilities.GetTokens(TokenUtilities.GetSyntaxRoot(expectedText, GetLanguage()));
var actualTokens = TokenUtilities.GetTokens(fixedRoot);
for (var i = 0; i < Math.Min(expectedTokens.Count, actualTokens.Count); i++)
{
var expectedToken = expectedTokens[i];
var actualToken = actualTokens[i];
var actualIsConflict = annotatedTokens.Contains(actualToken);
var expectedIsConflict = expectedSpans.Contains(expectedToken.Span);
Assert.Equal(expectedIsConflict, actualIsConflict);
}
}
}
protected static Document GetDocument(TestWorkspace workspace)
{
return workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
}
protected void TestAddDocument(
string initial,
string expected,
IList<string> expectedContainers,
string expectedDocumentName,
int index = 0,
bool compareTokens = true)
{
TestAddDocument(initial, expected, index, expectedContainers, expectedDocumentName, null, null, compareTokens);
TestAddDocument(initial, expected, index, expectedContainers, expectedDocumentName, GetScriptOptions(), null, compareTokens);
}
private void TestAddDocument(
string initialMarkup,
string expected,
int index,
IList<string> expectedContainers,
string expectedDocumentName,
ParseOptions parseOptions,
CompilationOptions compilationOptions,
bool compareTokens)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var codeIssue = GetCodeRefactoring(workspace, nodeLocator: null);
TestAddDocument(workspace, expected, index, expectedContainers, expectedDocumentName,
codeIssue.Actions.ToList(), compareTokens);
}
}
private void TestAddDocument(
TestWorkspace workspace,
string expected,
int index,
IList<string> expectedFolders,
string expectedDocumentName,
IList<CodeAction> fixes,
bool compareTokens)
{
Assert.NotNull(fixes);
Assert.InRange(index, 0, fixes.Count - 1);
var operations = fixes[index].GetOperationsAsync(CancellationToken.None).Result;
var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
var oldSolution = workspace.CurrentSolution;
var newSolution = applyChangesOperation.ChangedSolution;
var addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution);
Assert.NotNull(addedDocument);
AssertEx.Equal(expectedFolders, addedDocument.Folders);
Assert.Equal(expectedDocumentName, addedDocument.Name);
if (compareTokens)
{
TokenUtilities.AssertTokensEqual(
expected, addedDocument.GetTextAsync().Result.ToString(), GetLanguage());
}
else
{
Assert.Equal(expected, addedDocument.GetTextAsync().Result.ToString());
}
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
var content = editHandler.GetPreview(workspace, operations, CancellationToken.None);
var textView = content as IWpfTextView;
Assert.NotNull(textView);
textView.Close();
}
}
}
| |
//
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER
// REMAINS UNCHANGED.
//
// Email: yetiicb@hotmail.com
//
// Copyright (C) 2002-2003 Idael Cardoso.
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Globalization;
using WaveLib;
namespace Yeti.MMedia
{
/// <summary>
/// Summary description for EditFormat.
/// </summary>
public class EditFormat : System.Windows.Forms.UserControl, IEditFormat
{
private System.Windows.Forms.ComboBox comboBoxChannels;
private System.Windows.Forms.ComboBox comboBoxBitsPerSample;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private Yeti.Controls.NumericTextBox textBoxSampleRate;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ToolTip toolTip1;
private System.ComponentModel.IContainer components;
private WaveFormat m_OrigFormat;
private System.Windows.Forms.ErrorProvider errorProvider1;
private bool m_FireConfigChangeEvent = true;
public EditFormat()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this.Format = new WaveFormat(44100, 16, 2); //Set default values
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
public bool ReadOnly
{
get
{
return textBoxSampleRate.ReadOnly;
}
set
{
textBoxSampleRate.ReadOnly = value;
comboBoxBitsPerSample.Enabled = comboBoxChannels.Enabled = !value;
}
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.comboBoxChannels = new System.Windows.Forms.ComboBox();
this.comboBoxBitsPerSample = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textBoxSampleRate = new Yeti.Controls.NumericTextBox();
this.label1 = new System.Windows.Forms.Label();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.errorProvider1 = new System.Windows.Forms.ErrorProvider();
this.SuspendLayout();
//
// comboBoxChannels
//
this.comboBoxChannels.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxChannels.Items.AddRange(new object[] {
"MONO",
"STEREO"});
this.comboBoxChannels.Location = new System.Drawing.Point(96, 56);
this.comboBoxChannels.Name = "comboBoxChannels";
this.comboBoxChannels.Size = new System.Drawing.Size(112, 21);
this.comboBoxChannels.TabIndex = 13;
this.comboBoxChannels.SelectedIndexChanged += new System.EventHandler(this.comboBoxChannels_SelectedIndexChanged);
//
// comboBoxBitsPerSample
//
this.comboBoxBitsPerSample.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxBitsPerSample.Items.AddRange(new object[] {
"8 bits per sample",
"16 bits per sample"});
this.comboBoxBitsPerSample.Location = new System.Drawing.Point(96, 96);
this.comboBoxBitsPerSample.Name = "comboBoxBitsPerSample";
this.comboBoxBitsPerSample.Size = new System.Drawing.Size(112, 21);
this.comboBoxBitsPerSample.TabIndex = 12;
this.comboBoxBitsPerSample.SelectedIndexChanged += new System.EventHandler(this.comboBoxBitsPerSample_SelectedIndexChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 96);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(88, 23);
this.label3.TabIndex = 11;
this.label3.Text = "Bits per sample:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 56);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(72, 16);
this.label2.TabIndex = 10;
this.label2.Text = "Audio mode:";
//
// textBoxSampleRate
//
this.textBoxSampleRate.Location = new System.Drawing.Point(96, 16);
this.textBoxSampleRate.Name = "textBoxSampleRate";
this.textBoxSampleRate.Size = new System.Drawing.Size(112, 20);
this.textBoxSampleRate.TabIndex = 8;
this.textBoxSampleRate.Text = "44100";
this.toolTip1.SetToolTip(this.textBoxSampleRate, "Sample rate, in samples per second. ");
this.textBoxSampleRate.Value = 44100;
this.textBoxSampleRate.FormatValid += new System.EventHandler(this.textBoxSampleRate_FormatValid);
this.textBoxSampleRate.FormatError += new System.EventHandler(this.textBoxSampleRate_FormatError);
this.textBoxSampleRate.TextChanged += new System.EventHandler(this.textBoxSampleRate_TextChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(72, 16);
this.label1.TabIndex = 9;
this.label1.Text = "Sample rate:";
//
// errorProvider1
//
this.errorProvider1.ContainerControl = this;
//
// EditFormat
//
this.Controls.Add(this.comboBoxChannels);
this.Controls.Add(this.comboBoxBitsPerSample);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.textBoxSampleRate);
this.Controls.Add(this.label1);
this.Name = "EditFormat";
this.Size = new System.Drawing.Size(288, 200);
this.ResumeLayout(false);
}
#endregion
#region IConfigControl Members
public void DoApply()
{
// Nothing to do
}
public void DoSetInitialValues()
{
m_FireConfigChangeEvent = false;
try
{
textBoxSampleRate.Text = m_OrigFormat.nSamplesPerSec.ToString();
if (m_OrigFormat.wBitsPerSample == 8)
{
comboBoxBitsPerSample.SelectedIndex = 0;
}
else
{
comboBoxBitsPerSample.SelectedIndex = 1;
}
if (m_OrigFormat.nChannels == 1)
{
comboBoxChannels.SelectedIndex = 0;
}
else
{
comboBoxChannels.SelectedIndex = 1;
}
}
finally
{
m_FireConfigChangeEvent = true;
}
}
public Control ConfigControl
{
get
{
return this;
}
}
public string ControlName
{
get
{
return "Input Format";
}
}
public event System.EventHandler ConfigChange;
#endregion
#region IEditFormat members
public WaveFormat Format
{
get
{
int rate = int.Parse(textBoxSampleRate.Text, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite);
int bits;
int channels;
if (comboBoxBitsPerSample.SelectedIndex == 0)
{
bits = 8;
comboBoxBitsPerSample.SelectedIndex = 0;
}
else
{
bits = 16;
}
if (comboBoxChannels.SelectedIndex == 0)
{
channels = 1;
}
else
{
channels = 2;
}
return new WaveFormat(rate, bits, channels);
}
set
{
m_OrigFormat = value;
DoSetInitialValues();
}
}
#endregion
private void OnConfigChange(System.EventArgs e)
{
if ( m_FireConfigChangeEvent && (ConfigChange != null) )
{
ConfigChange(this, e);
}
}
private void textBoxSampleRate_TextChanged(object sender, System.EventArgs e)
{
// TODO: Validate text
OnConfigChange(EventArgs.Empty);
}
private void comboBoxChannels_SelectedIndexChanged(object sender, System.EventArgs e)
{
OnConfigChange(EventArgs.Empty);
}
private void comboBoxBitsPerSample_SelectedIndexChanged(object sender, System.EventArgs e)
{
OnConfigChange(EventArgs.Empty);
}
private void textBoxSampleRate_FormatError(object sender, System.EventArgs e)
{
errorProvider1.SetError(textBoxSampleRate, "Number expected");
}
private void textBoxSampleRate_FormatValid(object sender, System.EventArgs e)
{
errorProvider1.SetError(textBoxSampleRate, "");
}
}
}
| |
// 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.
namespace System.Buffers.Text
{
public static partial class Utf8Parser
{
private static bool TryParseSByteN(ReadOnlySpan<byte> source, out sbyte value, out int bytesConsumed)
{
if (source.Length < 1)
goto FalseExit;
int sign = 1;
int index = 0;
int c = source[index];
if (c == '-')
{
sign = -1;
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
c = source[index];
}
else if (c == '+')
{
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
c = source[index];
}
int answer;
// Handle the first digit (or period) as a special case. This ensures some compatible edge-case behavior with the classic parse routines
// (at least one digit must precede any commas, and a string without any digits prior to the decimal point must have at least
// one digit after the decimal point.)
if (c == Utf8Constants.Period)
goto FractionalPartWithoutLeadingDigits;
if (!ParserHelpers.IsDigit(c))
goto FalseExit;
answer = c - '0';
for (; ; )
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
c = source[index];
if (c == Utf8Constants.Comma)
continue;
if (c == Utf8Constants.Period)
goto FractionalDigits;
if (!ParserHelpers.IsDigit(c))
goto Done;
answer = answer * 10 + c - '0';
// if sign < 0, (-1 * sign + 1) / 2 = 1
// else, (-1 * sign + 1) / 2 = 0
if (answer > sbyte.MaxValue + (-1 * sign + 1) / 2)
goto FalseExit; // Overflow
}
FractionalPartWithoutLeadingDigits: // If we got here, we found a decimal point before we found any digits. This is legal as long as there's at least one zero after the decimal point.
answer = 0;
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
if (source[index] != '0')
goto FalseExit;
FractionalDigits: // "N" format allows a fractional portion despite being an integer format but only if the post-fraction digits are all 0.
do
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
c = source[index];
}
while (c == '0');
if (ParserHelpers.IsDigit(c))
goto FalseExit; // The fractional portion contained a non-zero digit. Treat this as an error, not an early termination.
goto Done;
FalseExit:
bytesConsumed = default;
value = default;
return false;
Done:
bytesConsumed = index;
value = (sbyte)(answer * sign);
return true;
}
private static bool TryParseInt16N(ReadOnlySpan<byte> source, out short value, out int bytesConsumed)
{
if (source.Length < 1)
goto FalseExit;
int sign = 1;
int index = 0;
int c = source[index];
if (c == '-')
{
sign = -1;
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
c = source[index];
}
else if (c == '+')
{
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
c = source[index];
}
int answer;
// Handle the first digit (or period) as a special case. This ensures some compatible edge-case behavior with the classic parse routines
// (at least one digit must precede any commas, and a string without any digits prior to the decimal point must have at least
// one digit after the decimal point.)
if (c == Utf8Constants.Period)
goto FractionalPartWithoutLeadingDigits;
if (!ParserHelpers.IsDigit(c))
goto FalseExit;
answer = c - '0';
for (; ; )
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
c = source[index];
if (c == Utf8Constants.Comma)
continue;
if (c == Utf8Constants.Period)
goto FractionalDigits;
if (!ParserHelpers.IsDigit(c))
goto Done;
answer = answer * 10 + c - '0';
// if sign < 0, (-1 * sign + 1) / 2 = 1
// else, (-1 * sign + 1) / 2 = 0
if (answer > short.MaxValue + (-1 * sign + 1) / 2)
goto FalseExit; // Overflow
}
FractionalPartWithoutLeadingDigits: // If we got here, we found a decimal point before we found any digits. This is legal as long as there's at least one zero after the decimal point.
answer = 0;
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
if (source[index] != '0')
goto FalseExit;
FractionalDigits: // "N" format allows a fractional portion despite being an integer format but only if the post-fraction digits are all 0.
do
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
c = source[index];
}
while (c == '0');
if (ParserHelpers.IsDigit(c))
goto FalseExit; // The fractional portion contained a non-zero digit. Treat this as an error, not an early termination.
goto Done;
FalseExit:
bytesConsumed = default;
value = default;
return false;
Done:
bytesConsumed = index;
value = (short)(answer * sign);
return true;
}
private static bool TryParseInt32N(ReadOnlySpan<byte> source, out int value, out int bytesConsumed)
{
if (source.Length < 1)
goto FalseExit;
int sign = 1;
int index = 0;
int c = source[index];
if (c == '-')
{
sign = -1;
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
c = source[index];
}
else if (c == '+')
{
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
c = source[index];
}
int answer;
// Handle the first digit (or period) as a special case. This ensures some compatible edge-case behavior with the classic parse routines
// (at least one digit must precede any commas, and a string without any digits prior to the decimal point must have at least
// one digit after the decimal point.)
if (c == Utf8Constants.Period)
goto FractionalPartWithoutLeadingDigits;
if (!ParserHelpers.IsDigit(c))
goto FalseExit;
answer = c - '0';
for (; ; )
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
c = source[index];
if (c == Utf8Constants.Comma)
continue;
if (c == Utf8Constants.Period)
goto FractionalDigits;
if (!ParserHelpers.IsDigit(c))
goto Done;
if (((uint)answer) > int.MaxValue / 10)
goto FalseExit;
answer = answer * 10 + c - '0';
// if sign < 0, (-1 * sign + 1) / 2 = 1
// else, (-1 * sign + 1) / 2 = 0
if ((uint)answer > (uint)int.MaxValue + (-1 * sign + 1) / 2)
goto FalseExit; // Overflow
}
FractionalPartWithoutLeadingDigits: // If we got here, we found a decimal point before we found any digits. This is legal as long as there's at least one zero after the decimal point.
answer = 0;
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
if (source[index] != '0')
goto FalseExit;
FractionalDigits: // "N" format allows a fractional portion despite being an integer format but only if the post-fraction digits are all 0.
do
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
c = source[index];
}
while (c == '0');
if (ParserHelpers.IsDigit(c))
goto FalseExit; // The fractional portion contained a non-zero digit. Treat this as an error, not an early termination.
goto Done;
FalseExit:
bytesConsumed = default;
value = default;
return false;
Done:
bytesConsumed = index;
value = answer * sign;
return true;
}
private static bool TryParseInt64N(ReadOnlySpan<byte> source, out long value, out int bytesConsumed)
{
if (source.Length < 1)
goto FalseExit;
int sign = 1;
int index = 0;
int c = source[index];
if (c == '-')
{
sign = -1;
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
c = source[index];
}
else if (c == '+')
{
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
c = source[index];
}
long answer;
// Handle the first digit (or period) as a special case. This ensures some compatible edge-case behavior with the classic parse routines
// (at least one digit must precede any commas, and a string without any digits prior to the decimal point must have at least
// one digit after the decimal point.)
if (c == Utf8Constants.Period)
goto FractionalPartWithoutLeadingDigits;
if (!ParserHelpers.IsDigit(c))
goto FalseExit;
answer = c - '0';
for (; ; )
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
c = source[index];
if (c == Utf8Constants.Comma)
continue;
if (c == Utf8Constants.Period)
goto FractionalDigits;
if (!ParserHelpers.IsDigit(c))
goto Done;
if (((ulong)answer) > long.MaxValue / 10)
goto FalseExit;
answer = answer * 10 + c - '0';
// if sign < 0, (-1 * sign + 1) / 2 = 1
// else, (-1 * sign + 1) / 2 = 0
if ((ulong)answer > (ulong)(long.MaxValue + (-1 * sign + 1) / 2))
goto FalseExit; // Overflow
}
FractionalPartWithoutLeadingDigits: // If we got here, we found a decimal point before we found any digits. This is legal as long as there's at least one zero after the decimal point.
answer = 0;
index++;
if ((uint)index >= (uint)source.Length)
goto FalseExit;
if (source[index] != '0')
goto FalseExit;
FractionalDigits: // "N" format allows a fractional portion despite being an integer format but only if the post-fraction digits are all 0.
do
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
c = source[index];
}
while (c == '0');
if (ParserHelpers.IsDigit(c))
goto FalseExit; // The fractional portion contained a non-zero digit. Treat this as an error, not an early termination.
goto Done;
FalseExit:
bytesConsumed = default;
value = default;
return false;
Done:
bytesConsumed = index;
value = answer * sign;
return true;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/cloudtrace/v1/trace.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Trace.V1 {
/// <summary>Holder for reflection information generated from google/devtools/cloudtrace/v1/trace.proto</summary>
public static partial class TraceReflection {
#region Descriptor
/// <summary>File descriptor for google/devtools/cloudtrace/v1/trace.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TraceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cilnb29nbGUvZGV2dG9vbHMvY2xvdWR0cmFjZS92MS90cmFjZS5wcm90bxId",
"Z29vZ2xlLmRldnRvb2xzLmNsb3VkdHJhY2UudjEaHGdvb2dsZS9hcGkvYW5u",
"b3RhdGlvbnMucHJvdG8aG2dvb2dsZS9wcm90b2J1Zi9lbXB0eS5wcm90bxof",
"Z29vZ2xlL3Byb3RvYnVmL3RpbWVzdGFtcC5wcm90byJmCgVUcmFjZRISCgpw",
"cm9qZWN0X2lkGAEgASgJEhAKCHRyYWNlX2lkGAIgASgJEjcKBXNwYW5zGAMg",
"AygLMiguZ29vZ2xlLmRldnRvb2xzLmNsb3VkdHJhY2UudjEuVHJhY2VTcGFu",
"Ij4KBlRyYWNlcxI0CgZ0cmFjZXMYASADKAsyJC5nb29nbGUuZGV2dG9vbHMu",
"Y2xvdWR0cmFjZS52MS5UcmFjZSKdAwoJVHJhY2VTcGFuEg8KB3NwYW5faWQY",
"ASABKAYSPwoEa2luZBgCIAEoDjIxLmdvb2dsZS5kZXZ0b29scy5jbG91ZHRy",
"YWNlLnYxLlRyYWNlU3Bhbi5TcGFuS2luZBIMCgRuYW1lGAMgASgJEi4KCnN0",
"YXJ0X3RpbWUYBCABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEiwK",
"CGVuZF90aW1lGAUgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIW",
"Cg5wYXJlbnRfc3Bhbl9pZBgGIAEoBhJECgZsYWJlbHMYByADKAsyNC5nb29n",
"bGUuZGV2dG9vbHMuY2xvdWR0cmFjZS52MS5UcmFjZVNwYW4uTGFiZWxzRW50",
"cnkaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJ",
"OgI4ASJFCghTcGFuS2luZBIZChVTUEFOX0tJTkRfVU5TUEVDSUZJRUQQABIO",
"CgpSUENfU0VSVkVSEAESDgoKUlBDX0NMSUVOVBACIucCChFMaXN0VHJhY2Vz",
"UmVxdWVzdBISCgpwcm9qZWN0X2lkGAEgASgJEkcKBHZpZXcYAiABKA4yOS5n",
"b29nbGUuZGV2dG9vbHMuY2xvdWR0cmFjZS52MS5MaXN0VHJhY2VzUmVxdWVz",
"dC5WaWV3VHlwZRIRCglwYWdlX3NpemUYAyABKAUSEgoKcGFnZV90b2tlbhgE",
"IAEoCRIuCgpzdGFydF90aW1lGAUgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRp",
"bWVzdGFtcBIsCghlbmRfdGltZRgGIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5U",
"aW1lc3RhbXASDgoGZmlsdGVyGAcgASgJEhAKCG9yZGVyX2J5GAggASgJIk4K",
"CFZpZXdUeXBlEhkKFVZJRVdfVFlQRV9VTlNQRUNJRklFRBAAEgsKB01JTklN",
"QUwQARIMCghST09UU1BBThACEgwKCENPTVBMRVRFEAMiYwoSTGlzdFRyYWNl",
"c1Jlc3BvbnNlEjQKBnRyYWNlcxgBIAMoCzIkLmdvb2dsZS5kZXZ0b29scy5j",
"bG91ZHRyYWNlLnYxLlRyYWNlEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSI3",
"Cg9HZXRUcmFjZVJlcXVlc3QSEgoKcHJvamVjdF9pZBgBIAEoCRIQCgh0cmFj",
"ZV9pZBgCIAEoCSJfChJQYXRjaFRyYWNlc1JlcXVlc3QSEgoKcHJvamVjdF9p",
"ZBgBIAEoCRI1CgZ0cmFjZXMYAiABKAsyJS5nb29nbGUuZGV2dG9vbHMuY2xv",
"dWR0cmFjZS52MS5UcmFjZXMy0QMKDFRyYWNlU2VydmljZRKbAQoKTGlzdFRy",
"YWNlcxIwLmdvb2dsZS5kZXZ0b29scy5jbG91ZHRyYWNlLnYxLkxpc3RUcmFj",
"ZXNSZXF1ZXN0GjEuZ29vZ2xlLmRldnRvb2xzLmNsb3VkdHJhY2UudjEuTGlz",
"dFRyYWNlc1Jlc3BvbnNlIiiC0+STAiISIC92MS9wcm9qZWN0cy97cHJvamVj",
"dF9pZH0vdHJhY2VzEpUBCghHZXRUcmFjZRIuLmdvb2dsZS5kZXZ0b29scy5j",
"bG91ZHRyYWNlLnYxLkdldFRyYWNlUmVxdWVzdBokLmdvb2dsZS5kZXZ0b29s",
"cy5jbG91ZHRyYWNlLnYxLlRyYWNlIjOC0+STAi0SKy92MS9wcm9qZWN0cy97",
"cHJvamVjdF9pZH0vdHJhY2VzL3t0cmFjZV9pZH0SigEKC1BhdGNoVHJhY2Vz",
"EjEuZ29vZ2xlLmRldnRvb2xzLmNsb3VkdHJhY2UudjEuUGF0Y2hUcmFjZXNS",
"ZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5IjCC0+STAioyIC92MS9w",
"cm9qZWN0cy97cHJvamVjdF9pZH0vdHJhY2VzOgZ0cmFjZXNCkgEKIWNvbS5n",
"b29nbGUuZGV2dG9vbHMuY2xvdWR0cmFjZS52MUIKVHJhY2VQcm90b1ABWkdn",
"b29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2RldnRvb2xz",
"L2Nsb3VkdHJhY2UvdjE7Y2xvdWR0cmFjZaoCFUdvb2dsZS5DbG91ZC5UcmFj",
"ZS5WMWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Trace.V1.Trace), global::Google.Cloud.Trace.V1.Trace.Parser, new[]{ "ProjectId", "TraceId", "Spans" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Trace.V1.Traces), global::Google.Cloud.Trace.V1.Traces.Parser, new[]{ "Traces_" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Trace.V1.TraceSpan), global::Google.Cloud.Trace.V1.TraceSpan.Parser, new[]{ "SpanId", "Kind", "Name", "StartTime", "EndTime", "ParentSpanId", "Labels" }, null, new[]{ typeof(global::Google.Cloud.Trace.V1.TraceSpan.Types.SpanKind) }, new pbr::GeneratedClrTypeInfo[] { null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Trace.V1.ListTracesRequest), global::Google.Cloud.Trace.V1.ListTracesRequest.Parser, new[]{ "ProjectId", "View", "PageSize", "PageToken", "StartTime", "EndTime", "Filter", "OrderBy" }, null, new[]{ typeof(global::Google.Cloud.Trace.V1.ListTracesRequest.Types.ViewType) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Trace.V1.ListTracesResponse), global::Google.Cloud.Trace.V1.ListTracesResponse.Parser, new[]{ "Traces", "NextPageToken" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Trace.V1.GetTraceRequest), global::Google.Cloud.Trace.V1.GetTraceRequest.Parser, new[]{ "ProjectId", "TraceId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Trace.V1.PatchTracesRequest), global::Google.Cloud.Trace.V1.PatchTracesRequest.Parser, new[]{ "ProjectId", "Traces" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A trace describes how long it takes for an application to perform an
/// operation. It consists of a set of spans, each of which represent a single
/// timed event within the operation.
/// </summary>
public sealed partial class Trace : pb::IMessage<Trace> {
private static readonly pb::MessageParser<Trace> _parser = new pb::MessageParser<Trace>(() => new Trace());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Trace> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Trace.V1.TraceReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Trace() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Trace(Trace other) : this() {
projectId_ = other.projectId_;
traceId_ = other.traceId_;
spans_ = other.spans_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Trace Clone() {
return new Trace(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 1;
private string projectId_ = "";
/// <summary>
/// Project ID of the Cloud project where the trace data is stored.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "trace_id" field.</summary>
public const int TraceIdFieldNumber = 2;
private string traceId_ = "";
/// <summary>
/// Globally unique identifier for the trace. This identifier is a 128-bit
/// numeric value formatted as a 32-byte hex string.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string TraceId {
get { return traceId_; }
set {
traceId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "spans" field.</summary>
public const int SpansFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Cloud.Trace.V1.TraceSpan> _repeated_spans_codec
= pb::FieldCodec.ForMessage(26, global::Google.Cloud.Trace.V1.TraceSpan.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Trace.V1.TraceSpan> spans_ = new pbc::RepeatedField<global::Google.Cloud.Trace.V1.TraceSpan>();
/// <summary>
/// Collection of spans in the trace.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Trace.V1.TraceSpan> Spans {
get { return spans_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Trace);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Trace other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (TraceId != other.TraceId) return false;
if(!spans_.Equals(other.spans_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (TraceId.Length != 0) hash ^= TraceId.GetHashCode();
hash ^= spans_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ProjectId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ProjectId);
}
if (TraceId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(TraceId);
}
spans_.WriteTo(output, _repeated_spans_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (TraceId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(TraceId);
}
size += spans_.CalculateSize(_repeated_spans_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Trace other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.TraceId.Length != 0) {
TraceId = other.TraceId;
}
spans_.Add(other.spans_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
ProjectId = input.ReadString();
break;
}
case 18: {
TraceId = input.ReadString();
break;
}
case 26: {
spans_.AddEntriesFrom(input, _repeated_spans_codec);
break;
}
}
}
}
}
/// <summary>
/// List of new or updated traces.
/// </summary>
public sealed partial class Traces : pb::IMessage<Traces> {
private static readonly pb::MessageParser<Traces> _parser = new pb::MessageParser<Traces>(() => new Traces());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Traces> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Trace.V1.TraceReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Traces() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Traces(Traces other) : this() {
traces_ = other.traces_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Traces Clone() {
return new Traces(this);
}
/// <summary>Field number for the "traces" field.</summary>
public const int Traces_FieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Trace.V1.Trace> _repeated_traces_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Trace.V1.Trace.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Trace.V1.Trace> traces_ = new pbc::RepeatedField<global::Google.Cloud.Trace.V1.Trace>();
/// <summary>
/// List of traces.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Trace.V1.Trace> Traces_ {
get { return traces_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Traces);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Traces other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!traces_.Equals(other.traces_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= traces_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
traces_.WriteTo(output, _repeated_traces_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += traces_.CalculateSize(_repeated_traces_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Traces other) {
if (other == null) {
return;
}
traces_.Add(other.traces_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
traces_.AddEntriesFrom(input, _repeated_traces_codec);
break;
}
}
}
}
}
/// <summary>
/// A span represents a single timed event within a trace. Spans can be nested
/// and form a trace tree. Often, a trace contains a root span that describes the
/// end-to-end latency of an operation and, optionally, one or more subspans for
/// its suboperations. Spans do not need to be contiguous. There may be gaps
/// between spans in a trace.
/// </summary>
public sealed partial class TraceSpan : pb::IMessage<TraceSpan> {
private static readonly pb::MessageParser<TraceSpan> _parser = new pb::MessageParser<TraceSpan>(() => new TraceSpan());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TraceSpan> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Trace.V1.TraceReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TraceSpan() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TraceSpan(TraceSpan other) : this() {
spanId_ = other.spanId_;
kind_ = other.kind_;
name_ = other.name_;
StartTime = other.startTime_ != null ? other.StartTime.Clone() : null;
EndTime = other.endTime_ != null ? other.EndTime.Clone() : null;
parentSpanId_ = other.parentSpanId_;
labels_ = other.labels_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TraceSpan Clone() {
return new TraceSpan(this);
}
/// <summary>Field number for the "span_id" field.</summary>
public const int SpanIdFieldNumber = 1;
private ulong spanId_;
/// <summary>
/// Identifier for the span. Must be a 64-bit integer other than 0 and
/// unique within a trace.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong SpanId {
get { return spanId_; }
set {
spanId_ = value;
}
}
/// <summary>Field number for the "kind" field.</summary>
public const int KindFieldNumber = 2;
private global::Google.Cloud.Trace.V1.TraceSpan.Types.SpanKind kind_ = 0;
/// <summary>
/// Distinguishes between spans generated in a particular context. For example,
/// two spans with the same name may be distinguished using `RPC_CLIENT`
/// and `RPC_SERVER` to identify queueing latency associated with the span.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Trace.V1.TraceSpan.Types.SpanKind Kind {
get { return kind_; }
set {
kind_ = value;
}
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 3;
private string name_ = "";
/// <summary>
/// Name of the trace. The trace name is sanitized and displayed in the
/// Stackdriver Trace tool in the Google Developers Console.
/// The name may be a method name or some other per-call site name.
/// For the same executable and the same call point, a best practice is
/// to use a consistent name, which makes it easier to correlate
/// cross-trace spans.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "start_time" field.</summary>
public const int StartTimeFieldNumber = 4;
private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_;
/// <summary>
/// Start time of the span in nanoseconds from the UNIX epoch.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime {
get { return startTime_; }
set {
startTime_ = value;
}
}
/// <summary>Field number for the "end_time" field.</summary>
public const int EndTimeFieldNumber = 5;
private global::Google.Protobuf.WellKnownTypes.Timestamp endTime_;
/// <summary>
/// End time of the span in nanoseconds from the UNIX epoch.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp EndTime {
get { return endTime_; }
set {
endTime_ = value;
}
}
/// <summary>Field number for the "parent_span_id" field.</summary>
public const int ParentSpanIdFieldNumber = 6;
private ulong parentSpanId_;
/// <summary>
/// ID of the parent span, if any. Optional.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong ParentSpanId {
get { return parentSpanId_; }
set {
parentSpanId_ = value;
}
}
/// <summary>Field number for the "labels" field.</summary>
public const int LabelsFieldNumber = 7;
private static readonly pbc::MapField<string, string>.Codec _map_labels_codec
= new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForString(18), 58);
private readonly pbc::MapField<string, string> labels_ = new pbc::MapField<string, string>();
/// <summary>
/// Collection of labels associated with the span.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, string> Labels {
get { return labels_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TraceSpan);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TraceSpan other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (SpanId != other.SpanId) return false;
if (Kind != other.Kind) return false;
if (Name != other.Name) return false;
if (!object.Equals(StartTime, other.StartTime)) return false;
if (!object.Equals(EndTime, other.EndTime)) return false;
if (ParentSpanId != other.ParentSpanId) return false;
if (!Labels.Equals(other.Labels)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (SpanId != 0UL) hash ^= SpanId.GetHashCode();
if (Kind != 0) hash ^= Kind.GetHashCode();
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (startTime_ != null) hash ^= StartTime.GetHashCode();
if (endTime_ != null) hash ^= EndTime.GetHashCode();
if (ParentSpanId != 0UL) hash ^= ParentSpanId.GetHashCode();
hash ^= Labels.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (SpanId != 0UL) {
output.WriteRawTag(9);
output.WriteFixed64(SpanId);
}
if (Kind != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) Kind);
}
if (Name.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Name);
}
if (startTime_ != null) {
output.WriteRawTag(34);
output.WriteMessage(StartTime);
}
if (endTime_ != null) {
output.WriteRawTag(42);
output.WriteMessage(EndTime);
}
if (ParentSpanId != 0UL) {
output.WriteRawTag(49);
output.WriteFixed64(ParentSpanId);
}
labels_.WriteTo(output, _map_labels_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (SpanId != 0UL) {
size += 1 + 8;
}
if (Kind != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Kind);
}
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (startTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime);
}
if (endTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime);
}
if (ParentSpanId != 0UL) {
size += 1 + 8;
}
size += labels_.CalculateSize(_map_labels_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TraceSpan other) {
if (other == null) {
return;
}
if (other.SpanId != 0UL) {
SpanId = other.SpanId;
}
if (other.Kind != 0) {
Kind = other.Kind;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.startTime_ != null) {
if (startTime_ == null) {
startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
StartTime.MergeFrom(other.StartTime);
}
if (other.endTime_ != null) {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
EndTime.MergeFrom(other.EndTime);
}
if (other.ParentSpanId != 0UL) {
ParentSpanId = other.ParentSpanId;
}
labels_.Add(other.labels_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
SpanId = input.ReadFixed64();
break;
}
case 16: {
kind_ = (global::Google.Cloud.Trace.V1.TraceSpan.Types.SpanKind) input.ReadEnum();
break;
}
case 26: {
Name = input.ReadString();
break;
}
case 34: {
if (startTime_ == null) {
startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(startTime_);
break;
}
case 42: {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(endTime_);
break;
}
case 49: {
ParentSpanId = input.ReadFixed64();
break;
}
case 58: {
labels_.AddEntriesFrom(input, _map_labels_codec);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the TraceSpan message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Type of span. Can be used to specify additional relationships between spans
/// in addition to a parent/child relationship.
/// </summary>
public enum SpanKind {
/// <summary>
/// Unspecified.
/// </summary>
[pbr::OriginalName("SPAN_KIND_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Indicates that the span covers server-side handling of an RPC or other
/// remote network request.
/// </summary>
[pbr::OriginalName("RPC_SERVER")] RpcServer = 1,
/// <summary>
/// Indicates that the span covers the client-side wrapper around an RPC or
/// other remote request.
/// </summary>
[pbr::OriginalName("RPC_CLIENT")] RpcClient = 2,
}
}
#endregion
}
/// <summary>
/// The request message for the `ListTraces` method. All fields are required
/// unless specified.
/// </summary>
public sealed partial class ListTracesRequest : pb::IMessage<ListTracesRequest> {
private static readonly pb::MessageParser<ListTracesRequest> _parser = new pb::MessageParser<ListTracesRequest>(() => new ListTracesRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListTracesRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Trace.V1.TraceReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTracesRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTracesRequest(ListTracesRequest other) : this() {
projectId_ = other.projectId_;
view_ = other.view_;
pageSize_ = other.pageSize_;
pageToken_ = other.pageToken_;
StartTime = other.startTime_ != null ? other.StartTime.Clone() : null;
EndTime = other.endTime_ != null ? other.EndTime.Clone() : null;
filter_ = other.filter_;
orderBy_ = other.orderBy_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTracesRequest Clone() {
return new ListTracesRequest(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 1;
private string projectId_ = "";
/// <summary>
/// ID of the Cloud project where the trace data is stored.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "view" field.</summary>
public const int ViewFieldNumber = 2;
private global::Google.Cloud.Trace.V1.ListTracesRequest.Types.ViewType view_ = 0;
/// <summary>
/// Type of data returned for traces in the list. Optional. Default is
/// `MINIMAL`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Trace.V1.ListTracesRequest.Types.ViewType View {
get { return view_; }
set {
view_ = value;
}
}
/// <summary>Field number for the "page_size" field.</summary>
public const int PageSizeFieldNumber = 3;
private int pageSize_;
/// <summary>
/// Maximum number of traces to return. If not specified or <= 0, the
/// implementation selects a reasonable value. The implementation may
/// return fewer traces than the requested page size. Optional.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int PageSize {
get { return pageSize_; }
set {
pageSize_ = value;
}
}
/// <summary>Field number for the "page_token" field.</summary>
public const int PageTokenFieldNumber = 4;
private string pageToken_ = "";
/// <summary>
/// Token identifying the page of results to return. If provided, use the
/// value of the `next_page_token` field from a previous request. Optional.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string PageToken {
get { return pageToken_; }
set {
pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "start_time" field.</summary>
public const int StartTimeFieldNumber = 5;
private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_;
/// <summary>
/// End of the time interval (inclusive) during which the trace data was
/// collected from the application.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime {
get { return startTime_; }
set {
startTime_ = value;
}
}
/// <summary>Field number for the "end_time" field.</summary>
public const int EndTimeFieldNumber = 6;
private global::Google.Protobuf.WellKnownTypes.Timestamp endTime_;
/// <summary>
/// Start of the time interval (inclusive) during which the trace data was
/// collected from the application.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp EndTime {
get { return endTime_; }
set {
endTime_ = value;
}
}
/// <summary>Field number for the "filter" field.</summary>
public const int FilterFieldNumber = 7;
private string filter_ = "";
/// <summary>
/// An optional filter for the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Filter {
get { return filter_; }
set {
filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "order_by" field.</summary>
public const int OrderByFieldNumber = 8;
private string orderBy_ = "";
/// <summary>
/// Field used to sort the returned traces. Optional.
/// Can be one of the following:
///
/// * `trace_id`
/// * `name` (`name` field of root span in the trace)
/// * `duration` (difference between `end_time` and `start_time` fields of
/// the root span)
/// * `start` (`start_time` field of the root span)
///
/// Descending order can be specified by appending `desc` to the sort field
/// (for example, `name desc`).
///
/// Only one sort field is permitted.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OrderBy {
get { return orderBy_; }
set {
orderBy_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListTracesRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListTracesRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (View != other.View) return false;
if (PageSize != other.PageSize) return false;
if (PageToken != other.PageToken) return false;
if (!object.Equals(StartTime, other.StartTime)) return false;
if (!object.Equals(EndTime, other.EndTime)) return false;
if (Filter != other.Filter) return false;
if (OrderBy != other.OrderBy) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (View != 0) hash ^= View.GetHashCode();
if (PageSize != 0) hash ^= PageSize.GetHashCode();
if (PageToken.Length != 0) hash ^= PageToken.GetHashCode();
if (startTime_ != null) hash ^= StartTime.GetHashCode();
if (endTime_ != null) hash ^= EndTime.GetHashCode();
if (Filter.Length != 0) hash ^= Filter.GetHashCode();
if (OrderBy.Length != 0) hash ^= OrderBy.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ProjectId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ProjectId);
}
if (View != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) View);
}
if (PageSize != 0) {
output.WriteRawTag(24);
output.WriteInt32(PageSize);
}
if (PageToken.Length != 0) {
output.WriteRawTag(34);
output.WriteString(PageToken);
}
if (startTime_ != null) {
output.WriteRawTag(42);
output.WriteMessage(StartTime);
}
if (endTime_ != null) {
output.WriteRawTag(50);
output.WriteMessage(EndTime);
}
if (Filter.Length != 0) {
output.WriteRawTag(58);
output.WriteString(Filter);
}
if (OrderBy.Length != 0) {
output.WriteRawTag(66);
output.WriteString(OrderBy);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (View != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) View);
}
if (PageSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize);
}
if (PageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken);
}
if (startTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime);
}
if (endTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime);
}
if (Filter.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Filter);
}
if (OrderBy.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OrderBy);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListTracesRequest other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.View != 0) {
View = other.View;
}
if (other.PageSize != 0) {
PageSize = other.PageSize;
}
if (other.PageToken.Length != 0) {
PageToken = other.PageToken;
}
if (other.startTime_ != null) {
if (startTime_ == null) {
startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
StartTime.MergeFrom(other.StartTime);
}
if (other.endTime_ != null) {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
EndTime.MergeFrom(other.EndTime);
}
if (other.Filter.Length != 0) {
Filter = other.Filter;
}
if (other.OrderBy.Length != 0) {
OrderBy = other.OrderBy;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
ProjectId = input.ReadString();
break;
}
case 16: {
view_ = (global::Google.Cloud.Trace.V1.ListTracesRequest.Types.ViewType) input.ReadEnum();
break;
}
case 24: {
PageSize = input.ReadInt32();
break;
}
case 34: {
PageToken = input.ReadString();
break;
}
case 42: {
if (startTime_ == null) {
startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(startTime_);
break;
}
case 50: {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(endTime_);
break;
}
case 58: {
Filter = input.ReadString();
break;
}
case 66: {
OrderBy = input.ReadString();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the ListTracesRequest message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Type of data returned for traces in the list.
/// </summary>
public enum ViewType {
/// <summary>
/// Default is `MINIMAL` if unspecified.
/// </summary>
[pbr::OriginalName("VIEW_TYPE_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Minimal view of the trace record that contains only the project
/// and trace IDs.
/// </summary>
[pbr::OriginalName("MINIMAL")] Minimal = 1,
/// <summary>
/// Root span view of the trace record that returns the root spans along
/// with the minimal trace data.
/// </summary>
[pbr::OriginalName("ROOTSPAN")] Rootspan = 2,
/// <summary>
/// Complete view of the trace record that contains the actual trace data.
/// This is equivalent to calling the REST `get` or RPC `GetTrace` method
/// using the ID of each listed trace.
/// </summary>
[pbr::OriginalName("COMPLETE")] Complete = 3,
}
}
#endregion
}
/// <summary>
/// The response message for the `ListTraces` method.
/// </summary>
public sealed partial class ListTracesResponse : pb::IMessage<ListTracesResponse> {
private static readonly pb::MessageParser<ListTracesResponse> _parser = new pb::MessageParser<ListTracesResponse>(() => new ListTracesResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListTracesResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Trace.V1.TraceReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTracesResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTracesResponse(ListTracesResponse other) : this() {
traces_ = other.traces_.Clone();
nextPageToken_ = other.nextPageToken_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTracesResponse Clone() {
return new ListTracesResponse(this);
}
/// <summary>Field number for the "traces" field.</summary>
public const int TracesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Trace.V1.Trace> _repeated_traces_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Trace.V1.Trace.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Trace.V1.Trace> traces_ = new pbc::RepeatedField<global::Google.Cloud.Trace.V1.Trace>();
/// <summary>
/// List of trace records returned.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Trace.V1.Trace> Traces {
get { return traces_; }
}
/// <summary>Field number for the "next_page_token" field.</summary>
public const int NextPageTokenFieldNumber = 2;
private string nextPageToken_ = "";
/// <summary>
/// If defined, indicates that there are more traces that match the request
/// and that this value should be passed to the next request to continue
/// retrieving additional traces.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string NextPageToken {
get { return nextPageToken_; }
set {
nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListTracesResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListTracesResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!traces_.Equals(other.traces_)) return false;
if (NextPageToken != other.NextPageToken) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= traces_.GetHashCode();
if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
traces_.WriteTo(output, _repeated_traces_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += traces_.CalculateSize(_repeated_traces_codec);
if (NextPageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListTracesResponse other) {
if (other == null) {
return;
}
traces_.Add(other.traces_);
if (other.NextPageToken.Length != 0) {
NextPageToken = other.NextPageToken;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
traces_.AddEntriesFrom(input, _repeated_traces_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The request message for the `GetTrace` method.
/// </summary>
public sealed partial class GetTraceRequest : pb::IMessage<GetTraceRequest> {
private static readonly pb::MessageParser<GetTraceRequest> _parser = new pb::MessageParser<GetTraceRequest>(() => new GetTraceRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetTraceRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Trace.V1.TraceReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetTraceRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetTraceRequest(GetTraceRequest other) : this() {
projectId_ = other.projectId_;
traceId_ = other.traceId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetTraceRequest Clone() {
return new GetTraceRequest(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 1;
private string projectId_ = "";
/// <summary>
/// ID of the Cloud project where the trace data is stored.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "trace_id" field.</summary>
public const int TraceIdFieldNumber = 2;
private string traceId_ = "";
/// <summary>
/// ID of the trace to return.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string TraceId {
get { return traceId_; }
set {
traceId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetTraceRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetTraceRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (TraceId != other.TraceId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (TraceId.Length != 0) hash ^= TraceId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ProjectId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ProjectId);
}
if (TraceId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(TraceId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (TraceId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(TraceId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetTraceRequest other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.TraceId.Length != 0) {
TraceId = other.TraceId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
ProjectId = input.ReadString();
break;
}
case 18: {
TraceId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The request message for the `PatchTraces` method.
/// </summary>
public sealed partial class PatchTracesRequest : pb::IMessage<PatchTracesRequest> {
private static readonly pb::MessageParser<PatchTracesRequest> _parser = new pb::MessageParser<PatchTracesRequest>(() => new PatchTracesRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PatchTracesRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Trace.V1.TraceReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PatchTracesRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PatchTracesRequest(PatchTracesRequest other) : this() {
projectId_ = other.projectId_;
Traces = other.traces_ != null ? other.Traces.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PatchTracesRequest Clone() {
return new PatchTracesRequest(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 1;
private string projectId_ = "";
/// <summary>
/// ID of the Cloud project where the trace data is stored.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "traces" field.</summary>
public const int TracesFieldNumber = 2;
private global::Google.Cloud.Trace.V1.Traces traces_;
/// <summary>
/// The body of the message.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Trace.V1.Traces Traces {
get { return traces_; }
set {
traces_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PatchTracesRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PatchTracesRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (!object.Equals(Traces, other.Traces)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (traces_ != null) hash ^= Traces.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ProjectId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ProjectId);
}
if (traces_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Traces);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (traces_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Traces);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PatchTracesRequest other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.traces_ != null) {
if (traces_ == null) {
traces_ = new global::Google.Cloud.Trace.V1.Traces();
}
Traces.MergeFrom(other.Traces);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
ProjectId = input.ReadString();
break;
}
case 18: {
if (traces_ == null) {
traces_ = new global::Google.Cloud.Trace.V1.Traces();
}
input.ReadMessage(traces_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//-----------------------------------------------------------------------
// <copyright file="StreamLayoutSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using FluentAssertions;
using Reactive.Streams;
using Xunit;
using Xunit.Abstractions;
using Fuse = Akka.Streams.Implementation.Fusing.Fusing;
namespace Akka.Streams.Tests.Implementation
{
public class StreamLayoutSpec : Akka.TestKit.Xunit2.TestKit
{
#region internal classes
private class TestAtomicModule : Module
{
public TestAtomicModule(int inportCount, int outportCount)
{
var inports = Enumerable.Range(0, inportCount).Select(i => new Inlet<object>(".in" + i)).ToImmutableArray<Inlet>();
var outports = Enumerable.Range(0, outportCount).Select(i => new Outlet<object>(".out" + i)).ToImmutableArray<Outlet>();
Shape = new AmorphousShape(inports, outports);
}
public override Shape Shape { get; }
public override IModule ReplaceShape(Shape shape)
{
throw new System.NotImplementedException();
}
public override ImmutableArray<IModule> SubModules => ImmutableArray<IModule>.Empty;
public override IModule CarbonCopy()
{
throw new System.NotImplementedException();
}
public override Attributes Attributes => Attributes.None;
public override IModule WithAttributes(Attributes attributes)
{
return this;
}
}
private class TestPublisher : IPublisher<object>, ISubscription
{
internal readonly IModule Owner;
internal readonly OutPort Port;
internal IModule DownstreamModule;
internal InPort DownstreamPort;
public TestPublisher(IModule owner, OutPort port)
{
Owner = owner;
Port = port;
}
public void Subscribe(ISubscriber<object> subscriber)
{
var sub = subscriber as TestSubscriber;
if (sub != null)
{
DownstreamModule = sub.Owner;
DownstreamPort = sub.Port;
sub.OnSubscribe(this);
}
}
public void Request(long n) { }
public void Cancel() { }
}
private class TestSubscriber : ISubscriber<object>
{
internal readonly IModule Owner;
internal readonly InPort Port;
internal IModule UpstreamModule;
internal OutPort UpstreamPort;
public TestSubscriber(IModule owner, InPort port)
{
Owner = owner;
Port = port;
}
public void OnSubscribe(ISubscription subscription)
{
var publisher = subscription as TestPublisher;
if (publisher != null)
{
UpstreamModule = publisher.Owner;
UpstreamPort = publisher.Port;
}
}
public void OnError(Exception cause) { }
public void OnComplete() { }
void ISubscriber<object>.OnNext(object element) { }
public void OnNext(object element) { }
}
private class FlatTestMaterializer : MaterializerSession
{
internal ImmutableList<TestPublisher> Publishers = ImmutableList<TestPublisher>.Empty;
internal ImmutableList<TestSubscriber> Subscribers = ImmutableList<TestSubscriber>.Empty;
public FlatTestMaterializer(IModule module) : base(module, Attributes.None)
{
}
protected override object MaterializeAtomic(IModule atomic, Attributes effectiveAttributes, IDictionary<IModule, object> materializedValues)
{
foreach (var inPort in atomic.InPorts)
{
var subscriber = new TestSubscriber(atomic, inPort);
Subscribers = Subscribers.Add(subscriber);
AssignPort(inPort, UntypedSubscriber.FromTyped(subscriber));
}
foreach (var outPort in atomic.OutPorts)
{
var publisher = new TestPublisher(atomic, outPort);
Publishers = Publishers.Add(publisher);
AssignPort(outPort, UntypedPublisher.FromTyped(publisher));
}
return NotUsed.Instance;
}
}
#endregion
const int TooDeepForStack = 200;
private readonly IMaterializer materializer;
private static TestAtomicModule TestStage() => new TestAtomicModule(1, 1);
private static TestAtomicModule TestSource() => new TestAtomicModule(0, 1);
private static TestAtomicModule TestSink() => new TestAtomicModule(1, 0);
public StreamLayoutSpec(ITestOutputHelper output) : base(output: output)
{
Sys.Settings.InjectTopLevelFallback(ActorMaterializer.DefaultConfig());
materializer = ActorMaterializer.Create(Sys, ActorMaterializerSettings.Create(Sys).WithAutoFusing(false));
}
[Fact]
public void StreamLayout_should_be_able_to_model_simple_linear_stages()
{
var stage1 = TestStage();
stage1.InPorts.Count.Should().Be(1);
stage1.OutPorts.Count.Should().Be(1);
stage1.IsRunnable.Should().Be(false);
stage1.IsFlow.Should().Be(true);
stage1.IsSink.Should().Be(false);
stage1.IsSource.Should().Be(false);
var stage2 = TestStage();
var flow12 = stage1.Compose<object, object, NotUsed>(stage2, Keep.None).Wire(stage1.OutPorts.First(), stage2.InPorts.First());
flow12.InPorts.Should().BeEquivalentTo(stage1.InPorts);
flow12.OutPorts.Should().BeEquivalentTo(stage2.OutPorts);
flow12.IsRunnable.Should().Be(false);
flow12.IsFlow.Should().Be(true);
flow12.IsSink.Should().Be(false);
flow12.IsSource.Should().Be(false);
var source0 = TestSource();
source0.InPorts.Count.Should().Be(0);
source0.OutPorts.Count.Should().Be(1);
source0.IsRunnable.Should().Be(false);
source0.IsFlow.Should().Be(false);
source0.IsSink.Should().Be(false);
source0.IsSource.Should().Be(true);
var sink3 = TestSink();
sink3.InPorts.Count.Should().Be(1);
sink3.OutPorts.Count.Should().Be(0);
sink3.IsRunnable.Should().Be(false);
sink3.IsFlow.Should().Be(false);
sink3.IsSink.Should().Be(true);
sink3.IsSource.Should().Be(false);
var source012 = source0.Compose<object, object, NotUsed>(flow12, Keep.None).Wire(source0.OutPorts.First(), flow12.InPorts.First());
source012.InPorts.Count.Should().Be(0);
source012.OutPorts.Should().BeEquivalentTo(flow12.OutPorts);
source012.IsRunnable.Should().Be(false);
source012.IsFlow.Should().Be(false);
source012.IsSink.Should().Be(false);
source012.IsSource.Should().Be(true);
var sink123 = flow12.Compose<object, object, NotUsed>(sink3, Keep.None).Wire(flow12.OutPorts.First(), sink3.InPorts.First());
sink123.InPorts.Should().BeEquivalentTo(flow12.InPorts);
sink123.OutPorts.Count.Should().Be(0);
sink123.IsRunnable.Should().Be(false);
sink123.IsFlow.Should().Be(false);
sink123.IsSink.Should().Be(true);
sink123.IsSource.Should().Be(false);
var runnable0123a = source0.Compose<object, object, NotUsed>(sink123, Keep.None).Wire(source0.OutPorts.First(), sink123.InPorts.First());
var runnable0123b = source012.Compose<object, object, NotUsed>(sink3, Keep.None).Wire(source012.OutPorts.First(), sink3.InPorts.First());
var runnable0123c = source0
.Compose<object, object, NotUsed>(flow12, Keep.None).Wire(source0.OutPorts.First(), flow12.InPorts.First())
.Compose<object, object, NotUsed>(sink3, Keep.None).Wire(flow12.OutPorts.First(), sink3.InPorts.First());
runnable0123a.InPorts.Count.Should().Be(0);
runnable0123a.OutPorts.Count.Should().Be(0);
runnable0123a.IsRunnable.Should().Be(true);
runnable0123a.IsFlow.Should().Be(false);
runnable0123a.IsSink.Should().Be(false);
runnable0123a.IsSource.Should().Be(false);
}
[Fact]
public void StreamLayout_should_be_able_to_materialize_linear_layouts()
{
var source = TestSource();
var stage1 = TestStage();
var stage2 = TestStage();
var sink = TestSink();
var runnable = source
.Compose<object, object, object>(stage1, Keep.None).Wire(source.OutPorts.First(), stage1.InPorts.First())
.Compose<object, object, object>(stage2, Keep.None).Wire(stage1.OutPorts.First(), stage2.InPorts.First())
.Compose<object, object, object>(sink, Keep.None).Wire(stage2.OutPorts.First(), sink.InPorts.First());
CheckMaterialized(runnable);
}
[Fact]
public void StreamLayout_should_not_fail_materialization_when_building_a_large_graph_with_simple_computation_when_starting_from_a_Source()
{
var g = Enumerable.Range(1, TooDeepForStack)
.Aggregate(Source.Single(42).MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x));
var t = g.ToMaterialized(Sink.Seq<int>(), Keep.Both).Run(materializer);
var materialized = t.Item1;
var result = t.Item2.Result;
materialized.Should().Be(1);
result.Count.Should().Be(1);
result.Should().Contain(42);
}
[Fact]
public void StreamLayout_should_not_fail_materialization_when_building_a_large_graph_with_simple_computation_when_starting_from_a_Flow()
{
var g = Enumerable.Range(1, TooDeepForStack)
.Aggregate(Flow.Create<int>().MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x));
var t = g.RunWith(Source.Single(42).MapMaterializedValue(_ => 1), Sink.Seq<int>(), materializer);
var materialized = t.Item1;
var result = t.Item2.Result;
materialized.Should().Be(1);
result.Count.Should().Be(1);
result.Should().Contain(42);
}
[Fact]
public void StreamLayout_should_not_fail_materialization_when_building_a_large_graph_with_simple_computation_when_using_Via()
{
var g = Enumerable.Range(1, TooDeepForStack)
.Aggregate(Source.Single(42).MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x));
var t = g.ToMaterialized(Sink.Seq<int>(), Keep.Both).Run(materializer);
var materialized = t.Item1;
var result = t.Item2.Result;
materialized.Should().Be(1);
result.Count.Should().Be(1);
result.Should().Contain(42);
}
[Fact]
public void StreamLayout_should_not_fail_fusing_and_materialization_when_building_a_large_graph_with_simple_computation_when_starting_from_a_Source()
{
var g = Source.FromGraph(Fuse.Aggressive(Enumerable.Range(1, TooDeepForStack)
.Aggregate(Source.Single(42).MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x))));
var m = g.ToMaterialized(Sink.Seq<int>(), Keep.Both);
var t = m.Run(materializer);
var materialized = t.Item1;
var result = t.Item2.Result;
materialized.Should().Be(1);
result.Count.Should().Be(1);
result.Should().Contain(42);
}
[Fact]
public void StreamLayout_should_not_fail_fusing_and_materialization_when_building_a_large_graph_with_simple_computation_when_starting_from_a_Flow()
{
var g = Flow.FromGraph(Fuse.Aggressive(Enumerable.Range(1, TooDeepForStack)
.Aggregate(Flow.Create<int>().MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x))));
var t = g.RunWith(Source.Single(42).MapMaterializedValue(_ => 1), Sink.Seq<int>(), materializer);
var materialized = t.Item1;
var result = t.Item2.Result;
materialized.Should().Be(1);
result.Count.Should().Be(1);
result.Should().Contain(42);
}
[Fact]
public void StreamLayout_should_not_fail_fusing_and_materialization_when_building_a_large_graph_with_simple_computation_when_using_Via()
{
var g = Source.FromGraph(Fuse.Aggressive(Enumerable.Range(1, TooDeepForStack)
.Aggregate(Source.Single(42).MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x))));
var t = g.ToMaterialized(Sink.Seq<int>(), Keep.Both).Run(materializer);
var materialized = t.Item1;
var result = t.Item2.Result;
materialized.Should().Be(1);
result.Count.Should().Be(1);
result.Should().Contain(42);
}
private void CheckMaterialized(IModule topLevel)
{
var materializer = new FlatTestMaterializer(topLevel);
materializer.Materialize();
materializer.Publishers.IsEmpty.Should().Be(false);
materializer.Subscribers.IsEmpty.Should().Be(false);
materializer.Subscribers.Count.Should().Be(materializer.Publishers.Count);
var inToSubscriber = materializer.Subscribers.ToImmutableDictionary(x => x.Port, x => x);
var outToPublisher = materializer.Publishers.ToImmutableDictionary(x => x.Port, x => x);
foreach (var publisher in materializer.Publishers)
{
publisher.Owner.IsAtomic.Should().Be(true);
topLevel.Upstreams[publisher.DownstreamPort].Should().Be(publisher.Port);
}
foreach (var subscriber in materializer.Subscribers)
{
subscriber.Owner.IsAtomic.Should().Be(true);
topLevel.Downstreams[subscriber.UpstreamPort].Should().Be(subscriber.Port);
}
var allAtomic = GetAllAtomic(topLevel);
foreach (var atomic in allAtomic)
{
foreach (var inPort in atomic.InPorts)
{
TestSubscriber subscriber;
if (inToSubscriber.TryGetValue(inPort, out subscriber))
{
subscriber.Owner.Should().Be(atomic);
subscriber.UpstreamPort.Should().Be(topLevel.Upstreams[inPort]);
subscriber.UpstreamModule.OutPorts.Should().Contain(x => outToPublisher[x].DownstreamPort == inPort);
}
}
foreach (var outPort in atomic.OutPorts)
{
TestPublisher publisher;
if (outToPublisher.TryGetValue(outPort, out publisher))
{
publisher.Owner.Should().Be(atomic);
publisher.DownstreamPort.Should().Be(topLevel.Downstreams[outPort]);
publisher.DownstreamModule.InPorts.Should().Contain(x => inToSubscriber[x].UpstreamPort == outPort);
}
}
}
materializer.Publishers.Distinct().Count().Should().Be(materializer.Publishers.Count);
materializer.Subscribers.Distinct().Count().Should().Be(materializer.Subscribers.Count);
// no need to return anything at the moment
}
private IImmutableSet<IModule> GetAllAtomic(IModule module)
{
var group = module.SubModules.GroupBy(x => x.IsAtomic).ToDictionary(x => x.Key, x => x.ToImmutableHashSet());
ImmutableHashSet<IModule> atomics, composites;
if (!group.TryGetValue(true, out atomics)) atomics = ImmutableHashSet<IModule>.Empty;
if (!group.TryGetValue(false, out composites)) composites = ImmutableHashSet<IModule>.Empty;
return atomics.Union(composites.SelectMany(GetAllAtomic));
}
}
}
| |
// 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.
namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// DurationOperations operations.
/// </summary>
internal partial class DurationOperations : IServiceOperations<AutoRestDurationTestServiceClient>, IDurationOperations
{
/// <summary>
/// Initializes a new instance of the DurationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DurationOperations(AutoRestDurationTestServiceClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestDurationTestServiceClient
/// </summary>
public AutoRestDurationTestServiceClient Client { get; private set; }
/// <summary>
/// Get null duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<System.TimeSpan?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<System.TimeSpan?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put a positive duration value
/// </summary>
/// <param name='durationBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutPositiveDurationWithHttpMessagesAsync(System.TimeSpan durationBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("durationBody", durationBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(durationBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a positive duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<System.TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPositiveDuration", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<System.TimeSpan?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get an invalid duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<System.TimeSpan?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<System.TimeSpan?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace SvnBridge.Views
{
partial class ProxySettings
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.proxyUrlTxtBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.portTxtBox = new System.Windows.Forms.TextBox();
this.useDefaultCredetialsCheckBox = new System.Windows.Forms.CheckBox();
this.label3 = new System.Windows.Forms.Label();
this.usernameTxtBox = new System.Windows.Forms.TextBox();
this.passwordLabel = new System.Windows.Forms.Label();
this.passwordTxtBox = new System.Windows.Forms.TextBox();
this.cancelButton = new System.Windows.Forms.Button();
this.okButton = new System.Windows.Forms.Button();
this.tfsProxyUrlTxtBox = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(13, 36);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(59, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Http &Proxy:";
//
// proxyUrlTxtBox
//
this.proxyUrlTxtBox.Location = new System.Drawing.Point(79, 36);
this.proxyUrlTxtBox.Name = "proxyUrlTxtBox";
this.proxyUrlTxtBox.Size = new System.Drawing.Size(218, 20);
this.proxyUrlTxtBox.TabIndex = 3;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(13, 62);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(29, 13);
this.label2.TabIndex = 4;
this.label2.Text = "P&ort:";
//
// portTxtBox
//
this.portTxtBox.Location = new System.Drawing.Point(79, 62);
this.portTxtBox.Name = "portTxtBox";
this.portTxtBox.Size = new System.Drawing.Size(65, 20);
this.portTxtBox.TabIndex = 5;
//
// useDefaultCredetialsCheckBox
//
this.useDefaultCredetialsCheckBox.AutoSize = true;
this.useDefaultCredetialsCheckBox.Checked = true;
this.useDefaultCredetialsCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.useDefaultCredetialsCheckBox.Location = new System.Drawing.Point(16, 87);
this.useDefaultCredetialsCheckBox.Name = "useDefaultCredetialsCheckBox";
this.useDefaultCredetialsCheckBox.Size = new System.Drawing.Size(137, 17);
this.useDefaultCredetialsCheckBox.TabIndex = 6;
this.useDefaultCredetialsCheckBox.Text = "Use Default Credentials";
this.useDefaultCredetialsCheckBox.UseVisualStyleBackColor = true;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(9, 118);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(58, 13);
this.label3.TabIndex = 7;
this.label3.Text = "Username:";
//
// usernameTxtBox
//
this.usernameTxtBox.Enabled = false;
this.usernameTxtBox.Location = new System.Drawing.Point(76, 113);
this.usernameTxtBox.Name = "usernameTxtBox";
this.usernameTxtBox.Size = new System.Drawing.Size(216, 20);
this.usernameTxtBox.TabIndex = 8;
//
// passwordLabel
//
this.passwordLabel.AutoSize = true;
this.passwordLabel.Location = new System.Drawing.Point(13, 144);
this.passwordLabel.Name = "passwordLabel";
this.passwordLabel.Size = new System.Drawing.Size(56, 13);
this.passwordLabel.TabIndex = 9;
this.passwordLabel.Text = "Password:";
this.passwordLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// passwordTxtBox
//
this.passwordTxtBox.Enabled = false;
this.passwordTxtBox.Location = new System.Drawing.Point(75, 144);
this.passwordTxtBox.Name = "passwordTxtBox";
this.passwordTxtBox.PasswordChar = '*';
this.passwordTxtBox.Size = new System.Drawing.Size(217, 20);
this.passwordTxtBox.TabIndex = 10;
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(215, 170);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 12;
this.cancelButton.Text = "&Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
//
// okButton
//
this.okButton.Location = new System.Drawing.Point(132, 170);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 11;
this.okButton.Text = "&Ok";
this.okButton.UseVisualStyleBackColor = true;
//
// tfsProxyUrlTxtBox
//
this.tfsProxyUrlTxtBox.Location = new System.Drawing.Point(79, 9);
this.tfsProxyUrlTxtBox.Name = "tfsProxyUrlTxtBox";
this.tfsProxyUrlTxtBox.Size = new System.Drawing.Size(218, 20);
this.tfsProxyUrlTxtBox.TabIndex = 1;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(13, 9);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(54, 13);
this.label4.TabIndex = 0;
this.label4.Text = "&Tfs Proxy:";
//
// ProxySettings
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(303, 204);
this.Controls.Add(this.tfsProxyUrlTxtBox);
this.Controls.Add(this.label4);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.okButton);
this.Controls.Add(this.passwordTxtBox);
this.Controls.Add(this.passwordLabel);
this.Controls.Add(this.usernameTxtBox);
this.Controls.Add(this.label3);
this.Controls.Add(this.useDefaultCredetialsCheckBox);
this.Controls.Add(this.portTxtBox);
this.Controls.Add(this.label2);
this.Controls.Add(this.proxyUrlTxtBox);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ProxySettings";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "ProxySettings";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox proxyUrlTxtBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox portTxtBox;
private System.Windows.Forms.CheckBox useDefaultCredetialsCheckBox;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox usernameTxtBox;
private System.Windows.Forms.Label passwordLabel;
private System.Windows.Forms.TextBox passwordTxtBox;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.TextBox tfsProxyUrlTxtBox;
private System.Windows.Forms.Label label4;
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using Hydra.Framework;
using Hydra.SharedCache.Common;
using Hydra.SharedCache.Common.Provider.Cache;
namespace Hydra.SharedCache.Notify
{
//
// **********************************************************************
/// <summary>
/// main window.
/// </summary>
// **********************************************************************
//
public partial class MainForm
: Form
{
#region Member Variables
//
// **********************************************************************
/// <summary>
/// Notifier
/// </summary>
// **********************************************************************
//
TaskbarNotifier m_Notifier = new TaskbarNotifier();
//
// **********************************************************************
/// <summary>
/// Worker Thread
/// </summary>
// **********************************************************************
//
System.Threading.Thread m_Worker = null;
//
// **********************************************************************
/// <summary>
/// Network Form
/// </summary>
// **********************************************************************
//
private Network m_Network;
//
// **********************************************************************
/// <summary>
/// Service Controller Form
/// </summary>
// **********************************************************************
//
private WinServiceController m_ServiceController;
//
// **********************************************************************
/// <summary>
/// About Form
/// </summary>
// **********************************************************************
//
private About m_WinAbout;
//
// **********************************************************************
/// <summary>
/// Check Server Node Version Form
/// </summary>
// **********************************************************************
//
private CheckServerNodeVersion m_WinCheckServerNodeVersion;
//
// **********************************************************************
/// <summary>
/// Check HashCode Form
/// </summary>
// **********************************************************************
//
private CheckHashCode m_WinCheckHashCode;
//
// **********************************************************************
/// <summary>
/// Check Server Node Form
/// </summary>
// **********************************************************************
//
private CheckServerNodeClr m_WinCheckServerNodeClr;
#endregion
#region Constructor
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="Form1"/> class.
/// </summary>
// **********************************************************************
//
public MainForm()
{
AssemblyInfo ai = new AssemblyInfo(typeof(Hydra.SharedCache.Notify.MainForm));
Log.Debug("AsmFQName: " + ai.AsmFQName);
Log.Debug("AsmName: " + ai.AsmName);
Log.Debug("CodeBase: " + ai.CodeBase);
Log.Debug("Company: " + ai.Company);
Log.Debug("Copyright: " + ai.Copyright);
Log.Debug("Description: " + ai.Description);
Log.Debug("Product: " + ai.Product);
Log.Debug("Title: " + ai.Title);
Log.Debug("Version: " + ai.Version);
InitializeComponent();
}
#endregion Constructor
#region Delegates
//
// **********************************************************************
/// <summary>
/// Show Notifier Delegate
/// </summary>
// **********************************************************************
//
private delegate void DelegateShowNotify();
#endregion
#region Properties
//
// **********************************************************************
/// <summary>
/// Gets/sets the NetworkOverview
/// </summary>
/// <value>The network.</value>
// **********************************************************************
//
public Network Network
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (m_Network == null)
m_Network = new Network();
if (m_Network != null &&
m_Network.IsDisposed)
{
m_Network = null;
m_Network = new Network();
}
return m_Network;
}
}
//
// **********************************************************************
/// <summary>
/// Gets/sets the NetworkOverview
/// </summary>
/// <value>The service controller.</value>
// **********************************************************************
//
public WinServiceController ServiceController
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (m_ServiceController == null)
m_ServiceController = new WinServiceController();
if (m_ServiceController != null &&
m_ServiceController.IsDisposed)
{
m_ServiceController = null;
m_ServiceController = new WinServiceController();
}
return m_ServiceController;
}
}
//
// **********************************************************************
/// <summary>
/// Gets/sets the WinAbout
/// </summary>
/// <value>The win about.</value>
// **********************************************************************
//
public About WinAbout
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (m_WinAbout == null)
m_WinAbout = new About();
if (m_WinAbout != null &&
m_WinAbout.IsDisposed)
{
m_WinAbout = null;
m_WinAbout = new About();
}
return m_WinAbout;
}
}
//
// **********************************************************************
/// <summary>
/// Gets the win check server node version.
/// </summary>
/// <value>The win check server node version.</value>
// **********************************************************************
//
public CheckServerNodeVersion WinCheckServerNodeVersion
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (m_WinCheckServerNodeVersion == null)
m_WinCheckServerNodeVersion = new CheckServerNodeVersion();
if (m_WinCheckServerNodeVersion != null &&
m_WinCheckServerNodeVersion.IsDisposed)
{
m_WinCheckServerNodeVersion = null;
m_WinCheckServerNodeVersion = new CheckServerNodeVersion();
}
return m_WinCheckServerNodeVersion;
}
}
//
// **********************************************************************
/// <summary>
/// Gets the win check hash code.
/// </summary>
/// <value>The win check hash code.</value>
// **********************************************************************
//
public CheckHashCode WinCheckHashCode
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (m_WinCheckHashCode == null)
m_WinCheckHashCode = new CheckHashCode();
if (m_WinCheckHashCode != null &&
m_WinCheckHashCode.IsDisposed)
{
m_WinCheckHashCode = null;
m_WinCheckHashCode = new CheckHashCode();
}
return m_WinCheckHashCode;
}
}
//
// **********************************************************************
/// <summary>
/// Gets the win check server node CLR.
/// </summary>
/// <value>The win check server node CLR.</value>
// **********************************************************************
//
public CheckServerNodeClr WinCheckServerNodeClr
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (m_WinCheckServerNodeClr == null)
m_WinCheckServerNodeClr = new CheckServerNodeClr();
if (m_WinCheckServerNodeClr != null &&
m_WinCheckServerNodeClr.IsDisposed)
{
m_WinCheckServerNodeClr = null;
m_WinCheckServerNodeClr = new CheckServerNodeClr();
}
return m_WinCheckServerNodeClr;
}
}
#endregion
#region Private Methods
//
// **********************************************************************
/// <summary>
/// Handles the Load event of the Form1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void MainForm_Load(object sender, EventArgs e)
{
System.Drawing.Size s = new Size(14, 14);
System.Drawing.Icon i = new Icon(Resource.shared_cache, s);
notifyIcon1.Icon = i;
//
// enable all options
//
if (GetRegistryValue())
{
foreach (ToolStripItem item in contextMenuStrip1.Items)
{
if (item.Enabled == false)
{
item.Enabled = true;
}
if (item.Text.Equals("Register", StringComparison.InvariantCultureIgnoreCase))
{
item.Enabled = false;
item.Text = "Registration Done!";
}
}
}
m_Worker = new System.Threading.Thread(new System.Threading.ThreadStart(ShowNoty));
m_Worker.Start();
}
//
// **********************************************************************
/// <summary>
/// Shows the notify window.
/// </summary>
// **********************************************************************
//
private void ShowNoty()
{
if (InvokeRequired)
{
DelegateShowNotify inv = new DelegateShowNotify(ShowNoty);
Invoke(inv, new object[] { });
}
else
{
m_Notifier.Hide();
m_Notifier.SetBackgroundBitmap(Resource.skin3, Color.FromArgb(255, 0, 255));
m_Notifier.SetCloseBitmap(Resource.close, Color.FromArgb(255, 0, 255), new Point(280, 57));
m_Notifier.TitleRectangle = new Rectangle(150, 57, 125, 28);
m_Notifier.ContentRectangle = new Rectangle(75, 92, 215, 55);
m_Notifier.TitleClick += new EventHandler(TitleClick);
m_Notifier.ContentClick += new EventHandler(ContentClick);
m_Notifier.CloseClick += new EventHandler(CloseClick);
m_Notifier.CloseClickable = true;
m_Notifier.TitleClickable = false;
m_Notifier.ContentClickable = false;
m_Notifier.KeepVisibleOnMousOver = true;
m_Notifier.ReShowOnMouseOver = true;
LBSStatistic stat = LBSDistributionCache.SharedCache.GetStats();
if (stat != null)
{
m_Notifier.Show("Shared Cache Status", stat.ToNotify(), 250, 30000, 500);
}
else
{
m_Notifier.Show("Info", "No Data Available - check if service is running", 500, 3000, 500);
}
}
}
//
// **********************************************************************
/// <summary>
/// Gets the registry value.
/// </summary>
/// <returns></returns>
// **********************************************************************
//
private bool GetRegistryValue()
{
try
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"Software\LBSView\SharedCache", true);
if (key == null)
return false;
return Convert.ToBoolean(key.GetValue("RegisterForSharedCache.com", "False"));
}
catch (Exception ex)
{
return false;
}
}
#endregion
#region Events
//
// **********************************************************************
/// <summary>
/// Closes the click.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="ea">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
void CloseClick(object obj, EventArgs ea)
{
m_Notifier.Hide();
}
//
// **********************************************************************
/// <summary>
/// Titles the click.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="ea">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
void TitleClick(object obj, EventArgs ea)
{
}
//
// **********************************************************************
/// <summary>
/// Contents the click.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="ea">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
void ContentClick(object obj, EventArgs ea)
{
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the Restart menu item.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void Restart_Click(object sender, EventArgs e)
{
Common.RestartService("127.0.0.1");
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the NetworkFamily control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void NetworkFamily_Click(object sender, EventArgs e)
{
Network.Show();
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the ServiceController menu item.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void ServiceController_Click(object sender, EventArgs e)
{
ServiceController.Show();
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the Status menu item.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void Status_Click(object sender, EventArgs e)
{
ShowNoty();
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the About menu item.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void About_Click(object sender, EventArgs e)
{
WinAbout.Show();
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the Exit menu item.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void Exit_Click(object sender, EventArgs e)
{
Close();
Dispose(true);
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the toolStripMenuItem1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
Hydra.SharedCache.Registration.Register reg = new Hydra.SharedCache.Registration.Register();
reg.Show();
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the checkSharedCacheVersionToolStripMenuItem control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void checkSharedCacheVersionToolStripMenuItem_Click(object sender, EventArgs e)
{
WinCheckServerNodeVersion.Show();
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the checkUsageOfHashCodeToolStripMenuItem control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void checkUsageOfHashCodeToolStripMenuItem_Click(object sender, EventArgs e)
{
WinCheckHashCode.Show();
}
//
// **********************************************************************
/// <summary>
/// Handles the Click event of the commonRuntimeLanguageCheckToolStripMenuItem control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
// **********************************************************************
//
private void commonRuntimeLanguageCheckToolStripMenuItem_Click(object sender, EventArgs e)
{
WinCheckServerNodeClr.Show();
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// File: ITextRange.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: A part of abstract layer of TextOM.
// Defines an abstraction for a TextRange.
// As the whole abstract TextOM iot supports only read-only
// positioning operations based on ITextPointer,
// and a minimal editing capabilities - plain text
// only.
// It includes though rich (Xaml) level of serialization
// support (read-only).
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents
{
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;
using System.Globalization;
using System.IO;
/// <summary>
/// A class a portion of text content.
/// Can be contigous or disjoint; supports rectangular table ranges.
/// Provides an API for text and table editing operations.
/// </summary>
internal interface ITextRange
{
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
//......................................................
//
// Selection Building
//
//......................................................
/// <summary>
/// Determines if the passed text position is within this range.
/// </summary>
/// <param name="position">
/// The ITextPointer to test.
/// </param>
/// <returns>
/// Returns true if position is contained within this TextRange, false
/// otherwise.
/// </returns>
/// <remarks>
/// The test is inclusive depending on position's LogicalDirection.
/// If position == Start and LogicalDirection is Forward
/// or position == End and LogicalDirection is Backward,
/// then it is contained by this TextRange.
/// Empty range does not contain any position.
/// </remarks>
bool Contains(ITextPointer position);
/// <summary>
/// </summary>
void Select(ITextPointer position1, ITextPointer position2);
/// <summary>
/// Selects a word containing this position
/// </summary>
/// <param name="position">
/// A TextPointer containing a word to select.
/// </param>
void SelectWord(ITextPointer position);
// TODO:EV: Remove this method
/// <summary>
/// Selects a paragraph around the given position.
/// </summary>
/// <param name="position">
/// A position identifying a paragraph to select.
/// </param>
void SelectParagraph(ITextPointer position);
// TODO:EV: Remove this method
/// <summary>
/// Adjust the range position in preparation for handling a TextInput event
/// or equivalent.
/// </summary>
/// <param name="overType">
/// If true, when the range is empty it will delete following character.
/// Otherwise no content is affected.
/// </param>
void ApplyTypingHeuristics(bool overType);
/// <summary>
/// Gets the value of the given formatting property on this range.
/// </summary>
/// <param name="formattingProperty">
/// Property value to get.
/// </param>
/// <returns>
/// Value of the requested property.
/// </returns>
object GetPropertyValue(DependencyProperty formattingProperty);
/// <summary>
/// Returns a UIElement if it is selected by this range as its
/// only content. If there is no UIElement in the range or
/// if there is any other printable content (charaters, other
/// UIElements, structural boundaries crossed), the method returns
/// null.
/// </summary>
/// <returns></returns>
UIElement GetUIElementSelected();
// TODO:EV: Think of renaming to something like GetSingleUIElementSelected
/// <summary>
/// Detects whether the content of a range can be converted
/// to a requested format.
/// </summary>
/// <param name="dataFormat">
/// A string indicatinng a requested format.
/// </param>
/// <returns>
/// True if the given format is supported; false otherwise.
/// </returns>
bool CanSave(string dataFormat);
/// <summary>
/// Writes the contents of the range into a stream
/// in a requested format.
/// </summary>
/// <param name="stream">
/// Writeable Stream - destination for the serialized conntent.
/// </param>
/// <param name="dataFormat">
/// A string denoting one of supported data conversions:
/// DataFormats.Text, DataFormats.Xaml, DataFormats.XamlPackage,
/// DataFormats.Rtf
/// </param>
/// <remarks>
/// When dataFormat requested is not supported
/// the method will throw an exception.
/// To detect whether the given format is supported
/// call CanSave method.
/// </remarks>
void Save(Stream stream, string dataFormat);
/// <summary>
/// Writes the contents of the range into a stream
/// in a requested format.
/// </summary>
/// <param name="stream">
/// Writeable Stream - destination for the serialized conntent.
/// </param>
/// <param name="dataFormat">
/// A string denoting one of supported data conversions:
/// DataFormats.Text, DataFormats.Xaml, DataFormats.XamlPackage,
/// DataFormats.Rtf
/// </param>
/// <param name="preserveTextElements">
/// If TRUE, TextElements are saved as-is. If FALSE, they are upcast
/// to their base type. Non-complex custom properties are also saved if this parameter
/// is true. This parameter is only used for DataFormats.Xaml and
/// DataFormats.XamlPackage and is ignored by other formats.
/// </param>
/// <remarks>
/// When dataFormat requested is not supported
/// the method will throw an exception.
/// To detect whether the given format is supported
/// call CanSave method.
/// </remarks>
void Save(Stream stream, string dataFormat, bool preserveTextElements);
// TODO:EV: Consider adding CanLoad & Load methods here
//......................................................
//
// Change Notifications
//
//......................................................
/// <summary>
/// </summary>
void BeginChange();
// Like BeginChange, but does not ever create an undo unit.
// This method is called before UndoManager.Undo, and can't have
// an open undo unit while running Undo.
void BeginChangeNoUndo();
/// <summary>
/// </summary>
void EndChange();
/// <summary>
/// </summary>
void EndChange(bool disableScroll, bool skipEvents);
/// <summary>
/// </summary>
IDisposable DeclareChangeBlock();
/// <summary>
/// </summary>
IDisposable DeclareChangeBlock(bool disableScroll);
/// <summary>
/// </summary>
void NotifyChanged(bool disableScroll, bool skipEvents);
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
// If true, normalization will ignore text normalization (surrogates,
// combining marks, etc).
// Used for fine-grained control by IMEs.
bool IgnoreTextUnitBoundaries { get; }
//......................................................
//
// Boundary Positions
//
//......................................................
/// <summary>
/// The starting text position of this TextRange.
/// </summary>
ITextPointer Start { get; }
/// <summary>
/// Get the ending text position.
/// </summary>
ITextPointer End { get; }
/// <summary>
/// Return true if this text range spans no content
/// </summary>
bool IsEmpty { get; }
/// <summary>
/// Read-only collection of TextSegments, which is available when
/// TextRange is in disjoint state.
/// </summary>
List<TextSegment> TextSegments { get; }
// TODO:EV: Make table selection public
//......................................................
//
// Content - rich and plain
//
//......................................................
// true when this TextRange lives in a TextContainer (as opposed to a
// generic ITextContainer).
//
// This property is used to filter commands that have "richer" meanings
// when we're acting on a TextContainer. For instance, we can insert
// TextElements only to TextContainers, not PasswordTextContainers, etc.
bool HasConcreteTextContainer { get; }
// TODO:EV: Use this method in all the code consistently instead of (range.Start is TextPointer) test. Maybe rename the property.
/// <summary>
/// Get and set the text spanned by this text range.
/// New line characters and paragraph breaks are
/// considered as equivalent from plain text perspective,
/// so all kinds of breaks are converted into new lines
/// on get, and they converted into paragraph breaks
/// on set (if back-end store does allow that, or
/// remain new line characters otherwise).
/// </summary>
/// <remarks>
/// The selected content is collapsed before setting text.
/// Collapse assumes mering all block elements crossed by
/// this range - from the two neighboring block the preceding
/// one survives.
/// Character formatting elements are not merged.
/// They only eliminated if become empty.
/// Range is normalized before inserting a new text,
/// which means moving the both ends to the nearest
/// caret position in backward direction (as if on typing).
/// </remarks>
string Text { get; set; }
/// <summary>
/// </summary>
string Xml { get; }
// TODO:EV: Remove this method
//......................................................
//
// Table Selection Properties
//
//......................................................
bool IsTableCellRange { get; }
// TODO:EV: Make table selection public
//......................................................
//
// Change Notification Properties
//
//......................................................
/// <summary>
/// Ref count of open change blocks -- incremented/decremented
/// around BeginChange/EndChange calls.
/// </summary>
int ChangeBlockLevel { get; }
#endregion Internal Properties
//------------------------------------------------------
//
// Internal Events
//
//------------------------------------------------------
#region Internal Events
/// <summary>
/// The Changed event is fired when the range is repositioned
/// to cover a new span of text.
///
/// The EventHandler delegate is called with this TextRange
/// as the sender, and EventArgs.Empty as the argument.
/// </summary>
event EventHandler Changed;
/// <summary>
/// This is for private use only - to access the event
/// firer from TextRangeBase implementation.
/// </summary>
void FireChanged();
#endregion Internal Events
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
//......................................................
// NOTE: These members are technicaly not fields,
// they are exposed as methods and expected to be implemented
// by concrete classes.
// By their nature they belong to "private fields"
// category - they would be fields if TextRangeBase
// would be an abstact class.
// They are supposed to be used only in TextRangeBase,
// while implementing classes must only provide a storage
// for them.
//......................................................
#region Private Fields
/// <summary>
/// Autoincremented counter of content change for the
/// underlying TextContainer
/// </summary>
uint _ContentGeneration { get; set; }
/// <summary>
/// Defines a state of this text range
/// </summary>
bool _IsTableCellRange { get; set; }
/// <summary>
/// Read-only collection of TextSegments, which is available when
/// TextRange is in disjoint state.
/// </summary>
List<TextSegment> _TextSegments { get; set; }
/// <summary>
/// Used by TextRangeBase to track the outermost change block.
/// </summary>
int _ChangeBlockLevel { get; set; }
/// <summary>
/// Object used by TextRangeBase to track undo status.
/// </summary>
ChangeBlockUndoRecord _ChangeBlockUndoRecord { get; set; }
/// <summary>
/// </summary>
bool _IsChanged { get; set; }
#endregion Public Events
}
}
| |
//
// Copyright (c) Microsoft Corporation. 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 Microsoft.PowerShell.PackageManagement.Cmdlets {
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Utility;
using System.Diagnostics.CodeAnalysis;
using Microsoft.PackageManagement.Internal.Packaging;
using Microsoft.PackageManagement.Internal.Utility.Async;
using Microsoft.PackageManagement.Internal.Utility.Collections;
using Microsoft.PackageManagement.Internal.Utility.Extensions;
using Microsoft.PackageManagement.Packaging;
[Cmdlet(VerbsCommon.Get, Constants.Nouns.PackageNoun, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=517135")]
public class GetPackage : CmdletWithSearch {
private readonly Dictionary<string, bool> _namesProcessed = new Dictionary<string, bool>();
private readonly string _newSoftwareIdentityTypeName = "Microsoft.PackageManagement.Packaging.SoftwareIdentity#GetPackage";
public GetPackage()
: base(new[] {
OptionCategory.Provider, OptionCategory.Install
}) {
}
protected override IEnumerable<string> ParameterSets {
get {
return new[] {""};
}
}
protected IEnumerable<string> UnprocessedNames {
get {
return _namesProcessed.Keys.Where(each => !_namesProcessed[each]);
}
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Considered. Still No.")]
protected bool IsPackageInVersionRange(SoftwareIdentity pkg) {
if (RequiredVersion != null && SoftwareIdentityVersionComparer.CompareVersions(pkg.VersionScheme, pkg.Version, RequiredVersion) != 0) {
return false;
}
if (MinimumVersion != null && SoftwareIdentityVersionComparer.CompareVersions(pkg.VersionScheme, pkg.Version, MinimumVersion) < 0) {
return false;
}
if (MaximumVersion != null && SoftwareIdentityVersionComparer.CompareVersions(pkg.VersionScheme, pkg.Version, MaximumVersion) > 0) {
return false;
}
return true;
}
protected bool IsDuplicate(SoftwareIdentity package) {
// todo: add duplicate checking (need canonical ids)
return false;
}
public override bool ProcessRecordAsync() {
ValidateVersion(RequiredVersion);
ValidateVersion(MinimumVersion);
ValidateVersion(MaximumVersion);
// If AllVersions is specified, make sure other version parameters are not supplied
if (AllVersions.IsPresent)
{
if ((!string.IsNullOrWhiteSpace(RequiredVersion)) || (!string.IsNullOrWhiteSpace(MinimumVersion)) || (!string.IsNullOrWhiteSpace(MaximumVersion)))
{
Error(Constants.Errors.AllVersionsCannotBeUsedWithOtherVersionParameters);
}
}
// Cannot have Max/Min version parameters with RequiredVersion
if (RequiredVersion != null)
{
if ((!string.IsNullOrWhiteSpace(MaximumVersion)) || (!string.IsNullOrWhiteSpace(MinimumVersion)))
{
Error(Constants.Errors.VersionRangeAndRequiredVersionCannotBeSpecifiedTogether);
}
}
// keep track of what package names the user asked for.
if (!Name.IsNullOrEmpty()) {
foreach (var name in Name) {
_namesProcessed.GetOrAdd(name, () => false);
}
}
var requests = (Name.IsNullOrEmpty() ?
// if the user didn't specify any names
SelectedProviders.Select(pv => new {
query = "?",
packages = pv.GetInstalledPackages("",RequiredVersion, MinimumVersion, MaximumVersion, this.ProviderSpecific(pv)).CancelWhen(CancellationEvent.Token)
}) :
// if the user specified a name,
SelectedProviders.SelectMany(pv => {
// for a given provider, if we get an error, we want just that provider to stop.
var host = this.ProviderSpecific(pv);
return Name.Select(name => new {
query = name,
packages = pv.GetInstalledPackages(name, RequiredVersion, MinimumVersion, MaximumVersion, host).CancelWhen(CancellationEvent.Token)
});
})).ToArray();
var potentialPackagesToProcess = new System.Collections.ObjectModel.Collection<SoftwareIdentity>();
while (WaitForActivity(requests.Select(each => each.packages))) {
// keep processing while any of the the queries is still going.
foreach (var result in requests.Where(each => each.packages.HasData)) {
// look only at requests that have data waiting.
foreach (var package in result.packages.GetConsumingEnumerable()) {
// process the results for that set.
if (IsPackageInVersionRange(package)) {
// it only counts if the package is in the range we're looking for.
// mark down that we found something for that query
_namesProcessed.AddOrSet(result.query, true);
// If AllVersions is specified, process the package immediately
if (AllVersions)
{
// Process the package immediately if -AllVersions are required
ProcessPackage(package);
}
else
{
// Save to perform post-processing to eliminate duplicate versions and group by Name
potentialPackagesToProcess.Add(package);
}
}
}
}
// just work with whatever is not yet consumed
requests = requests.FilterWithFinalizer(each => each.packages.IsConsumed, each => each.packages.Dispose()).ToArray();
} // end of WaitForActivity()
// Perform post-processing only if -AllVersions is not specified
if (!AllVersions)
{
// post processing the potential packages as we have to display only
// 1 package per name (note multiple versions of the same package may be installed)
// In general, it is good practice to show only the latest one.
// However there are cases when the same package can be found by different providers. in that case, we will show
// the packages from different providers even through they have the same package name. This is important because uninstall-package
// inherits from get-package, so that when the first provider does not implement the uninstall-package(), such as Programs, others will
// perform the uninstall.
//grouping packages by package name first
var enumerablePotentialPackages = from p in potentialPackagesToProcess
group p by p.Name
into grouping
select grouping.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance);
//each group of packages with the same name, return the first if the packages are from the same provider
foreach (var potentialPackage in enumerablePotentialPackages.Select(pp => (from p in pp
group p by p.ProviderName
into grouping
select grouping.OrderByDescending(each => each, SoftwareIdentityVersionComparer.Instance).First())).SelectMany(pkgs => pkgs.ToArray())) {
ProcessPackage(potentialPackage);
}
}
return true;
}
protected virtual void ProcessPackage(SoftwareIdentity package) {
// Check for duplicates
if (!IsDuplicate(package)) {
// Display the SoftwareIdentity object in a format: Name, Version, Source and Provider
var swidTagAsPsobj = PSObject.AsPSObject(package);
var noteProperty = new PSNoteProperty("PropertyOfSoftwareIdentity", "PropertyOfSoftwareIdentity");
swidTagAsPsobj.Properties.Add(noteProperty, true);
swidTagAsPsobj.TypeNames.Insert(0, _newSoftwareIdentityTypeName);
WriteObject(swidTagAsPsobj);
}
}
public override bool EndProcessingAsync() {
// give out errors for any package names that we don't find anything for.
foreach (var name in UnprocessedNames) {
Error(Constants.Errors.NoMatchFound, name);
}
return true;
}
//use wide Source column for get-package
protected override bool UseDefaultSourceFormat {
get {
return false;
}
}
}
}
| |
// 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.
#if !netstandard
using Internal.Runtime.CompilerServices;
#else
using System.Runtime.CompilerServices;
#endif
namespace System.Buffers.Text
{
/// <summary>
/// Methods to parse common data types to Utf8 strings.
/// </summary>
public static partial class Utf8Parser
{
/// <summary>
/// Parses a SByte at the start of a Utf8 string.
/// </summary>
/// <param name="text">The Utf8 string to parse</param>
/// <param name="value">Receives the parsed value</param>
/// <param name="bytesConsumed">On a successful parse, receives the length in bytes of the substring that was parsed </param>
/// <param name="standardFormat">Expected format of the Utf8 string</param>
/// <returns>
/// true for success. "bytesConsumed" contains the length in bytes of the substring that was parsed.
/// false if the string was not syntactically valid or an overflow or underflow occurred. "bytesConsumed" is set to 0.
/// </returns>
/// <remarks>
/// Formats supported:
/// G/g (default)
/// D/d 32767
/// N/n 32,767
/// X/x 7fff
/// </remarks>
/// <exceptions>
/// <cref>System.FormatException</cref> if the format is not valid for this data type.
/// </exceptions>
[CLSCompliant(false)]
public static bool TryParse(ReadOnlySpan<byte> text, out sbyte value, out int bytesConsumed, char standardFormat = default)
{
switch (standardFormat)
{
case (default):
case 'g':
case 'G':
case 'd':
case 'D':
return TryParseSByteD(text, out value, out bytesConsumed);
case 'n':
case 'N':
return TryParseSByteN(text, out value, out bytesConsumed);
case 'x':
case 'X':
value = default;
return TryParseByteX(text, out Unsafe.As<sbyte, byte>(ref value), out bytesConsumed);
default:
return ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed);
}
}
/// <summary>
/// Parses an Int16 at the start of a Utf8 string.
/// </summary>
/// <param name="text">The Utf8 string to parse</param>
/// <param name="value">Receives the parsed value</param>
/// <param name="bytesConsumed">On a successful parse, receives the length in bytes of the substring that was parsed </param>
/// <param name="standardFormat">Expected format of the Utf8 string</param>
/// <returns>
/// true for success. "bytesConsumed" contains the length in bytes of the substring that was parsed.
/// false if the string was not syntactically valid or an overflow or underflow occurred. "bytesConsumed" is set to 0.
/// </returns>
/// <remarks>
/// Formats supported:
/// G/g (default)
/// D/d 32767
/// N/n 32,767
/// X/x 7fff
/// </remarks>
/// <exceptions>
/// <cref>System.FormatException</cref> if the format is not valid for this data type.
/// </exceptions>
public static bool TryParse(ReadOnlySpan<byte> text, out short value, out int bytesConsumed, char standardFormat = default)
{
switch (standardFormat)
{
case (default):
case 'g':
case 'G':
case 'd':
case 'D':
return TryParseInt16D(text, out value, out bytesConsumed);
case 'n':
case 'N':
return TryParseInt16N(text, out value, out bytesConsumed);
case 'x':
case 'X':
value = default;
return TryParseUInt16X(text, out Unsafe.As<short, ushort>(ref value), out bytesConsumed);
default:
return ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed);
}
}
/// <summary>
/// Parses an Int32 at the start of a Utf8 string.
/// </summary>
/// <param name="text">The Utf8 string to parse</param>
/// <param name="value">Receives the parsed value</param>
/// <param name="bytesConsumed">On a successful parse, receives the length in bytes of the substring that was parsed </param>
/// <param name="standardFormat">Expected format of the Utf8 string</param>
/// <returns>
/// true for success. "bytesConsumed" contains the length in bytes of the substring that was parsed.
/// false if the string was not syntactically valid or an overflow or underflow occurred. "bytesConsumed" is set to 0.
/// </returns>
/// <remarks>
/// Formats supported:
/// G/g (default)
/// D/d 32767
/// N/n 32,767
/// X/x 7fff
/// </remarks>
/// <exceptions>
/// <cref>System.FormatException</cref> if the format is not valid for this data type.
/// </exceptions>
public static bool TryParse(ReadOnlySpan<byte> text, out int value, out int bytesConsumed, char standardFormat = default)
{
switch (standardFormat)
{
case (default):
case 'g':
case 'G':
case 'd':
case 'D':
return TryParseInt32D(text, out value, out bytesConsumed);
case 'n':
case 'N':
return TryParseInt32N(text, out value, out bytesConsumed);
case 'x':
case 'X':
value = default;
return TryParseUInt32X(text, out Unsafe.As<int, uint>(ref value), out bytesConsumed);
default:
return ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed);
}
}
/// <summary>
/// Parses an Int64 at the start of a Utf8 string.
/// </summary>
/// <param name="text">The Utf8 string to parse</param>
/// <param name="value">Receives the parsed value</param>
/// <param name="bytesConsumed">On a successful parse, receives the length in bytes of the substring that was parsed </param>
/// <param name="standardFormat">Expected format of the Utf8 string</param>
/// <returns>
/// true for success. "bytesConsumed" contains the length in bytes of the substring that was parsed.
/// false if the string was not syntactically valid or an overflow or underflow occurred. "bytesConsumed" is set to 0.
/// </returns>
/// <remarks>
/// Formats supported:
/// G/g (default)
/// D/d 32767
/// N/n 32,767
/// X/x 7fff
/// </remarks>
/// <exceptions>
/// <cref>System.FormatException</cref> if the format is not valid for this data type.
/// </exceptions>
public static bool TryParse(ReadOnlySpan<byte> text, out long value, out int bytesConsumed, char standardFormat = default)
{
switch (standardFormat)
{
case (default):
case 'g':
case 'G':
case 'd':
case 'D':
return TryParseInt64D(text, out value, out bytesConsumed);
case 'n':
case 'N':
return TryParseInt64N(text, out value, out bytesConsumed);
case 'x':
case 'X':
value = default;
return TryParseUInt64X(text, out Unsafe.As<long, ulong>(ref value), out bytesConsumed);
default:
return ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed);
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Input.Inking;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Streams;
using SDKTemplate;
namespace simpleInk
{
/// <summary>
/// This page demonstrates the usage of the InkPresenter APIs. It shows the following functionality:
/// - Load/Save ink files
/// - Usage of drawing attributes
/// - Input type switching to enable/disable touch
/// - Pen tip transform, highlighter and different pen colors and sizes
/// </summary>
public sealed partial class Scenario1 : Page
{
private MainPage rootPage;
const int initialPenSize = 4;
const int penSizeIncrement = 5;
int penSize = initialPenSize;
public Scenario1()
{
this.InitializeComponent();
InkDrawingAttributes drawingAttributes = new InkDrawingAttributes();
drawingAttributes.Color = Windows.UI.Colors.Red;
drawingAttributes.Size = new Size(penSize, penSize);
drawingAttributes.IgnorePressure = false;
drawingAttributes.FitToCurve = true;
inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse | Windows.UI.Core.CoreInputDeviceTypes.Pen;
inkCanvas.InkPresenter.StrokesCollected += InkPresenter_StrokesCollected;
inkCanvas.InkPresenter.StrokesErased += InkPresenter_StrokesErased;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
Output.Width = Window.Current.Bounds.Width;
Output.Height = Window.Current.Bounds.Height / 2;
inkCanvas.Width = Window.Current.Bounds.Width;
inkCanvas.Height = Window.Current.Bounds.Height / 2;
}
private void InkPresenter_StrokesErased(InkPresenter sender, InkStrokesErasedEventArgs args)
{
rootPage.NotifyUser(args.Strokes.Count + " strokes erased!", SDKTemplate.NotifyType.StatusMessage);
}
private void InkPresenter_StrokesCollected(Windows.UI.Input.Inking.InkPresenter sender, Windows.UI.Input.Inking.InkStrokesCollectedEventArgs args)
{
rootPage.NotifyUser(args.Strokes.Count + " strokes collected!", SDKTemplate.NotifyType.StatusMessage);
}
void OnPenColorChanged(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (inkCanvas != null)
{
InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
// Use button's background to set new pen's color
var btnSender = sender as Windows.UI.Xaml.Controls.Button;
var brush = btnSender.Background as Windows.UI.Xaml.Media.SolidColorBrush;
drawingAttributes.Color = brush.Color;
inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
}
}
void OnPenThicknessChanged(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (inkCanvas != null)
{
InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
penSize = initialPenSize + penSizeIncrement * PenThickness.SelectedIndex;
string value = ((ComboBoxItem)PenType.SelectedItem).Content.ToString();
if (value == "Highlighter" || value == "Calligraphy")
{
// Make the pen tip rectangular for highlighter and calligraphy pen
drawingAttributes.Size = new Size(penSize, penSize * 2);
}
else
{
drawingAttributes.Size = new Size(penSize, penSize);
}
inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
}
}
void OnPenTypeChanged(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (inkCanvas != null)
{
InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
string value = ((ComboBoxItem)PenType.SelectedItem).Content.ToString();
if (value == "Ballpoint")
{
drawingAttributes.Size = new Size(penSize, penSize);
drawingAttributes.PenTip = PenTipShape.Circle;
drawingAttributes.DrawAsHighlighter = false;
drawingAttributes.PenTipTransform = System.Numerics.Matrix3x2.Identity;
}
else if (value == "Highlighter")
{
// Make the pen rectangular for highlighter
drawingAttributes.Size = new Size(penSize, penSize * 2);
drawingAttributes.PenTip = PenTipShape.Rectangle;
drawingAttributes.DrawAsHighlighter = true;
drawingAttributes.PenTipTransform = System.Numerics.Matrix3x2.Identity;
}
if (value == "Calligraphy")
{
drawingAttributes.Size = new Size(penSize, penSize * 2);
drawingAttributes.PenTip = PenTipShape.Rectangle;
drawingAttributes.DrawAsHighlighter = false;
// Set a 45 degree rotation on the pen tip
double radians = 45.0 * Math.PI / 180;
drawingAttributes.PenTipTransform = System.Numerics.Matrix3x2.CreateRotation((float)radians);
}
inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
}
}
void OnClear(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
inkCanvas.InkPresenter.StrokeContainer.Clear();
rootPage.NotifyUser("Cleared Canvas", SDKTemplate.NotifyType.StatusMessage);
}
async void OnSaveAsync(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
// We don't want to save an empty file
if (inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count > 0)
{
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
savePicker.FileTypeChoices.Add("Gif with embedded ISF", new System.Collections.Generic.List<string> { ".gif" });
Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
if (null != file)
{
try
{
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);
}
rootPage.NotifyUser(inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count + " strokes saved!", SDKTemplate.NotifyType.StatusMessage);
}
catch(Exception ex)
{
rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
}
}
}
else
{
rootPage.NotifyUser("There is no ink to save.", SDKTemplate.NotifyType.ErrorMessage);
}
}
async void OnLoadAsync(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".gif");
openPicker.FileTypeFilter.Add(".isf");
Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();
if (null != file)
{
using (var stream = await file.OpenSequentialReadAsync())
{
try
{
await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(stream);
}
catch(Exception ex)
{
rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
}
}
rootPage.NotifyUser(inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count + " strokes loaded!", SDKTemplate.NotifyType.StatusMessage);
}
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse | Windows.UI.Core.CoreInputDeviceTypes.Pen | Windows.UI.Core.CoreInputDeviceTypes.Touch;
rootPage.NotifyUser("Enable Touch Inking", SDKTemplate.NotifyType.StatusMessage);
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse | Windows.UI.Core.CoreInputDeviceTypes.Pen;
rootPage.NotifyUser("Disable Touch Inking", SDKTemplate.NotifyType.StatusMessage);
}
}
}
| |
/*
* SubSonic - http://subsonicproject.com
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
using System;
using System.Data;
using System.Web.UI.WebControls;
using SubSonic.Utilities;
namespace SubSonic
{
/// <summary>
/// Base class for read-only, data-aware objects (Views).
/// </summary>
/// <typeparam name="T"></typeparam>
[Serializable]
public abstract class ReadOnlyRecord<T> : RecordBase<T>, IReadOnlyRecord where T : RecordBase<T>, new()
{
#region Fetchers
/// <summary>
/// Loads a the AbstractRecord by specifying an arbitrary column name and value
/// as the retrieval criteria
/// </summary>
/// <param name="columnName">Name of the column to use as the retrieval key</param>
/// <param name="paramValue">Value of the column to use as the retrieval criteria</param>
public void LoadByParam(string columnName, object paramValue)
{
MarkOld();
IDataReader rdr = null;
try
{
rdr = new Query(BaseSchema).AddWhere(columnName, paramValue).ExecuteReader();
if (rdr.Read())
Load(rdr);
else {
MarkNew();
IsLoaded = false;
}
}
finally
{
if(rdr != null)
rdr.Close();
}
}
/// <summary>
/// Loads the record by fetching the underlying record with the passed value as the primary key
/// </summary>
/// <param name="keyID">The primary key value to retrieve the record for</param>
public void LoadByKey(object keyID)
{
MarkOld();
IDataReader rdr = null;
try
{
Query q = new Query(BaseSchema).AddWhere(BaseSchema.PrimaryKey.ColumnName, keyID);
rdr = q.ExecuteReader();
if (rdr.Read())
Load(rdr);
else
{
MarkNew();
IsLoaded = false;
}
}
finally
{
if(rdr != null)
rdr.Close();
}
}
/// <summary>
/// Returns a record for this keyValue
/// </summary>
/// <param name="keyValue">Key Value</param>
/// <returns></returns>
public static T FetchByID(int keyValue)
{
return FetchByIdInternal(keyValue);
}
/// <summary>
/// Returns a record for this keyValue
/// </summary>
/// <param name="keyValue">Key Value</param>
/// <returns></returns>
public static T FetchByID(int? keyValue)
{
return FetchByIdInternal(keyValue);
}
/// <summary>
/// Returns a record for this keyValue
/// </summary>
/// <param name="keyValue">Key Value</param>
/// <returns></returns>
public static T FetchByID(long keyValue)
{
return FetchByIdInternal(keyValue);
}
/// <summary>
/// Returns a record for this keyValue
/// </summary>
/// <param name="keyValue">Key Value</param>
/// <returns></returns>
public static T FetchByID(long? keyValue)
{
return FetchByIdInternal(keyValue);
}
/// <summary>
/// Returns a record for this keyValue
/// </summary>
/// <param name="keyValue">Key Value</param>
/// <returns></returns>
public static T FetchByID(decimal keyValue)
{
return FetchByIdInternal(keyValue);
}
/// <summary>
/// Returns a record for this keyValue
/// </summary>
/// <param name="keyValue">Key Value</param>
/// <returns></returns>
public static T FetchByID(decimal? keyValue)
{
return FetchByIdInternal(keyValue);
}
/// <summary>
/// Returns a record for this keyValue
/// </summary>
/// <param name="keyValue">Key Value</param>
/// <returns></returns>
public static T FetchByID(Guid keyValue)
{
return FetchByIdInternal(keyValue);
}
/// <summary>
/// Returns a record for this keyValue
/// </summary>
/// <param name="keyValue">Key Value</param>
/// <returns></returns>
public static T FetchByID(Guid? keyValue)
{
return FetchByIdInternal(keyValue);
}
/// <summary>
/// Returns a record for this keyValue
/// </summary>
/// <param name="keyValue">Key Value</param>
/// <returns></returns>
public static T FetchByID(string keyValue)
{
return FetchByIdInternal(keyValue);
}
/// <summary>
/// Returns a record for this keyValue
/// </summary>
/// <param name="keyValue">Key Value</param>
/// <returns></returns>
private static T FetchByIdInternal(object keyValue)
{
if(keyValue == null)
return null;
// makes sure the table schema is loaded
T item = new T();
// build the query
Query q = new Query(BaseSchema).WHERE(BaseSchema.PrimaryKey.ColumnName, Comparison.Equals, keyValue);
// load the reader
using(IDataReader rdr = DataService.GetSingleRecordReader(q.BuildSelectCommand()))
{
if(rdr.Read())
item.Load(rdr);
rdr.Close();
}
if(!item._isNew && item.IsLoaded)
return item;
return null;
}
/// <summary>
/// Returns all records for this table
/// </summary>
/// <returns>IDataReader</returns>
public static IDataReader FetchAll()
{
Query q = new Query(BaseSchema);
CheckLogicalDelete(q);
IDataReader rdr = DataService.GetReader(q.BuildSelectCommand());
return rdr;
}
/// <summary>
/// Returns all records for this table, ordered
/// </summary>
/// <returns>Generic Typed List</returns>
/// <param name="orderBy">OrderBy object used to specify sort behavior</param>
public static IDataReader FetchAll(OrderBy orderBy)
{
Query q = new Query(BaseSchema)
{
OrderBy = orderBy
};
CheckLogicalDelete(q);
return DataService.GetReader(q.BuildSelectCommand());
}
/// <summary>
/// Returns all records for the given column/parameter, ordered by the passed in orderBy
/// The expression for this is always "column=parameter"
/// </summary>
/// <param name="columnName">Name of the column to use in parameter statement</param>
/// <param name="oValue">Value of the column</param>
/// <param name="orderBy">Ordering of results</param>
/// <returns>IDataReader</returns>
public static IDataReader FetchByParameter(string columnName, object oValue, OrderBy orderBy)
{
Query q = new Query(BaseSchema)
{
OrderBy = orderBy
};
q.AddWhere(columnName, oValue);
CheckLogicalDelete(q);
return DataService.GetReader(q.BuildSelectCommand());
}
/// <summary>
/// Returns all records for the given column/parameter
/// The expression for this is always "column=parameter"
/// </summary>
/// <param name="columnName">The name of the column, as defined in the database</param>
/// <param name="oValue">The value to match when fetching</param>
/// <returns>IDataReader</returns>
public static IDataReader FetchByParameter(string columnName, object oValue)
{
Query q = new Query(BaseSchema);
q.AddWhere(columnName, oValue);
CheckLogicalDelete(q);
return DataService.GetReader(q.BuildSelectCommand());
}
/// <summary>
/// Returns all records for the given column, comparison operator, and parameter
/// This overload is used for queries that don't use and '=' operator, i.e. IS, IS NOT, etc.
/// </summary>
/// <param name="columnName">The name of the column, as defined in the database</param>
/// <param name="comparison">The comparison operator used for the query</param>
/// <param name="oValue">The value to match when fetching</param>
/// <returns>IDataReader</returns>
public static IDataReader FetchByParameter(string columnName, Comparison comparison, object oValue)
{
Query q = new Query(BaseSchema);
q.AddWhere(columnName, comparison, oValue);
CheckLogicalDelete(q);
return DataService.GetReader(q.BuildSelectCommand());
}
/// <summary>
/// Returns all records for the given column, comparison operator, and parameter
/// in the order specified with the OrderBy parameter.
/// This overload is used for queries that don't use and '=' operator, i.e. IS, IS NOT, etc,
/// </summary>
/// <param name="columnName">The name of the column, as defined in the database</param>
/// <param name="comparison">The comparison operator used for the query</param>
/// <param name="oValue">The value to match when fetching</param>
/// <param name="orderBy">An OrderBy object used determine the order of results</param>
/// <returns>IDataReader</returns>
public static IDataReader FetchByParameter(string columnName, Comparison comparison, object oValue, OrderBy orderBy)
{
Query q = new Query(BaseSchema);
q.AddWhere(columnName, comparison, oValue);
q.OrderBy = orderBy;
CheckLogicalDelete(q);
return DataService.GetReader(q.BuildSelectCommand());
}
/// <summary>
/// Returns all records for the given Query object
/// </summary>
/// <param name="query">Query for complex records</param>
/// <returns>Generic Typed List</returns>
public static IDataReader FetchByQuery(Query query)
{
CheckLogicalDelete(query);
return DataService.GetReader(query.BuildSelectCommand());
}
/// <summary>
/// Uses the passed-in object as a parameter set. Does not use the created/modified fields
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
public static IDataReader Find(T item)
{
return Find(item, null);
}
/// <summary>
/// Finds the specified item by building a SELECT query with conditions matching
/// the values of the properties on the AbstractRecord object to the columns
/// on the corresponding database table
/// </summary>
/// <param name="item">The AbstractRecord derived type</param>
/// <param name="orderBy">The OrberBy object used to return results</param>
/// <returns></returns>
public static IDataReader Find(T item, OrderBy orderBy)
{
Query q = new Query(BaseSchema);
CheckLogicalDelete(q);
// retrieve data from database
foreach(TableSchema.TableColumn col in BaseSchema.Columns)
{
string columnName = col.ColumnName;
object columnValue = item.GetColumnValue<object>(columnName);
if(!Utility.IsAuditField(columnName))
{
object defaultValue = String.Empty;
switch(col.DataType)
{
case DbType.Boolean:
defaultValue = false;
break;
case DbType.Currency:
case DbType.Decimal:
case DbType.Int16:
case DbType.Double:
case DbType.Int32:
defaultValue = 0;
break;
case DbType.Date:
case DbType.DateTime:
defaultValue = new DateTime(1900, 1, 1);
break;
case DbType.Guid:
defaultValue = Guid.Empty;
break;
}
if(columnValue != null)
{
if(!columnValue.Equals(defaultValue))
q.AddWhere(columnName, columnValue);
}
}
}
if(orderBy != null)
q.OrderBy = orderBy;
return DataService.GetReader(q.BuildSelectCommand());
}
/// <summary>
/// Return a new Query object based on the underlying TableSchema.Table type of the record
/// </summary>
/// <returns></returns>
public static Query Query()
{
new T();
return new Query(table);
}
#endregion
#region Command Builder
/// <summary>
/// Gets the select command used to retrieve the AbstractRecord object.
/// </summary>
/// <returns></returns>
public QueryCommand GetSelectCommand()
{
return ActiveHelper<T>.GetSelectCommand(this);
}
#endregion
#region Utility
/// <summary>
/// If this object has a logical delete column, this method will append in the required parameter to avoid returning
/// deleted records
/// </summary>
/// <param name="q">The q.</param>
internal static void CheckLogicalDelete(Query q)
{
q.CheckLogicalDelete();
}
/// <summary>
/// Returns an ordered ListItemCollection for use with DropDowns, RadioButtonLists, and CheckBoxLists
/// </summary>
/// <returns></returns>
public static ListItemCollection GetListItems()
{
// get the textColumn based on position
// which should be the second column of the table
string textColumn = BaseSchema.Descriptor.ColumnName;
return GetListItems(textColumn);
}
/// <summary>
/// Returns an ordered ListItemCollection for use with DropDowns, RadioButtonLists, and CheckBoxLists
/// </summary>
/// <param name="textColumn">The name of the column which should be used as the text value column</param>
/// <returns></returns>
public static ListItemCollection GetListItems(string textColumn)
{
ListItemCollection list = new ListItemCollection();
string pkCol = BaseSchema.PrimaryKey.ColumnName;
string textCol = BaseSchema.GetColumn(textColumn).ColumnName;
// run a query retrieving the two columns
Query q = new Query(BaseSchema)
{
SelectList = String.Concat(pkCol, ",",textCol),
OrderBy = OrderBy.Asc(textCol)
};
using(IDataReader rdr = q.ExecuteReader())
{
while(rdr.Read())
{
ListItem listItem = new ListItem(rdr[1].ToString(), rdr[0].ToString());
list.Add(listItem);
}
rdr.Close();
}
return list;
}
#endregion
}
}
| |
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Security.Protocol.Tls
{
#region Enumerations
[Serializable]
internal enum AlertLevel : byte
{
Warning = 1,
Fatal = 2
}
[Serializable]
internal enum AlertDescription : byte
{
CloseNotify = 0,
UnexpectedMessage = 10,
BadRecordMAC = 20,
DecryptionFailed = 21,
RecordOverflow = 22,
DecompressionFailiure = 30,
HandshakeFailiure = 40,
NoCertificate = 41, // should be used in SSL3
BadCertificate = 42,
UnsupportedCertificate = 43,
CertificateRevoked = 44,
CertificateExpired = 45,
CertificateUnknown = 46,
IlegalParameter = 47,
UnknownCA = 48,
AccessDenied = 49,
DecodeError = 50,
DecryptError = 51,
ExportRestriction = 60,
ProtocolVersion = 70,
InsuficientSecurity = 71,
InternalError = 80,
UserCancelled = 90,
NoRenegotiation = 100
}
#endregion
internal class Alert
{
#region Fields
private AlertLevel level;
private AlertDescription description;
#endregion
#region Properties
public AlertLevel Level
{
get { return this.level; }
}
public AlertDescription Description
{
get { return this.description; }
}
public string Message
{
get { return Alert.GetAlertMessage(this.description); }
}
public bool IsWarning
{
get { return this.level == AlertLevel.Warning ? true : false; }
}
/*
public bool IsFatal
{
get { return this.level == AlertLevel.Fatal ? true : false; }
}
*/
public bool IsCloseNotify
{
get
{
if (this.IsWarning &&
this.description == AlertDescription.CloseNotify)
{
return true;
}
return false;
}
}
#endregion
#region Constructors
public Alert(AlertDescription description)
{
this.inferAlertLevel();
this.description = description;
}
public Alert(
AlertLevel level,
AlertDescription description)
{
this.level = level;
this.description = description;
}
#endregion
#region Private Methods
private void inferAlertLevel()
{
switch (description)
{
case AlertDescription.CloseNotify:
case AlertDescription.NoRenegotiation:
case AlertDescription.UserCancelled:
this.level = AlertLevel.Warning;
break;
case AlertDescription.AccessDenied:
case AlertDescription.BadCertificate:
case AlertDescription.BadRecordMAC:
case AlertDescription.CertificateExpired:
case AlertDescription.CertificateRevoked:
case AlertDescription.CertificateUnknown:
case AlertDescription.DecodeError:
case AlertDescription.DecompressionFailiure:
case AlertDescription.DecryptError:
case AlertDescription.DecryptionFailed:
case AlertDescription.ExportRestriction:
case AlertDescription.HandshakeFailiure:
case AlertDescription.IlegalParameter:
case AlertDescription.InsuficientSecurity:
case AlertDescription.InternalError:
case AlertDescription.ProtocolVersion:
case AlertDescription.RecordOverflow:
case AlertDescription.UnexpectedMessage:
case AlertDescription.UnknownCA:
case AlertDescription.UnsupportedCertificate:
default:
this.level = AlertLevel.Fatal;
break;
}
}
#endregion
#region Static Methods
public static string GetAlertMessage(AlertDescription description)
{
#if (DEBUG)
switch (description)
{
case AlertDescription.AccessDenied:
return "An inappropriate message was received.";
case AlertDescription.BadCertificate:
return "TLSCiphertext decrypted in an invalid way.";
case AlertDescription.BadRecordMAC:
return "Record with an incorrect MAC.";
case AlertDescription.CertificateExpired:
return "Certificate has expired or is not currently valid";
case AlertDescription.CertificateRevoked:
return "Certificate was revoked by its signer.";
case AlertDescription.CertificateUnknown:
return "Certificate Unknown.";
case AlertDescription.CloseNotify:
return "Connection closed";
case AlertDescription.DecodeError:
return "A message could not be decoded because some field was out of the specified range or the length of the message was incorrect.";
case AlertDescription.DecompressionFailiure:
return "The decompression function received improper input (e.g. data that would expand to excessive length).";
case AlertDescription.DecryptError:
return "TLSCiphertext decrypted in an invalid way: either it wasn`t an even multiple of the block length or its padding values, when checked, weren`t correct.";
case AlertDescription.DecryptionFailed:
return "Handshake cryptographic operation failed, including being unable to correctly verify a signature, decrypt a key exchange, or validate finished message.";
case AlertDescription.ExportRestriction:
return "Negotiation not in compliance with export restrictions was detected.";
case AlertDescription.HandshakeFailiure:
return "Unable to negotiate an acceptable set of security parameters given the options available.";
case AlertDescription.IlegalParameter:
return "A field in the handshake was out of range or inconsistent with other fields.";
case AlertDescription.InsuficientSecurity:
return "Negotiation has failed specifically because the server requires ciphers more secure than those supported by the client.";
case AlertDescription.InternalError:
return "Internal error unrelated to the peer or the correctness of the protocol makes it impossible to continue.";
case AlertDescription.NoRenegotiation:
return "Invalid renegotiation.";
case AlertDescription.ProtocolVersion:
return "Unsupported protocol version.";
case AlertDescription.RecordOverflow:
return "Invalid length on TLSCiphertext record or TLSCompressed record.";
case AlertDescription.UnexpectedMessage:
return "Invalid message received.";
case AlertDescription.UnknownCA:
return "CA can't be identified as a trusted CA.";
case AlertDescription.UnsupportedCertificate:
return "Certificate was of an unsupported type.";
case AlertDescription.UserCancelled:
return "Handshake cancelled by user.";
default:
return "";
}
#else
return "The authentication or decryption has failed.";
#endif
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.IO;
using Raksha.Asn1.X509;
using Raksha.Crypto;
using Raksha.Crypto.Digests;
using Raksha.Crypto.Engines;
using Raksha.Crypto.Modes;
using Raksha.Crypto.Parameters;
namespace Raksha.Crypto.Tls
{
public abstract class DefaultTlsClient
: TlsClient
{
protected TlsCipherFactory cipherFactory;
protected TlsClientContext context;
protected CompressionMethod selectedCompressionMethod;
protected CipherSuite selectedCipherSuite;
public DefaultTlsClient()
: this(new DefaultTlsCipherFactory())
{
}
public DefaultTlsClient(TlsCipherFactory cipherFactory)
{
this.cipherFactory = cipherFactory;
}
public virtual void Init(TlsClientContext context)
{
this.context = context;
}
public virtual CipherSuite[] GetCipherSuites()
{
return new CipherSuite[] {
CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
};
}
public virtual CompressionMethod[] GetCompressionMethods()
{
/*
* To offer DEFLATE compression, override this method:
* return new CompressionMethod[] { CompressionMethod.DEFLATE, CompressionMethod.NULL };
*/
return new CompressionMethod[] { CompressionMethod.NULL };
}
public virtual IDictionary GetClientExtensions()
{
return null;
}
public virtual void NotifySessionID(byte[] sessionID)
{
// Currently ignored
}
public virtual void NotifySelectedCipherSuite(CipherSuite selectedCipherSuite)
{
this.selectedCipherSuite = selectedCipherSuite;
}
public virtual void NotifySelectedCompressionMethod(CompressionMethod selectedCompressionMethod)
{
this.selectedCompressionMethod = selectedCompressionMethod;
}
public virtual void NotifySecureRenegotiation(bool secureRenegotiation)
{
if (!secureRenegotiation)
{
/*
* RFC 5746 3.4.
* If the extension is not present, the server does not support
* secure renegotiation; set secure_renegotiation flag to FALSE.
* In this case, some clients may want to terminate the handshake
* instead of continuing; see Section 4.1 for discussion.
*/
// throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
}
public virtual void ProcessServerExtensions(IDictionary serverExtensions)
{
}
public virtual TlsKeyExchange GetKeyExchange()
{
switch (selectedCipherSuite)
{
case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA:
return CreateRsaKeyExchange();
case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA:
return CreateDHKeyExchange(KeyExchangeAlgorithm.DH_DSS);
case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA:
return CreateDHKeyExchange(KeyExchangeAlgorithm.DH_RSA);
case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
return CreateDheKeyExchange(KeyExchangeAlgorithm.DHE_DSS);
case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
return CreateDheKeyExchange(KeyExchangeAlgorithm.DHE_RSA);
case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
return CreateECDHKeyExchange(KeyExchangeAlgorithm.ECDH_ECDSA);
case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
return CreateECDheKeyExchange(KeyExchangeAlgorithm.ECDHE_ECDSA);
case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
return CreateECDHKeyExchange(KeyExchangeAlgorithm.ECDH_RSA);
case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
return CreateECDheKeyExchange(KeyExchangeAlgorithm.ECDHE_RSA);
default:
/*
* Note: internal error here; the TlsProtocolHandler verifies that the
* server-selected cipher suite was in the list of client-offered cipher
* suites, so if we now can't produce an implementation, we shouldn't have
* offered it!
*/
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public abstract TlsAuthentication GetAuthentication();
public virtual ITlsCompression GetCompression()
{
switch (selectedCompressionMethod)
{
case CompressionMethod.NULL:
return new TlsNullCompression();
case CompressionMethod.DEFLATE:
return new TlsDeflateCompression();
default:
/*
* Note: internal error here; the TlsProtocolHandler verifies that the
* server-selected compression method was in the list of client-offered compression
* methods, so if we now can't produce an implementation, we shouldn't have
* offered it!
*/
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public virtual TlsCipher GetCipher()
{
switch (selectedCipherSuite)
{
case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
return cipherFactory.CreateCipher(context, EncryptionAlgorithm.cls_3DES_EDE_CBC, DigestAlgorithm.SHA);
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
return cipherFactory.CreateCipher(context, EncryptionAlgorithm.AES_128_CBC, DigestAlgorithm.SHA);
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
return cipherFactory.CreateCipher(context, EncryptionAlgorithm.AES_256_CBC, DigestAlgorithm.SHA);
default:
/*
* Note: internal error here; the TlsProtocolHandler verifies that the
* server-selected cipher suite was in the list of client-offered cipher
* suites, so if we now can't produce an implementation, we shouldn't have
* offered it!
*/
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
protected virtual TlsKeyExchange CreateDHKeyExchange(KeyExchangeAlgorithm keyExchange)
{
return new TlsDHKeyExchange(context, keyExchange);
}
protected virtual TlsKeyExchange CreateDheKeyExchange(KeyExchangeAlgorithm keyExchange)
{
return new TlsDheKeyExchange(context, keyExchange);
}
protected virtual TlsKeyExchange CreateECDHKeyExchange(KeyExchangeAlgorithm keyExchange)
{
return new TlsECDHKeyExchange(context, keyExchange);
}
protected virtual TlsKeyExchange CreateECDheKeyExchange(KeyExchangeAlgorithm keyExchange)
{
return new TlsECDheKeyExchange(context, keyExchange);
}
protected virtual TlsKeyExchange CreateRsaKeyExchange()
{
return new TlsRsaKeyExchange(context);
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// Section 5.3.6.2. Remove an entity
/// </summary>
[Serializable]
[XmlRoot]
public partial class RemoveEntityPdu : SimulationManagementPdu, IEquatable<RemoveEntityPdu>
{
/// <summary>
/// Identifier for the request
/// </summary>
private uint _requestID;
/// <summary>
/// Initializes a new instance of the <see cref="RemoveEntityPdu"/> class.
/// </summary>
public RemoveEntityPdu()
{
PduType = (byte)12;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(RemoveEntityPdu left, RemoveEntityPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(RemoveEntityPdu left, RemoveEntityPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += 4; // this._requestID
return marshalSize;
}
/// <summary>
/// Gets or sets the Identifier for the request
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "requestID")]
public uint RequestID
{
get
{
return this._requestID;
}
set
{
this._requestID = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
dos.WriteUnsignedInt((uint)this._requestID);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._requestID = dis.ReadUnsignedInt();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<RemoveEntityPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>");
sb.AppendLine("</RemoveEntityPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as RemoveEntityPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(RemoveEntityPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (this._requestID != obj._requestID)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._requestID.GetHashCode();
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using CsvHelper;
using CsvHelper.Configuration;
using FinTransConverterLib.Helpers;
using FinTransConverterLib.Transactions;
namespace FinTransConverterLib.FinanceEntities.Homebank {
public class HomeBank : FinanceEntity {
// supported read file types
private static readonly List<FileType> suppReadFileTypes = new List<FileType> {
FinanceEntity.PossibleFileTypes[eFileTypes.Xhb],
FinanceEntity.PossibleFileTypes[eFileTypes.PaymodePatterns],
FinanceEntity.PossibleFileTypes[eFileTypes.TransactionAssignments]
};
// supported write file types
private static readonly List<FileType> suppWriteFileTypes = new List<FileType> {
FinanceEntity.PossibleFileTypes[eFileTypes.Csv],
FinanceEntity.PossibleFileTypes[eFileTypes.Xhb]
};
private CultureInfo culture;
private List<HomeBankTransaction> duplicates;
public const string XmlTagName = "homebank";
public List<HBAccount> Accounts { get; private set; }
public List<HBPayee> Payees { get; private set; }
public List<HBCategory> Categories { get; private set; }
public List<HBAssignment> Assignments { get; private set; }
public List<HBTag> Tags { get; private set; }
public List<HBPaymodePatterns> PaymodePatterns { get; private set; }
public List<HBTransactionAssignment> TransactionAssignments { get; private set; }
public List<HomeBankTransaction> ExistingTransactions { get; private set; }
public HBAccount TargetAccount { get; private set; }
private string TargetAccountPattern;
private bool AppendDuplicates;
internal int MaxStrongLinkId { get; set; }
public HomeBank(eFinanceEntityType entityType, bool appendDuplicates = false, CultureInfo ci = null, string accountPattern = null) :
base (suppReadFileTypes, suppWriteFileTypes, entityType) {
AppendDuplicates = appendDuplicates;
culture = ci ?? (ci = CultureInfo.InvariantCulture);
duplicates = new List<HomeBankTransaction>();
Payees = new List<HBPayee>();
Categories = new List<HBCategory>();
Assignments = new List<HBAssignment>();
Tags = new List<HBTag>();
Accounts = new List<HBAccount>();
PaymodePatterns = new List<HBPaymodePatterns>();
TransactionAssignments = new List<HBTransactionAssignment>();
ExistingTransactions = new List<HomeBankTransaction>();
TargetAccountPattern = accountPattern ?? string.Empty;
TargetAccount = null;
}
protected override void Read(string path, FileType fileType) {
using(StreamReader reader = File.OpenText(path)) {
switch(fileType.Id) {
case eFileTypes.Xhb: ParseHombankSettingsFile(reader); break;
case eFileTypes.PaymodePatterns: ParsePaymodePatternsFile(reader); break;
case eFileTypes.TransactionAssignments: ParseTransactionAssignments(reader); break;
}
}
}
protected override bool Write(string path, FileType fileType) {
bool success = true;
switch(fileType.Id) {
case eFileTypes.Csv:
using(StreamWriter writer = new StreamWriter(File.OpenWrite(path))) {
success = WriteCsv(writer);
}
break;
case eFileTypes.Xhb:
success = WriteHombankSettingsFile(path);
break;
}
return success;
}
protected override void WriteFailed(string path) {
FileMode mode = (AppendDuplicates) ? FileMode.Append : FileMode.OpenOrCreate;
// Writecsv file with duplicates.
string duplicatesCsvFile = String.Format("{0}{1}{2}.duplicates.csv",
Path.GetDirectoryName(path),
Path.DirectorySeparatorChar,
Path.GetFileNameWithoutExtension(path));
using(StreamWriter output = new StreamWriter(File.Open(duplicatesCsvFile, mode, FileAccess.Write, FileShare.None))) {
using(var writer = new CsvWriter(output)) {
ConfigureCsv(writer.Configuration);
HomeBankTransaction.WriteCsvHeader(writer);
writer.NextRecord();
foreach(var transaction in duplicates) {
transaction.WriteCsv(writer, culture);
writer.NextRecord();
}
}
}
// Write text file with duplicates. This includes all values of a transaction.
string duplicatesTextFile = String.Format("{0}{1}{2}.duplicates.txt",
Path.GetDirectoryName(path),
Path.DirectorySeparatorChar,
Path.GetFileNameWithoutExtension(path));
using(StreamWriter output = new StreamWriter(File.Open(duplicatesTextFile, mode, FileAccess.Write, FileShare.None))) {
output.WriteLine(String.Format(
"Timestamp: {0}" + Environment.NewLine +
"Duplicates for target: {1}" + Environment.NewLine +
"---------------------------------------------------------------------" + Environment.NewLine +
"Duplicate transactions:",
DateTime.Now.ToString(culture), path
));
foreach(var transaction in duplicates) {
if(duplicates.LastOrDefault().Equals(transaction)) {
output.WriteLine(String.Format(
"--+ Transaction: " + Environment.NewLine + "{0}", transaction.ToString().Indent(" ")));
} else {
output.WriteLine(String.Format(
"|-+ Transaction: " + Environment.NewLine + "{0}" + Environment.NewLine + "|",
transaction.ToString().Indent("| ")));
}
}
}
}
private bool WriteCsv(TextWriter output) {
duplicates.Clear();
using(var writer = new CsvWriter(output)) {
HomeBankTransaction hbTransaction;
ConfigureCsv(writer.Configuration);
HomeBankTransaction.WriteCsvHeader(writer);
writer.NextRecord();
foreach(var transaction in Transactions) {
hbTransaction = transaction as HomeBankTransaction;
// Only add if transaction is not a duplicate.
if(transaction.IsDuplicate(ExistingTransactions)) {
duplicates.Add(hbTransaction);
} else {
// Transaction is not a duplicate.
hbTransaction.WriteCsv(writer, culture);
writer.NextRecord();
// If paymode is between accounts create a linked transaction.
if(hbTransaction.Paymode == ePaymodeType.BetweenAccounts) {
var linkedTrans = HomeBankTransaction.CreateLinkedTransaction(hbTransaction, culture);
// Only add if transaction is not a duplicate.
if(linkedTrans.IsDuplicate(ExistingTransactions)) {
duplicates.Add(linkedTrans);
} else {
// Transaction is not a duplicate.
hbTransaction.WriteCsv(writer, culture);
writer.NextRecord();
}
}
}
}
}
return duplicates.Count() <= 0;
}
private void ConfigureCsv(CsvConfiguration config) {
config.AllowComments = false;
config.CultureInfo = culture;
config.Delimiter = ";";
config.HasHeaderRecord = true;
config.IgnorePrivateAccessor = false;
config.IgnoreReadingExceptions = false;
config.IgnoreQuotes = false;
config.IsHeaderCaseSensitive = true;
config.Quote = '"';
config.SkipEmptyRecords = true;
config.TrimFields = true;
config.TrimHeaders = true;
config.WillThrowOnMissingField = true;
}
private bool WriteHombankSettingsFile(string path) {
if(TargetAccountPattern == string.Empty) {
throw new InvalidOperationException(
"Could not write to Homebank settings file, because of missing a valid target account pattern.");
}
if(TargetAccount == null) {
throw new InvalidOperationException(String.Format(
"Could not write to Homebank settings file, because there is no account matching" + Environment.NewLine +
"with the target account pattern: {0}", TargetAccountPattern
));
}
duplicates.Clear();
XmlDocument doc = new XmlDocument();
using(StreamReader xmlReader = new StreamReader(File.OpenRead(path))) {
doc.Load(xmlReader);
}
XmlNodeList rootList = doc.GetElementsByTagName(XmlTagName);
if(rootList.Count > 0) {
XmlNode homebank = rootList[0];
XmlNodeList homebankChilds = homebank.ChildNodes;
// Write new tags if there are new one.
if(Tags.Where(tag => tag.FromXml == false).Count() > 0) {
XmlNode previousNode = null;
XmlNodeList tags = doc.GetElementsByTagName(HBTag.XmlTagName);
if(tags.Count > 0) previousNode = tags[tags.Count - 1];
else {
XmlNodeList categories = doc.GetElementsByTagName(HBCategory.XmlTagName);
if(categories.Count > 0) previousNode = categories[categories.Count - 1];
else {
XmlNodeList payees = doc.GetElementsByTagName(HBPayee.XmlTagName);
if(payees.Count > 0) previousNode = payees[payees.Count - 1];
else {
XmlNodeList accounts = doc.GetElementsByTagName(HBAccount.XmlTagName);
if(accounts.Count > 0) previousNode = accounts[accounts.Count - 1];
else {
XmlNodeList props = doc.GetElementsByTagName("properties");
if(props.Count > 0) previousNode = props[props.Count - 1];
else previousNode = homebank.FirstChild;
}
}
}
}
foreach(var tag in Tags) {
// Only create new tags.
if(tag.FromXml == false) {
previousNode = homebank.InsertAfter(tag.CreateXmlElement(doc), previousNode);
}
}
}
// Write new transactions.
XmlNodeList xmlTransactions = doc.GetElementsByTagName(HomeBankTransaction.XmlTagName);
XmlNode current = null, previous;
HomeBankTransaction hbTransaction;
if(xmlTransactions.Count > 0) current = xmlTransactions[0];
else current = homebank.LastChild;
foreach(var transaction in Transactions) {
hbTransaction = transaction as HomeBankTransaction;
// Only add if transaction is not a duplicate.
if(hbTransaction.IsDuplicate(ExistingTransactions)) {
duplicates.Add(hbTransaction);
} else {
// Transaction is not a duplicate.
previous = hbTransaction.GetPreviousXmlElement(current);
previous = homebank.InsertAfter(hbTransaction.CreateXmlElement(doc), previous);
// If paymode is between accounts create a linked transaction.
if(hbTransaction.Paymode == ePaymodeType.BetweenAccounts) {
var linkedTrans = HomeBankTransaction.CreateLinkedTransaction(hbTransaction, culture);
// Only add if transaction is not a duplicate.
if(linkedTrans.IsDuplicate(ExistingTransactions)) {
duplicates.Add(linkedTrans);
} else {
// Transaction is not a duplicate.
var element = linkedTrans.CreateXmlElement(doc);
previous = homebank.InsertAfter(element, previous);
}
}
current = previous;
}
}
}
using(FileStream fileWriter = File.OpenWrite(path)) {
byte[] xmlHeader = new UTF8Encoding(true).GetBytes("<?xml version=\"1.0\"?>" + Environment.NewLine);
fileWriter.Write(xmlHeader, 0, xmlHeader.Length);
var settings = new XmlWriterSettings() {
OmitXmlDeclaration = true,
Indent = true,
NewLineChars = Environment.NewLine
};
using(XmlWriter xmlWriter = XmlWriter.Create(fileWriter, settings)) {
doc.Save(xmlWriter);
}
}
return duplicates.Count() <= 0;
}
private void ParsePaymodePatternsFile(TextReader input) {
using(XmlReader reader = XmlReader.Create(input)) {
while(reader.Read()) {
if(reader.NodeType == XmlNodeType.Element && reader.Name.Equals(HBPaymodePatterns.XmlTagName)) {
var pmps = new HBPaymodePatterns();
pmps.ParseXmlElement(reader);
PaymodePatterns.Add(pmps);
}
}
PaymodePatterns = PaymodePatterns
.OrderBy((pt) => pt.Patterns.FirstOrDefault()?.Level ?? uint.MaxValue)
.ToList();
}
}
private void ParseTransactionAssignments(TextReader input) {
using(XmlReader reader = XmlReader.Create(input)) {
reader.ReadToFollowing(HBTransactionAssignment.XmlRootTagName);
while(reader.Read()) {
if(reader.NodeType == XmlNodeType.Element && reader.Name.Equals(HBTransactionAssignment.XmlTagName)) {
var tasg = new HBTransactionAssignment();
tasg.ParseXmlElement(reader, this);
TransactionAssignments.Add(tasg);
}
}
}
TransactionAssignments = TransactionAssignments
.OrderBy(tasg => tasg.Category?.Key ?? 0)
.ToList();
}
private void ParseHombankSettingsFile(TextReader input) {
using(XmlReader reader = XmlReader.Create(input)) {
while(reader.Read()) {
if(reader.NodeType == XmlNodeType.Element) {
switch(reader.Name) {
case HBPayee.XmlTagName:
if(reader.HasAttributes) {
var payee = new HBPayee();
payee.ParseXmlElement(reader);
Payees.Add(payee);
reader.MoveToElement();
}
break;
case HBCategory.XmlTagName:
if(reader.HasAttributes) {
var category = new HBCategory();
category.ParseXmlElement(reader, Categories);
Categories.Add(category);
reader.MoveToElement();
}
break;
case HBAssignment.XmlTagName:
if(reader.HasAttributes) {
var assignment = new HBAssignment();
assignment.ParseXmlElement(reader, Payees, Categories);
Assignments.Add(assignment);
reader.MoveToElement();
}
break;
case HBAccount.XmlTagName:
if(reader.HasAttributes) {
var account = new HBAccount();
account.ParseXmlElement(reader);
Accounts.Add(account);
reader.MoveToElement();
}
break;
case HomeBankTransaction.XmlTagName:
if(reader.HasAttributes) {
var existingTransaction = new HomeBankTransaction(culture);
existingTransaction.ParseXmlElement(reader, this);
ExistingTransactions.Add(existingTransaction);
reader.MoveToElement();
}
break;
case HBTag.XmlTagName:
if(reader.HasAttributes) {
var tag = new HBTag();
tag.ParseXmlElement(reader);
Tags.Add(tag);
reader.MoveToElement();
}
break;
}
}
}
}
// Try to parse taget account.
if(TargetAccountPattern != string.Empty) {
TargetAccount = Accounts.Where((a) => {
return (new Regex(TargetAccountPattern)).Match(a.Name).Success;
}).FirstOrDefault();
}
// Try to parse maximum strong link id.
if(ExistingTransactions.Count() > 0) MaxStrongLinkId = ExistingTransactions.Max(t => t.StrongLinkId);
else MaxStrongLinkId = 0;
}
public override void Convert(IFinanceEntity finEntity) {
if(finEntity is HelloBank) {
foreach(var transaction in finEntity.Transactions) {
var helloBankTransaction = transaction as HelloBankTransaction;
var homebankTransaction = new HomeBankTransaction(culture);
homebankTransaction.ConvertTransaction(helloBankTransaction, finEntity, this);
Transactions.Add(homebankTransaction);
}
return;
}
// All other finance entity types are not supported by this class.
base.Convert(finEntity);
}
}
}
| |
//
// Photo.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Stephane Delcroix <sdelcroix@src.gnome.org>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2008-2010 Novell, Inc.
// Copyright (C) 2010 Ruben Vermeersch
// Copyright (C) 2008-2009 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Hyena;
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using Mono.Unix;
using FSpot.Core;
using FSpot.Imaging;
using FSpot.Settings;
using FSpot.Thumbnail;
using FSpot.Utils;
namespace FSpot
{
public class Photo : DbItem, IComparable, IPhoto, IPhotoVersionable
{
readonly IImageFileFactory imageFileFactory;
readonly IThumbnailService thumbnailService;
PhotoChanges changes = new PhotoChanges ();
public PhotoChanges Changes {
get{ return changes; }
set {
if (value != null)
throw new ArgumentException ("The only valid value is null");
changes = new PhotoChanges ();
}
}
// The time is always in UTC.
DateTime time;
public DateTime Time {
get { return time; }
set {
if (time == value)
return;
time = value;
changes.TimeChanged = true;
}
}
public string Name {
get { return Uri.UnescapeDataString (System.IO.Path.GetFileName (VersionUri (OriginalVersionId).AbsolutePath)); }
}
List<Tag> tags;
public Tag [] Tags {
get {
return tags.ToArray ();
}
}
bool all_versions_loaded = false;
public bool AllVersionsLoaded {
get { return all_versions_loaded; }
set {
if (value)
if (DefaultVersionId != OriginalVersionId && !versions.ContainsKey (DefaultVersionId))
DefaultVersionId = OriginalVersionId;
all_versions_loaded = value;
}
}
string description;
public string Description {
get { return description; }
set {
if (description == value)
return;
description = value;
changes.DescriptionChanged = true;
}
}
uint roll_id = 0;
public uint RollId {
get { return roll_id; }
set {
if (roll_id == value)
return;
roll_id = value;
changes.RollIdChanged = true;
}
}
uint rating;
public uint Rating {
get { return rating; }
set {
if (rating == value || value > 5)
return;
rating = value;
changes.RatingChanged = true;
}
}
#region Properties Version Management
public const int OriginalVersionId = 1;
uint highest_version_id;
readonly Dictionary<uint, PhotoVersion> versions = new Dictionary<uint, PhotoVersion> ();
public IEnumerable<IPhotoVersion> Versions {
get {
foreach (var version in versions.Values) {
yield return version;
}
}
}
public uint [] VersionIds {
get {
if (versions == null)
return Array.Empty<uint> ();
uint [] ids = new uint [versions.Count];
versions.Keys.CopyTo (ids, 0);
Array.Sort (ids);
return ids;
}
}
uint default_version_id = OriginalVersionId;
public uint DefaultVersionId {
get { return default_version_id; }
set {
if (default_version_id == value)
return;
default_version_id = value;
changes.DefaultVersionIdChanged = true;
}
}
#endregion
#region Photo Version Management
public PhotoVersion GetVersion (uint versionId)
{
return versions?[versionId];
}
// This doesn't check if a version of that name already exists,
// it's supposed to be used only within the Photo and PhotoStore classes.
public void AddVersionUnsafely (uint version_id, SafeUri base_uri, string filename, string import_md5, string name, bool is_protected)
{
versions [version_id] = new PhotoVersion (this, version_id, base_uri, filename, import_md5, name, is_protected);
highest_version_id = Math.Max (version_id, highest_version_id);
changes.AddVersion (version_id);
}
public uint AddVersion (SafeUri base_uri, string filename, string name)
{
return AddVersion (base_uri, filename, name, false);
}
public uint AddVersion (SafeUri base_uri, string filename, string name, bool is_protected)
{
if (VersionNameExists (name))
throw new ApplicationException ("A version with that name already exists");
highest_version_id ++;
string import_md5 = string.Empty; // Modified version
versions [highest_version_id] = new PhotoVersion (this, highest_version_id, base_uri, filename, import_md5, name, is_protected);
changes.AddVersion (highest_version_id);
return highest_version_id;
}
//FIXME: store versions next to originals. will crash on ro locations.
string GetFilenameForVersionName (string version_name, string extension)
{
string name_without_extension = Path.GetFileNameWithoutExtension (Name);
var escapeString = UriUtils.EscapeString (version_name, true, true, true);
return $"{name_without_extension} ({escapeString}){extension}";
}
public bool VersionNameExists (string version_name)
{
return Versions.Any (v => v.Name == version_name);
}
public SafeUri VersionUri (uint version_id)
{
if (!versions.ContainsKey (version_id))
return null;
PhotoVersion v = versions [version_id];
return v?.Uri;
}
public IPhotoVersion DefaultVersion {
get {
if (!versions.ContainsKey (DefaultVersionId))
throw new Exception ("Something is horribly wrong, this should never happen: no default version!");
return versions [DefaultVersionId];
}
}
public void SetDefaultVersion (IPhotoVersion version)
{
PhotoVersion photo_version = version as PhotoVersion;
if (photo_version == null)
throw new ArgumentException ("Not a valid version for this photo");
DefaultVersionId = photo_version.VersionId;
}
//FIXME: won't work on non file uris
public uint SaveVersion (Gdk.Pixbuf buffer, bool create_version)
{
uint version = DefaultVersionId;
using (var img = imageFileFactory.Create (DefaultVersion.Uri)) {
// Always create a version if the source is not a jpeg for now.
create_version = create_version || imageFileFactory.IsJpeg (DefaultVersion.Uri);
if (buffer == null)
throw new ApplicationException ("invalid (null) image");
if (create_version)
version = CreateDefaultModifiedVersion (DefaultVersionId, false);
try {
var versionUri = VersionUri (version);
FSpot.Utils.PixbufUtils.CreateDerivedVersion (DefaultVersion.Uri, versionUri, 95, buffer);
GetVersion (version).ImportMD5 = HashUtils.GenerateMD5 (VersionUri (version));
DefaultVersionId = version;
} catch (Exception e) {
Log.Exception (e);
if (create_version)
DeleteVersion (version);
throw;
}
}
return version;
}
public void DeleteVersion (uint versionId, bool removeOriginal)
{
DeleteVersion (versionId, removeOriginal, false);
}
public void DeleteVersion (uint versionId, bool removeOriginal = false, bool keepFile = false)
{
if (versionId == OriginalVersionId && !removeOriginal)
throw new Exception ("Cannot delete original version");
SafeUri uri = VersionUri (versionId);
var fileInfo = new FileInfo (uri.AbsolutePath);
var dirInfo = new DirectoryInfo (uri.AbsolutePath);
if (!keepFile) {
if (fileInfo.Exists)
fileInfo.Delete ();
try {
thumbnailService.DeleteThumbnails (uri);
} catch {
// ignore an error here we don't really care.
}
DeleteEmptyDirectory (dirInfo);
}
versions.Remove (versionId);
changes.RemoveVersion (versionId);
for (versionId = highest_version_id; versionId >= OriginalVersionId; versionId--) {
if (versions.ContainsKey (versionId)) {
DefaultVersionId = versionId;
break;
}
}
}
void DeleteEmptyDirectory (DirectoryInfo directory)
{
// if the directory we're dealing with is not in the
// F-Spot photos directory, don't delete anything,
// even if it is empty
string photo_uri = SafeUri.UriToFilename (FSpotConfiguration.PhotoUri.ToString ());
bool path_matched = directory.FullName.IndexOf (photo_uri) > -1;
if (directory.Name.Equals (photo_uri) || !path_matched)
return;
if (DirectoryIsEmpty (directory)) {
try {
Log.Debug ($"Removing empty directory: {directory.FullName}");
directory.Delete ();
} catch (GLib.GException e) {
// silently log the exception, but don't re-throw it
// as to not annoy the user
Log.Exception (e);
}
// check to see if the parent is empty
DeleteEmptyDirectory (directory.Parent);
}
}
bool DirectoryIsEmpty (DirectoryInfo directory)
=> !directory.EnumerateFileSystemInfos ().Any ();
public uint CreateVersion (string name, uint baseVersionId, bool create)
{
return CreateVersion (name, null, baseVersionId, create, false);
}
uint CreateVersion (string name, string extension, uint base_version_id, bool create, bool is_protected = false)
{
extension ??= VersionUri (base_version_id).GetExtension ();
SafeUri new_base_uri = DefaultVersion.BaseUri;
string filename = GetFilenameForVersionName (name, extension);
SafeUri original_uri = VersionUri (base_version_id);
SafeUri new_uri = new_base_uri.Append (filename);
string import_md5 = DefaultVersion.ImportMD5;
if (VersionNameExists (name))
throw new Exception ("This version name already exists");
if (create) {
if (File.Exists (new_uri.AbsolutePath))
throw new Exception ($"An object at this uri {new_uri} already exists");
File.Copy (original_uri.AbsolutePath, new_uri.AbsolutePath);
}
highest_version_id ++;
versions [highest_version_id] = new PhotoVersion (this, highest_version_id, new_base_uri, filename, import_md5, name, is_protected);
changes.AddVersion (highest_version_id);
return highest_version_id;
}
public uint CreateReparentedVersion (PhotoVersion version)
{
return CreateReparentedVersion (version, false);
}
public uint CreateReparentedVersion (PhotoVersion version, bool is_protected)
{
// Try to derive version name from its filename
string filename = Uri.UnescapeDataString (Path.GetFileNameWithoutExtension (version.Uri.AbsolutePath));
string parent_filename = Path.GetFileNameWithoutExtension (Name);
string name = null;
if (filename.StartsWith (parent_filename))
name = filename.Substring (parent_filename.Length).Replace ("(", "").Replace (")", "").Replace ("_", " "). Trim ();
if (string.IsNullOrEmpty (name)) {
// Note for translators: Reparented is a picture becoming a version of another one
string rep = name = Catalog.GetString ("Reparented");
for (int num = 1; VersionNameExists (name); num++) {
name = $"rep + ({num})";
}
}
highest_version_id ++;
versions [highest_version_id] = new PhotoVersion (this, highest_version_id, version.BaseUri, version.Filename, version.ImportMD5, name, is_protected);
changes.AddVersion (highest_version_id);
return highest_version_id;
}
public uint CreateDefaultModifiedVersion (uint baseVersionId, bool createFile)
{
int num = 1;
while (true) {
string name = Catalog.GetPluralString ("Modified", "Modified ({0})", num);
name = string.Format (name, num);
//SafeUri uri = GetUriForVersionName (name, System.IO.Path.GetExtension (VersionUri(baseVersionId).GetFilename()));
string filename = GetFilenameForVersionName (name, System.IO.Path.GetExtension (versions [baseVersionId].Filename));
SafeUri uri = DefaultVersion.BaseUri.Append (filename);
if (! VersionNameExists (name) && !File.Exists (uri.AbsolutePath))
return CreateVersion (name, baseVersionId, createFile);
num ++;
}
}
public uint CreateNamedVersion (string name, string extension, uint baseVersionId, bool createFile)
{
int num = 1;
while (true) {
var final_name = string.Format (
(num == 1) ? Catalog.GetString ("Modified in {1}") : Catalog.GetString ("Modified in {1} ({0})"), num, name);
string filename = GetFilenameForVersionName (name, System.IO.Path.GetExtension (versions [baseVersionId].Filename));
SafeUri uri = DefaultVersion.BaseUri.Append (filename);
if (! VersionNameExists (final_name) && !File.Exists (uri.AbsolutePath))
return CreateVersion (final_name, extension, baseVersionId, createFile);
num ++;
}
}
public void RenameVersion (uint versionId, string newName)
{
if (versionId == OriginalVersionId)
throw new Exception ("Cannot rename original version");
if (VersionNameExists (newName))
throw new Exception ("This name already exists");
GetVersion (versionId).Name = newName;
changes.ChangeVersion (versionId);
//TODO: rename file too ???
// if (System.IO.File.Exists (new_path))
// throw new Exception ("File with this name already exists");
//
// File.Move (old_path, new_path);
// PhotoStore.MoveThumbnail (old_path, new_path);
}
public void CopyAttributesFrom (Photo that)
{
Time = that.Time;
Description = that.Description;
Rating = that.Rating;
AddTag (that.Tags);
}
#endregion
#region Tag management
// This doesn't check if the tag is already there, use with caution.
public void AddTagUnsafely (Tag tag)
{
tags.Add (tag);
changes.AddTag (tag);
}
// This on the other hand does, but is O(n) with n being the number of existing tags.
public void AddTag (Tag tag)
{
if (!tags.Contains (tag))
AddTagUnsafely (tag);
}
public void AddTag (IEnumerable<Tag> taglist)
{
/*
* FIXME need a better naming convention here, perhaps just
* plain Add.
*
* tags.AddRange (taglist);
* but, AddTag calls AddTagUnsafely which
* adds and calls changes.AddTag on each tag?
* Need to investigate that.
*/
foreach (Tag tag in taglist) {
AddTag (tag);
}
}
public void RemoveTag (Tag tag)
{
if (!tags.Contains (tag))
return;
tags.Remove (tag);
changes.RemoveTag (tag);
}
public void RemoveTag (Tag []taglist)
{
foreach (Tag tag in taglist) {
RemoveTag (tag);
}
}
public void RemoveCategory (IList<Tag> taglist)
{
foreach (Tag tag in taglist) {
if (tag is Category cat)
RemoveCategory (cat.Children);
RemoveTag (tag);
}
}
// FIXME: This should be removed (I think)
public bool HasTag (Tag tag)
{
return tags.Contains (tag);
}
static readonly IDictionary<SafeUri, string> md5_cache = new Dictionary<SafeUri, string> ();
public static void ResetMD5Cache ()
{
md5_cache?.Clear ();
}
#endregion
#region Constructor
public Photo (IImageFileFactory imageFactory, IThumbnailService thumbnailService, uint id, long unix_time)
: base (id)
{
this.imageFileFactory = imageFactory;
this.thumbnailService = thumbnailService;
time = DateTimeUtil.ToDateTime (unix_time);
tags = new List<Tag> ();
description = string.Empty;
rating = 0;
}
#endregion
#region IComparable implementation
public int CompareTo (object obj)
{
if (GetType () == obj.GetType ())
return this.Compare((Photo)obj);
if (obj is DateTime)
return time.CompareTo ((DateTime)obj);
throw new Exception ("Object must be of type Photo");
}
public int CompareTo (Photo photo)
{
int result = Id.CompareTo (photo.Id);
if (result == 0)
return 0;
return this.Compare (photo);
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if PARALLEL
using System;
using System.Collections;
using System.Globalization;
using System.Runtime.Serialization;
using System.Threading;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Execution
{
#region Individual Event Classes
/// <summary>
/// NUnit.Core.Event is the abstract base for all stored events.
/// An Event is the stored representation of a call to the
/// ITestListener interface and is used to record such calls
/// or to queue them for forwarding on another thread or at
/// a later time.
/// </summary>
public abstract class Event
{
/// <summary>
/// The Send method is implemented by derived classes to send the event to the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public abstract void Send(ITestListener listener);
/// <summary>
/// Gets a value indicating whether this event is delivered synchronously by the NUnit <see cref="EventPump"/>.
/// <para>
/// If <c>true</c>, and if <see cref="EventQueue.SetWaitHandleForSynchronizedEvents"/> has been used to
/// set a WaitHandle, <see cref="EventQueue.Enqueue"/> blocks its calling thread until the <see cref="EventPump"/>
/// thread has delivered the event and sets the WaitHandle.
/// </para>
/// </summary>
public virtual bool IsSynchronous
{
get { return false; }
}
// protected static Exception WrapUnserializableException(Exception ex)
// {
// string message = string.Format(
// CultureInfo.InvariantCulture,
// "(failed to serialize original Exception - original Exception follows){0}{1}",
// Environment.NewLine,
// ex);
// return new Exception(message);
// }
}
/// <summary>
/// TestStartedEvent holds information needed to call the TestStarted method.
/// </summary>
public class TestStartedEvent : Event
{
private ITest test;
/// <summary>
/// Initializes a new instance of the <see cref="TestStartedEvent"/> class.
/// </summary>
/// <param name="test">The test.</param>
public TestStartedEvent(ITest test)
{
this.test = test;
}
///// <summary>
///// Gets a value indicating whether this event is delivered synchronously by the NUnit <see cref="EventPump"/>.
///// <para>
///// If <c>true</c>, and if <see cref="EventQueue.SetWaitHandleForSynchronizedEvents"/> has been used to
///// set a WaitHandle, <see cref="EventQueue.Enqueue"/> blocks its calling thread until the <see cref="EventPump"/>
///// thread has delivered the event and sets the WaitHandle.
///// </para>
///// </summary>
// Keeping this as a synchronous until we rewrite using multiple autoresetevents
// public override bool IsSynchronous
// {
// get
// {
// return true;
// }
// }
/// <summary>
/// Calls TestStarted on the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public override void Send(ITestListener listener)
{
listener.TestStarted(test);
}
}
/// <summary>
/// TestFinishedEvent holds information needed to call the TestFinished method.
/// </summary>
public class TestFinishedEvent : Event
{
private ITestResult result;
/// <summary>
/// Initializes a new instance of the <see cref="TestFinishedEvent"/> class.
/// </summary>
/// <param name="result">The result.</param>
public TestFinishedEvent(ITestResult result)
{
this.result = result;
}
/// <summary>
/// Calls TestFinished on the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public override void Send(ITestListener listener)
{
listener.TestFinished(result);
}
}
#endregion
/// <summary>
/// Implements a queue of work items each of which
/// is queued as a WaitCallback.
/// </summary>
public class EventQueue
{
// static readonly Logger log = InternalTrace.GetLogger("EventQueue");
private readonly Queue queue = new Queue();
private readonly object syncRoot;
private bool stopped;
#if NETCF
private ManualResetEvent syncEvent = new ManualResetEvent(false);
private int waitCount = 0;
#endif
/// <summary>
/// Construct a new EventQueue
/// </summary>
public EventQueue()
{
syncRoot = queue.SyncRoot;
}
/// <summary>
/// WaitHandle for synchronous event delivery in <see cref="Enqueue"/>.
/// <para>
/// Having just one handle for the whole <see cref="EventQueue"/> implies that
/// there may be only one producer (the test thread) for synchronous events.
/// If there can be multiple producers for synchronous events, one would have
/// to introduce one WaitHandle per event.
/// </para>
/// </summary>
private AutoResetEvent synchronousEventSent;
/// <summary>
/// Gets the count of items in the queue.
/// </summary>
public int Count
{
get
{
lock (syncRoot)
{
return queue.Count;
}
}
}
/// <summary>
/// Sets a handle on which to wait, when <see cref="Enqueue"/> is called
/// for an <see cref="Event"/> with <see cref="Event.IsSynchronous"/> == true.
/// </summary>
/// <param name="synchronousEventWaitHandle">
/// The wait handle on which to wait, when <see cref="Enqueue"/> is called
/// for an <see cref="Event"/> with <see cref="Event.IsSynchronous"/> == true.
/// <para>The caller is responsible for disposing this wait handle.</para>
/// </param>
public void SetWaitHandleForSynchronizedEvents(AutoResetEvent synchronousEventWaitHandle)
{
synchronousEventSent = synchronousEventWaitHandle;
}
/// <summary>
/// Enqueues the specified event
/// </summary>
/// <param name="e">The event to enqueue.</param>
public void Enqueue(Event e)
{
lock (syncRoot)
{
queue.Enqueue(e);
#if NETCF
syncEvent.Set();
while (waitCount != 0)
Thread.Sleep(0);
syncEvent.Reset();
#else
Monitor.Pulse(syncRoot);
#endif
}
if (synchronousEventSent != null && e.IsSynchronous)
synchronousEventSent.WaitOne();
else
Thread.Sleep(0); // give EventPump thread a chance to process the event
}
/// <summary>
/// Removes the first element from the queue and returns it (or <c>null</c>).
/// </summary>
/// <param name="blockWhenEmpty">
/// If <c>true</c> and the queue is empty, the calling thread is blocked until
/// either an element is enqueued, or <see cref="Stop"/> is called.
/// </param>
/// <returns>
/// <list type="bullet">
/// <item>
/// <term>If the queue not empty</term>
/// <description>the first element.</description>
/// </item>
/// <item>
/// <term>otherwise, if <paramref name="blockWhenEmpty"/>==<c>false</c>
/// or <see cref="Stop"/> has been called</term>
/// <description><c>null</c>.</description>
/// </item>
/// </list>
/// </returns>
public Event Dequeue(bool blockWhenEmpty)
{
lock (syncRoot)
{
while (queue.Count == 0)
{
if (blockWhenEmpty && !stopped)
#if NETCF
{
Monitor.Exit(syncRoot);
Interlocked.Increment(ref waitCount);
syncEvent.WaitOne();
Interlocked.Decrement(ref waitCount);
Monitor.Enter(syncRoot);
}
#else
Monitor.Wait(syncRoot);
#endif
else
return null;
}
return (Event)queue.Dequeue();
}
}
/// <summary>
/// Stop processing of the queue
/// </summary>
public void Stop()
{
lock (syncRoot)
{
if (!stopped)
{
stopped = true;
#if NETCF
syncEvent.Set();
while (waitCount != 0)
Thread.Sleep(0);
syncEvent.Reset();
#else
Monitor.PulseAll(syncRoot);
#endif
}
}
}
}
}
#endif
| |
// 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 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for PublicIPAddressesOperations.
/// </summary>
public static partial class PublicIPAddressesOperationsExtensions
{
/// <summary>
/// The delete publicIpAddress operation deletes the specified publicIpAddress.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
public static void Delete(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName)
{
Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).DeleteAsync(resourceGroupName, publicIpAddressName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete publicIpAddress operation deletes the specified publicIpAddress.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The delete publicIpAddress operation deletes the specified publicIpAddress.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
public static void BeginDelete(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName)
{
Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).BeginDeleteAsync(resourceGroupName, publicIpAddressName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete publicIpAddress operation deletes the specified publicIpAddress.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Get publicIpAddress operation retrieves information about the
/// specified pubicIpAddress
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
public static PublicIPAddress Get(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, string expand = default(string))
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).GetAsync(resourceGroupName, publicIpAddressName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get publicIpAddress operation retrieves information about the
/// specified pubicIpAddress
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublicIPAddress> GetAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put PublicIPAddress operation creates/updates a stable/dynamic
/// PublicIP address
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the publicIpAddress.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update PublicIPAddress operation
/// </param>
public static PublicIPAddress CreateOrUpdate(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).CreateOrUpdateAsync(resourceGroupName, publicIpAddressName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put PublicIPAddress operation creates/updates a stable/dynamic
/// PublicIP address
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the publicIpAddress.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update PublicIPAddress operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublicIPAddress> CreateOrUpdateAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put PublicIPAddress operation creates/updates a stable/dynamic
/// PublicIP address
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the publicIpAddress.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update PublicIPAddress operation
/// </param>
public static PublicIPAddress BeginCreateOrUpdate(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, publicIpAddressName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put PublicIPAddress operation creates/updates a stable/dynamic
/// PublicIP address
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the publicIpAddress.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update PublicIPAddress operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublicIPAddress> BeginCreateOrUpdateAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List publicIpAddress operation retrieves all the publicIpAddresses in
/// a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<PublicIPAddress> ListAll(this IPublicIPAddressesOperations operations)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List publicIpAddress operation retrieves all the publicIpAddresses in
/// a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PublicIPAddress>> ListAllAsync(this IPublicIPAddressesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List publicIpAddress operation retrieves all the publicIpAddresses in
/// a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<PublicIPAddress> List(this IPublicIPAddressesOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List publicIpAddress operation retrieves all the publicIpAddresses in
/// a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PublicIPAddress>> ListAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List publicIpAddress operation retrieves all the publicIpAddresses in
/// a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<PublicIPAddress> ListAllNext(this IPublicIPAddressesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List publicIpAddress operation retrieves all the publicIpAddresses in
/// a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PublicIPAddress>> ListAllNextAsync(this IPublicIPAddressesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List publicIpAddress operation retrieves all the publicIpAddresses in
/// a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<PublicIPAddress> ListNext(this IPublicIPAddressesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List publicIpAddress operation retrieves all the publicIpAddresses in
/// a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PublicIPAddress>> ListNextAsync(this IPublicIPAddressesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Channels.Tests
{
public class BoundedChannelTests : ChannelTestBase
{
protected override Channel<int> CreateChannel() => Channel.CreateBounded<int>(1);
protected override Channel<int> CreateFullChannel()
{
var c = Channel.CreateBounded<int>(1);
c.Writer.WriteAsync(42).Wait();
return c;
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(10000)]
public void TryWrite_TryRead_Many_Wait(int bufferedCapacity)
{
var c = Channel.CreateBounded<int>(bufferedCapacity);
for (int i = 0; i < bufferedCapacity; i++)
{
Assert.True(c.Writer.TryWrite(i));
}
Assert.False(c.Writer.TryWrite(bufferedCapacity));
int result;
for (int i = 0; i < bufferedCapacity; i++)
{
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.False(c.Reader.TryRead(out result));
Assert.Equal(0, result);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(10000)]
public void TryWrite_TryRead_Many_DropOldest(int bufferedCapacity)
{
var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropOldest });
for (int i = 0; i < bufferedCapacity * 2; i++)
{
Assert.True(c.Writer.TryWrite(i));
}
int result;
for (int i = bufferedCapacity; i < bufferedCapacity * 2; i++)
{
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.False(c.Reader.TryRead(out result));
Assert.Equal(0, result);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(10000)]
public void WriteAsync_TryRead_Many_DropOldest(int bufferedCapacity)
{
var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropOldest });
for (int i = 0; i < bufferedCapacity * 2; i++)
{
AssertSynchronousSuccess(c.Writer.WriteAsync(i));
}
int result;
for (int i = bufferedCapacity; i < bufferedCapacity * 2; i++)
{
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.False(c.Reader.TryRead(out result));
Assert.Equal(0, result);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(10000)]
public void TryWrite_TryRead_Many_DropNewest(int bufferedCapacity)
{
var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropNewest });
for (int i = 0; i < bufferedCapacity * 2; i++)
{
Assert.True(c.Writer.TryWrite(i));
}
int result;
for (int i = 0; i < bufferedCapacity - 1; i++)
{
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(bufferedCapacity * 2 - 1, result);
Assert.False(c.Reader.TryRead(out result));
Assert.Equal(0, result);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(10000)]
public void WriteAsync_TryRead_Many_DropNewest(int bufferedCapacity)
{
var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropNewest });
for (int i = 0; i < bufferedCapacity * 2; i++)
{
AssertSynchronousSuccess(c.Writer.WriteAsync(i));
}
int result;
for (int i = 0; i < bufferedCapacity - 1; i++)
{
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(bufferedCapacity * 2 - 1, result);
Assert.False(c.Reader.TryRead(out result));
Assert.Equal(0, result);
}
[Fact]
public async Task TryWrite_DropNewest_WrappedAroundInternalQueue()
{
var c = Channel.CreateBounded<int>(new BoundedChannelOptions(3) { FullMode = BoundedChannelFullMode.DropNewest });
// Move head of dequeue beyond the beginning
Assert.True(c.Writer.TryWrite(1));
Assert.True(c.Reader.TryRead(out int item));
Assert.Equal(1, item);
// Add items to fill the capacity and put the tail at 0
Assert.True(c.Writer.TryWrite(2));
Assert.True(c.Writer.TryWrite(3));
Assert.True(c.Writer.TryWrite(4));
// Add an item to overwrite the newest
Assert.True(c.Writer.TryWrite(5));
// Verify current contents
Assert.Equal(2, await c.Reader.ReadAsync());
Assert.Equal(3, await c.Reader.ReadAsync());
Assert.Equal(5, await c.Reader.ReadAsync());
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(10000)]
public void TryWrite_TryRead_Many_Ignore(int bufferedCapacity)
{
var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropWrite });
for (int i = 0; i < bufferedCapacity * 2; i++)
{
Assert.True(c.Writer.TryWrite(i));
}
int result;
for (int i = 0; i < bufferedCapacity; i++)
{
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.False(c.Reader.TryRead(out result));
Assert.Equal(0, result);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(10000)]
public void WriteAsync_TryRead_Many_Ignore(int bufferedCapacity)
{
var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropWrite });
for (int i = 0; i < bufferedCapacity * 2; i++)
{
AssertSynchronousSuccess(c.Writer.WriteAsync(i));
}
int result;
for (int i = 0; i < bufferedCapacity; i++)
{
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.False(c.Reader.TryRead(out result));
Assert.Equal(0, result);
}
[Fact]
public async Task CancelPendingWrite_Reading_DataTransferredFromCorrectWriter()
{
var c = Channel.CreateBounded<int>(1);
Assert.Equal(TaskStatus.RanToCompletion, c.Writer.WriteAsync(42).Status);
var cts = new CancellationTokenSource();
Task write1 = c.Writer.WriteAsync(43, cts.Token);
Assert.Equal(TaskStatus.WaitingForActivation, write1.Status);
cts.Cancel();
Task write2 = c.Writer.WriteAsync(44);
Assert.Equal(42, await c.Reader.ReadAsync());
Assert.Equal(44, await c.Reader.ReadAsync());
await AssertCanceled(write1, cts.Token);
await write2;
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(10000)]
public void TryWrite_TryRead_OneAtATime(int bufferedCapacity)
{
var c = Channel.CreateBounded<int>(bufferedCapacity);
const int NumItems = 100000;
for (int i = 0; i < NumItems; i++)
{
Assert.True(c.Writer.TryWrite(i));
Assert.True(c.Reader.TryRead(out int result));
Assert.Equal(i, result);
}
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(10000)]
public void SingleProducerConsumer_ConcurrentReadWrite_WithBufferedCapacity_Success(int bufferedCapacity)
{
var c = Channel.CreateBounded<int>(bufferedCapacity);
const int NumItems = 10000;
Task.WaitAll(
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
await c.Writer.WriteAsync(i);
}
}),
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
Assert.Equal(i, await c.Reader.ReadAsync());
}
}));
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(10000)]
public void ManyProducerConsumer_ConcurrentReadWrite_WithBufferedCapacity_Success(int bufferedCapacity)
{
var c = Channel.CreateBounded<int>(bufferedCapacity);
const int NumWriters = 10;
const int NumReaders = 10;
const int NumItems = 10000;
long readTotal = 0;
int remainingWriters = NumWriters;
int remainingItems = NumItems;
Task[] tasks = new Task[NumWriters + NumReaders];
for (int i = 0; i < NumReaders; i++)
{
tasks[i] = Task.Run(async () =>
{
try
{
while (true)
{
Interlocked.Add(ref readTotal, await c.Reader.ReadAsync());
}
}
catch (ChannelClosedException) { }
});
}
for (int i = 0; i < NumWriters; i++)
{
tasks[NumReaders + i] = Task.Run(async () =>
{
while (true)
{
int value = Interlocked.Decrement(ref remainingItems);
if (value < 0)
{
break;
}
await c.Writer.WriteAsync(value + 1);
}
if (Interlocked.Decrement(ref remainingWriters) == 0)
{
c.Writer.Complete();
}
});
}
Task.WaitAll(tasks);
Assert.Equal((NumItems * (NumItems + 1L)) / 2, readTotal);
}
[Fact]
public async Task WaitToWriteAsync_AfterFullThenRead_ReturnsTrue()
{
var c = Channel.CreateBounded<int>(1);
Assert.True(c.Writer.TryWrite(1));
Task<bool> write1 = c.Writer.WaitToWriteAsync();
Assert.False(write1.IsCompleted);
Task<bool> write2 = c.Writer.WaitToWriteAsync();
Assert.False(write2.IsCompleted);
Assert.Equal(1, await c.Reader.ReadAsync());
Assert.True(await write1);
Assert.True(await write2);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AllowSynchronousContinuations_WaitToReadAsync_ContinuationsInvokedAccordingToSetting(bool allowSynchronousContinuations)
{
var c = Channel.CreateBounded<int>(new BoundedChannelOptions(1) { AllowSynchronousContinuations = allowSynchronousContinuations });
int expectedId = Environment.CurrentManagedThreadId;
Task r = c.Reader.WaitToReadAsync().ContinueWith(_ =>
{
Assert.Equal(allowSynchronousContinuations, expectedId == Environment.CurrentManagedThreadId);
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Assert.Equal(TaskStatus.RanToCompletion, c.Writer.WriteAsync(42).Status);
((IAsyncResult)r).AsyncWaitHandle.WaitOne(); // avoid inlining the continuation
r.GetAwaiter().GetResult();
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AllowSynchronousContinuations_CompletionTask_ContinuationsInvokedAccordingToSetting(bool allowSynchronousContinuations)
{
var c = Channel.CreateBounded<int>(new BoundedChannelOptions(1) { AllowSynchronousContinuations = allowSynchronousContinuations });
int expectedId = Environment.CurrentManagedThreadId;
Task r = c.Reader.Completion.ContinueWith(_ =>
{
Assert.Equal(allowSynchronousContinuations, expectedId == Environment.CurrentManagedThreadId);
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Assert.True(c.Writer.TryComplete());
((IAsyncResult)r).AsyncWaitHandle.WaitOne(); // avoid inlining the continuation
r.GetAwaiter().GetResult();
}
[Fact]
public void TryWrite_NoBlockedReaders_WaitingReader_WaiterNotifified()
{
Channel<int> c = CreateChannel();
Task<bool> r = c.Reader.WaitToReadAsync();
Assert.True(c.Writer.TryWrite(42));
AssertSynchronousTrue(r);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting
{
[Export(typeof(IViewTaggerProvider))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TagType(typeof(NavigableHighlightTag))]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
internal partial class ReferenceHighlightingViewTaggerProvider : AsynchronousViewTaggerProvider<NavigableHighlightTag>
{
private readonly ISemanticChangeNotificationService _semanticChangeNotificationService;
// Whenever an edit happens, clear all highlights. When moving the caret, preserve
// highlights if the caret stays within an existing tag.
protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag;
protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags;
protected override IEnumerable<PerLanguageOption<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.ReferenceHighlighting);
[ImportingConstructor]
public ReferenceHighlightingViewTaggerProvider(
IForegroundNotificationService notificationService,
ISemanticChangeNotificationService semanticChangeNotificationService,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
: base(new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.ReferenceHighlighting), notificationService)
{
_semanticChangeNotificationService = semanticChangeNotificationService;
}
protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer)
{
// Note: we don't listen for OnTextChanged. Text changes to this buffer will get
// reported by OnSemanticChanged.
return TaggerEventSources.Compose(
TaggerEventSources.OnCaretPositionChanged(textView, textView.TextBuffer, TaggerDelay.Short),
TaggerEventSources.OnSemanticChanged(subjectBuffer, TaggerDelay.OnIdle, _semanticChangeNotificationService),
TaggerEventSources.OnDocumentActiveContextChanged(subjectBuffer, TaggerDelay.Short));
}
protected override SnapshotPoint? GetCaretPoint(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
return textViewOpt.Caret.Position.Point.GetPoint(b => IsSupportedContentType(b.ContentType), PositionAffinity.Successor);
}
protected override IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
return textViewOpt.BufferGraph.GetTextBuffers(b => IsSupportedContentType(b.ContentType))
.Select(b => b.CurrentSnapshot.GetFullSpan())
.ToList();
}
protected override Task ProduceTagsAsync(TaggerContext<NavigableHighlightTag> context)
{
// NOTE(cyrusn): Normally we'd limit ourselves to producing tags in the span we were
// asked about. However, we want to produce all tags here so that the user can actually
// navigate between all of them using the appropriate tag navigation commands. If we
// don't generate all the tags then the user will cycle through an incorrect subset.
if (context.CaretPosition == null)
{
return SpecializedTasks.EmptyTask;
}
var caretPosition = context.CaretPosition.Value;
if (!Workspace.TryGetWorkspace(caretPosition.Snapshot.AsText().Container, out var workspace))
{
return SpecializedTasks.EmptyTask;
}
var document = context.SpansToTag.First(vt => vt.SnapshotSpan.Snapshot == caretPosition.Snapshot).Document;
if (document == null)
{
return SpecializedTasks.EmptyTask;
}
// Don't produce tags if the feature is not enabled.
if (!workspace.Options.GetOption(FeatureOnOffOptions.ReferenceHighlighting, document.Project.Language))
{
return SpecializedTasks.EmptyTask;
}
var existingTags = context.GetExistingTags(new SnapshotSpan(caretPosition, 0));
if (!existingTags.IsEmpty())
{
// We already have a tag at this position. So the user is moving from one highlight
// tag to another. In this case we don't want to recompute anything. Let our caller
// know that we should preserve all tags.
context.SetSpansTagged(SpecializedCollections.EmptyEnumerable<DocumentSnapshotSpan>());
return SpecializedTasks.EmptyTask;
}
// Otherwise, we need to go produce all tags.
return ProduceTagsAsync(context, caretPosition, document);
}
internal async Task ProduceTagsAsync(
TaggerContext<NavigableHighlightTag> context,
SnapshotPoint position,
Document document)
{
var cancellationToken = context.CancellationToken;
var solution = document.Project.Solution;
using (Logger.LogBlock(FunctionId.Tagger_ReferenceHighlighting_TagProducer_ProduceTags, cancellationToken))
{
if (document != null)
{
// As we transition to the new API (defined at the Features layer) we support
// calling into both it and the old API (defined at the EditorFeatures layer).
//
// Once TypeScript and F# can move over, then we can remove the calls to the old
// API.
await TryNewServiceAsync(context, position, document).ConfigureAwait(false);
await TryOldServiceAsync(context, position, document).ConfigureAwait(false);
}
}
}
private Task TryOldServiceAsync(TaggerContext<NavigableHighlightTag> context, SnapshotPoint position, Document document)
{
return TryServiceAsync<IDocumentHighlightsService>(
context, position, document,
(s, d, p, ds, c) => s.GetDocumentHighlightsAsync(d, p, ds, c));
}
private Task TryNewServiceAsync(
TaggerContext<NavigableHighlightTag> context, SnapshotPoint position, Document document)
{
return TryServiceAsync<DocumentHighlighting.IDocumentHighlightsService>(
context, position, document,
async (service, doc, point, documents, cancellation) =>
{
// Call into the new service.
var newHighlights = await service.GetDocumentHighlightsAsync(doc, point, documents, cancellation).ConfigureAwait(false);
// then convert the result to the form the old service would return.
return ConvertHighlights(newHighlights);
});
}
private async Task TryServiceAsync<T>(
TaggerContext<NavigableHighlightTag> context, SnapshotPoint position, Document document,
Func<T, Document, SnapshotPoint, ImmutableHashSet<Document>, CancellationToken, Task<ImmutableArray<DocumentHighlights>>> getDocumentHighlightsAsync)
where T : class, ILanguageService
{
var cancellationToken = context.CancellationToken;
var documentHighlightsService = document.GetLanguageService<T>();
if (documentHighlightsService != null)
{
// We only want to search inside documents that correspond to the snapshots
// we're looking at
var documentsToSearch = ImmutableHashSet.CreateRange(context.SpansToTag.Select(vt => vt.Document).WhereNotNull());
var documentHighlightsList = await getDocumentHighlightsAsync(
documentHighlightsService, document, position, documentsToSearch, cancellationToken).ConfigureAwait(false);
if (documentHighlightsList != null)
{
foreach (var documentHighlights in documentHighlightsList)
{
await AddTagSpansAsync(
context, document.Project.Solution, documentHighlights).ConfigureAwait(false);
}
}
}
}
private ImmutableArray<DocumentHighlights> ConvertHighlights(ImmutableArray<DocumentHighlighting.DocumentHighlights> newHighlights)
=> newHighlights.SelectAsArray(
documentHighlights => new DocumentHighlights(
documentHighlights.Document,
documentHighlights.HighlightSpans.SelectAsArray(
highlightSpan => new HighlightSpan(
highlightSpan.TextSpan,
(HighlightSpanKind)highlightSpan.Kind))));
private async Task AddTagSpansAsync(
TaggerContext<NavigableHighlightTag> context,
Solution solution,
DocumentHighlights documentHighlights)
{
var cancellationToken = context.CancellationToken;
var document = documentHighlights.Document;
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var textSnapshot = text.FindCorrespondingEditorTextSnapshot();
if (textSnapshot == null)
{
// There is no longer an editor snapshot for this document, so we can't care about the
// results.
return;
}
foreach (var span in documentHighlights.HighlightSpans)
{
var tag = GetTag(span);
context.AddTag(new TagSpan<NavigableHighlightTag>(
textSnapshot.GetSpan(Span.FromBounds(span.TextSpan.Start, span.TextSpan.End)), tag));
}
}
private static NavigableHighlightTag GetTag(HighlightSpan span)
{
switch (span.Kind)
{
case HighlightSpanKind.WrittenReference:
return WrittenReferenceHighlightTag.Instance;
case HighlightSpanKind.Definition:
return DefinitionHighlightTag.Instance;
case HighlightSpanKind.Reference:
case HighlightSpanKind.None:
default:
return ReferenceHighlightTag.Instance;
}
}
private static bool IsSupportedContentType(IContentType contentType)
{
// This list should match the list of exported content types above
return contentType.IsOfType(ContentTypeNames.RoslynContentType) ||
contentType.IsOfType(ContentTypeNames.XamlContentType);
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Razor.Editor;
using Microsoft.AspNet.Razor.Parser;
using Microsoft.AspNet.Razor.Parser.SyntaxTree;
using Microsoft.AspNet.Razor.Test.Framework;
using Microsoft.AspNet.Razor.Tokenizer.Symbols;
using Xunit;
namespace Microsoft.AspNet.Razor.Test.Parser.CSharp
{
public class CSharpToMarkupSwitchTest : CsHtmlCodeParserTestBase
{
[Fact]
public void SingleAngleBracketDoesNotCauseSwitchIfOuterBlockIsTerminated()
{
ParseBlockTest("{ List< }",
new StatementBlock(
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.Code(" List< ").AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void ParseBlockGivesSpacesToCodeOnAtTagTemplateTransitionInDesignTimeMode()
{
ParseBlockTest("Foo( @<p>Foo</p> )",
new ExpressionBlock(
Factory.Code("Foo( ")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.Any),
new TemplateBlock(
new MarkupBlock(
Factory.MarkupTransition(),
Factory.Markup("<p>Foo</p>").Accepts(AcceptedCharacters.None)
)
),
Factory.Code(" )")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace)
), designTimeParser: true);
}
[Fact]
public void ParseBlockGivesSpacesToCodeOnAtColonTemplateTransitionInDesignTimeMode()
{
ParseBlockTest("Foo( " + Environment.NewLine
+ "@:<p>Foo</p> " + Environment.NewLine
+ ")",
new ExpressionBlock(
Factory.Code("Foo( \r\n").AsImplicitExpression(CSharpCodeParser.DefaultKeywords),
new TemplateBlock(
new MarkupBlock(
Factory.MarkupTransition(),
Factory.MetaMarkup(":", HtmlSymbolType.Colon),
Factory.Markup("<p>Foo</p> \r\n")
.With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))
)
),
Factory.Code(")")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace)
), designTimeParser: true);
}
[Fact]
public void ParseBlockGivesSpacesToCodeOnTagTransitionInDesignTimeMode()
{
ParseBlockTest("{" + Environment.NewLine
+ " <p>Foo</p> " + Environment.NewLine
+ "}",
new StatementBlock(
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.Code("\r\n ").AsStatement(),
new MarkupBlock(
Factory.Markup("<p>Foo</p>").Accepts(AcceptedCharacters.None)
),
Factory.Code(" \r\n").AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)
), designTimeParser: true);
}
[Fact]
public void ParseBlockGivesSpacesToCodeOnInvalidAtTagTransitionInDesignTimeMode()
{
ParseBlockTest("{" + Environment.NewLine
+ " @<p>Foo</p> " + Environment.NewLine
+ "}",
new StatementBlock(
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.Code("\r\n ").AsStatement(),
new MarkupBlock(
Factory.MarkupTransition(),
Factory.Markup("<p>Foo</p>").Accepts(AcceptedCharacters.None)
),
Factory.Code(" \r\n").AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)
), true,
new RazorError(RazorResources.ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start, 7, 1, 4));
}
[Fact]
public void ParseBlockGivesSpacesToCodeOnAtColonTransitionInDesignTimeMode()
{
ParseBlockTest("{" + Environment.NewLine
+ " @:<p>Foo</p> " + Environment.NewLine
+ "}",
new StatementBlock(
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.Code("\r\n ").AsStatement(),
new MarkupBlock(
Factory.MarkupTransition(),
Factory.MetaMarkup(":", HtmlSymbolType.Colon),
Factory.Markup("<p>Foo</p> \r\n")
.With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))
),
Factory.EmptyCSharp().AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)
), designTimeParser: true);
}
[Fact]
public void ParseBlockShouldSupportSingleLineMarkupContainingStatementBlock()
{
ParseBlockTest("Repeat(10," + Environment.NewLine
+ " @: @{}" + Environment.NewLine
+ ")",
new ExpressionBlock(
Factory.Code("Repeat(10,\r\n ")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords),
new TemplateBlock(
new MarkupBlock(
Factory.MarkupTransition(),
Factory.MetaMarkup(":", HtmlSymbolType.Colon),
Factory.Markup(" ")
.With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)),
new StatementBlock(
Factory.CodeTransition(),
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.EmptyCSharp().AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)
),
Factory.Markup("\r\n")
.With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))
)
),
Factory.Code(")")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace)
));
}
[Fact]
public void ParseBlockShouldSupportMarkupWithoutPreceedingWhitespace()
{
ParseBlockTest("foreach(var file in files){" + Environment.NewLine
+ Environment.NewLine
+ Environment.NewLine
+ "@:Baz" + Environment.NewLine
+ "<br/>" + Environment.NewLine
+ "<a>Foo</a>" + Environment.NewLine
+ "@:Bar" + Environment.NewLine
+ "}",
new StatementBlock(
Factory.Code("foreach(var file in files){\r\n\r\n\r\n").AsStatement(),
new MarkupBlock(
Factory.MarkupTransition(),
Factory.MetaMarkup(":", HtmlSymbolType.Colon),
Factory.Markup("Baz\r\n")
.With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))
),
new MarkupBlock(
Factory.Markup("<br/>\r\n")
.Accepts(AcceptedCharacters.None)
),
new MarkupBlock(
Factory.Markup("<a>Foo</a>\r\n")
.Accepts(AcceptedCharacters.None)
),
new MarkupBlock(
Factory.MarkupTransition(),
Factory.MetaMarkup(":", HtmlSymbolType.Colon),
Factory.Markup("Bar\r\n")
.With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))
),
Factory.Code("}").AsStatement().Accepts(AcceptedCharacters.None)
));
}
[Fact]
public void ParseBlockGivesAllWhitespaceOnSameLineExcludingPreceedingNewlineButIncludingTrailingNewLineToMarkup()
{
ParseBlockTest("if(foo) {" + Environment.NewLine
+ " var foo = \"After this statement there are 10 spaces\"; " + Environment.NewLine
+ " <p>" + Environment.NewLine
+ " Foo" + Environment.NewLine
+ " @bar" + Environment.NewLine
+ " </p>" + Environment.NewLine
+ " @:Hello!" + Environment.NewLine
+ " var biz = boz;" + Environment.NewLine
+ "}",
new StatementBlock(
Factory.Code("if(foo) {\r\n var foo = \"After this statement there are 10 spaces\"; \r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>\r\n Foo\r\n"),
new ExpressionBlock(
Factory.Code(" ").AsStatement(),
Factory.CodeTransition(),
Factory.Code("bar").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)
),
Factory.Markup("\r\n </p>\r\n").Accepts(AcceptedCharacters.None)
),
new MarkupBlock(
Factory.Markup(" "),
Factory.MarkupTransition(),
Factory.MetaMarkup(":", HtmlSymbolType.Colon),
Factory.Markup("Hello!\r\n").With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))
),
Factory.Code(" var biz = boz;\r\n}").AsStatement()));
}
[Fact]
public void ParseBlockAllowsMarkupInIfBodyWithBraces()
{
ParseBlockTest("if(foo) { <p>Bar</p> } else if(bar) { <p>Baz</p> } else { <p>Boz</p> }",
new StatementBlock(
Factory.Code("if(foo) {").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Bar</p> ").Accepts(AcceptedCharacters.None)
),
Factory.Code("} else if(bar) {").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Baz</p> ").Accepts(AcceptedCharacters.None)
),
Factory.Code("} else {").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Boz</p> ").Accepts(AcceptedCharacters.None)
),
Factory.Code("}").AsStatement().Accepts(AcceptedCharacters.None)
));
}
[Fact]
public void ParseBlockAllowsMarkupInIfBodyWithBracesWithinCodeBlock()
{
ParseBlockTest("{ if(foo) { <p>Bar</p> } else if(bar) { <p>Baz</p> } else { <p>Boz</p> } }",
new StatementBlock(
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.Code(" if(foo) {").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Bar</p> ").Accepts(AcceptedCharacters.None)
),
Factory.Code("} else if(bar) {").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Baz</p> ").Accepts(AcceptedCharacters.None)
),
Factory.Code("} else {").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Boz</p> ").Accepts(AcceptedCharacters.None)
),
Factory.Code("} ").AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)
));
}
[Fact]
public void ParseBlockSupportsMarkupInCaseAndDefaultBranchesOfSwitch()
{
// Arrange
ParseBlockTest("switch(foo) {" + Environment.NewLine
+ " case 0:" + Environment.NewLine
+ " <p>Foo</p>" + Environment.NewLine
+ " break;" + Environment.NewLine
+ " case 1:" + Environment.NewLine
+ " <p>Bar</p>" + Environment.NewLine
+ " return;" + Environment.NewLine
+ " case 2:" + Environment.NewLine
+ " {" + Environment.NewLine
+ " <p>Baz</p>" + Environment.NewLine
+ " <p>Boz</p>" + Environment.NewLine
+ " }" + Environment.NewLine
+ " default:" + Environment.NewLine
+ " <p>Biz</p>" + Environment.NewLine
+ "}",
new StatementBlock(
Factory.Code("switch(foo) {\r\n case 0:\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Foo</p>\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code(" break;\r\n case 1:\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Bar</p>\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code(" return;\r\n case 2:\r\n {\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Baz</p>\r\n").Accepts(AcceptedCharacters.None)
),
new MarkupBlock(
Factory.Markup(" <p>Boz</p>\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code(" }\r\n default:\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Biz</p>\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code("}").AsStatement().Accepts(AcceptedCharacters.None)));
}
[Fact]
public void ParseBlockSupportsMarkupInCaseAndDefaultBranchesOfSwitchInCodeBlock()
{
// Arrange
ParseBlockTest("{ switch(foo) {" + Environment.NewLine
+ " case 0:" + Environment.NewLine
+ " <p>Foo</p>" + Environment.NewLine
+ " break;" + Environment.NewLine
+ " case 1:" + Environment.NewLine
+ " <p>Bar</p>" + Environment.NewLine
+ " return;" + Environment.NewLine
+ " case 2:" + Environment.NewLine
+ " {" + Environment.NewLine
+ " <p>Baz</p>" + Environment.NewLine
+ " <p>Boz</p>" + Environment.NewLine
+ " }" + Environment.NewLine
+ " default:" + Environment.NewLine
+ " <p>Biz</p>" + Environment.NewLine
+ "} }",
new StatementBlock(
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.Code(" switch(foo) {\r\n case 0:\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Foo</p>\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code(" break;\r\n case 1:\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Bar</p>\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code(" return;\r\n case 2:\r\n {\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Baz</p>\r\n").Accepts(AcceptedCharacters.None)
),
new MarkupBlock(
Factory.Markup(" <p>Boz</p>\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code(" }\r\n default:\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Biz</p>\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code("} ").AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void ParseBlockParsesMarkupStatementOnOpenAngleBracket()
{
ParseBlockTest("for(int i = 0; i < 10; i++) { <p>Foo</p> }",
new StatementBlock(
Factory.Code("for(int i = 0; i < 10; i++) {").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Foo</p> ").Accepts(AcceptedCharacters.None)
),
Factory.Code("}").AsStatement().Accepts(AcceptedCharacters.None)
));
}
[Fact]
public void ParseBlockParsesMarkupStatementOnOpenAngleBracketInCodeBlock()
{
ParseBlockTest("{ for(int i = 0; i < 10; i++) { <p>Foo</p> } }",
new StatementBlock(
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.Code(" for(int i = 0; i < 10; i++) {").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>Foo</p> ").Accepts(AcceptedCharacters.None)
),
Factory.Code("} ").AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void ParseBlockParsesMarkupStatementOnSwitchCharacterFollowedByColon()
{
// Arrange
ParseBlockTest("if(foo) { @:Bar" + Environment.NewLine
+ "} zoop",
new StatementBlock(
Factory.Code("if(foo) {").AsStatement(),
new MarkupBlock(
Factory.Markup(" "),
Factory.MarkupTransition(),
Factory.MetaMarkup(":", HtmlSymbolType.Colon),
Factory.Markup("Bar\r\n").With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))
),
Factory.Code("}").AsStatement()));
}
[Fact]
public void ParseBlockParsesMarkupStatementOnSwitchCharacterFollowedByColonInCodeBlock()
{
// Arrange
ParseBlockTest("{ if(foo) { @:Bar" + Environment.NewLine
+ "} } zoop",
new StatementBlock(
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.Code(" if(foo) {").AsStatement(),
new MarkupBlock(
Factory.Markup(" "),
Factory.MarkupTransition(),
Factory.MetaMarkup(":", HtmlSymbolType.Colon),
Factory.Markup("Bar\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code("} ").AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void ParseBlockCorrectlyReturnsFromMarkupBlockWithPseudoTag()
{
ParseBlockTest("if (i > 0) { <text>;</text> }",
new StatementBlock(
Factory.Code("if (i > 0) {").AsStatement(),
new MarkupBlock(
Factory.Markup(" "),
Factory.MarkupTransition("<text>").Accepts(AcceptedCharacters.None),
Factory.Markup(";"),
Factory.MarkupTransition("</text>").Accepts(AcceptedCharacters.None),
Factory.Markup(" ").Accepts(AcceptedCharacters.None)
),
Factory.Code("}").AsStatement()));
}
[Fact]
public void ParseBlockCorrectlyReturnsFromMarkupBlockWithPseudoTagInCodeBlock()
{
ParseBlockTest("{ if (i > 0) { <text>;</text> } }",
new StatementBlock(
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.Code(" if (i > 0) {").AsStatement(),
new MarkupBlock(
Factory.Markup(" "),
Factory.MarkupTransition("<text>").Accepts(AcceptedCharacters.None),
Factory.Markup(";"),
Factory.MarkupTransition("</text>").Accepts(AcceptedCharacters.None),
Factory.Markup(" ").Accepts(AcceptedCharacters.None)
),
Factory.Code("} ").AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void ParseBlockSupportsAllKindsOfImplicitMarkupInCodeBlock()
{
ParseBlockTest("{" + Environment.NewLine
+ " if(true) {" + Environment.NewLine
+ " @:Single Line Markup" + Environment.NewLine
+ " }" + Environment.NewLine
+ " foreach (var p in Enumerable.Range(1, 10)) {" + Environment.NewLine
+ " <text>The number is @p</text>" + Environment.NewLine
+ " }" + Environment.NewLine
+ " if(!false) {" + Environment.NewLine
+ " <p>A real tag!</p>" + Environment.NewLine
+ " }" + Environment.NewLine
+ "}",
new StatementBlock(
Factory.MetaCode("{").Accepts(AcceptedCharacters.None),
Factory.Code("\r\n if(true) {\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" "),
Factory.MarkupTransition(),
Factory.MetaMarkup(":", HtmlSymbolType.Colon),
Factory.Markup("Single Line Markup\r\n").With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))
),
Factory.Code(" }\r\n foreach (var p in Enumerable.Range(1, 10)) {\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" "),
Factory.MarkupTransition("<text>").Accepts(AcceptedCharacters.None),
Factory.Markup("The number is "),
new ExpressionBlock(
Factory.CodeTransition(),
Factory.Code("p").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)
),
Factory.MarkupTransition("</text>").Accepts(AcceptedCharacters.None),
Factory.Markup("\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code(" }\r\n if(!false) {\r\n").AsStatement(),
new MarkupBlock(
Factory.Markup(" <p>A real tag!</p>\r\n").Accepts(AcceptedCharacters.None)
),
Factory.Code(" }\r\n").AsStatement(),
Factory.MetaCode("}").Accepts(AcceptedCharacters.None)));
}
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using HETSAPI.Models;
namespace HETSAPI.ViewModels
{
/// <summary>
/// Time Record View Model
/// </summary>
[DataContract]
public sealed class TimeRecordViewModel : IEquatable<TimeRecordViewModel>
{
/// <summary>
/// Time Record View Model Constructor
/// </summary>
public TimeRecordViewModel()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TimeRecordViewModel" /> class.
/// </summary>
/// <param name="equipmentCode">EquipmentCode (from Equipment Record)</param>
/// <param name="projectName">Project Name (from the project/agreement)</param>
/// <param name="provincialProjectNumber">Provincial Project Number</param>
/// <param name="maximumHours">Returns the Maxumum Hours for this Type of Equipment</param>
/// <param name="hoursYtd">Hours YTD (calculated)</param>
/// <param name="timeRecords">The TimeRecords for this agreement</param>
public TimeRecordViewModel(string equipmentCode, string projectName, string provincialProjectNumber, int maximumHours,
float? hoursYtd = null, List<TimeRecord> timeRecords = null)
{
EquipmentCode = equipmentCode;
ProjectName = projectName;
ProvincialProjectNumber = provincialProjectNumber;
MaximumHours = maximumHours;
HoursYtd = hoursYtd;
TimeRecords = timeRecords;
}
/// <summary>
/// EquipmentCode (from Equipment Record)
/// </summary>
[DataMember(Name = "equipmentCode")]
public string EquipmentCode { get; set; }
/// <summary>
/// Project Name (from the project/agreement)
/// </summary>
[DataMember(Name = "projectName")]
public string ProjectName { get; set; }
/// <summary>
/// Project Number
/// </summary>
[DataMember(Name = "provincialProjectNumber")]
public string ProvincialProjectNumber { get; set; }
/// <summary>
/// Hours YTD (calculated)
/// </summary>
[DataMember(Name = "hoursYtd")]
public float? HoursYtd { get; set; }
/// <summary>
/// Returns the Maxumum Hours for this Type of Equipment
/// </summary>
[DataMember(Name = "maximumHours")]
public int MaximumHours { get; set; }
/// <summary>
/// Gets or Sets TimeRecords
/// </summary>
[DataMember(Name="timeRecords")]
public List<TimeRecord> TimeRecords { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class TimeRecordViewModel {\n");
sb.Append(" EquipmentCode: ").Append(EquipmentCode).Append("\n");
sb.Append(" ProjectName: ").Append(ProjectName).Append("\n");
sb.Append(" ProvincialProjectNumber: ").Append(ProvincialProjectNumber).Append("\n");
sb.Append(" MaximumHours: ").Append(MaximumHours).Append("\n");
sb.Append(" HoursYtd: ").Append(HoursYtd).Append("\n");
sb.Append(" TimeRecords: ").Append(TimeRecords).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
return obj.GetType() == GetType() && Equals((TimeRecordViewModel)obj);
}
/// <summary>
/// Returns true if TimeRecordViewModel instances are equal
/// </summary>
/// <param name="other">Instance of TimeRecordViewModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TimeRecordViewModel other)
{
if (other is null) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
EquipmentCode == other.EquipmentCode ||
EquipmentCode.Equals(other.EquipmentCode)
) &&
(
ProjectName == other.ProjectName ||
ProjectName.Equals(other.ProjectName)
) &&
(
ProvincialProjectNumber == other.ProvincialProjectNumber ||
ProvincialProjectNumber.Equals(other.ProvincialProjectNumber)
) &&
(
MaximumHours == other.MaximumHours ||
MaximumHours.Equals(other.MaximumHours)
) &&
(
HoursYtd == other.HoursYtd ||
HoursYtd != null &&
HoursYtd.Equals(other.HoursYtd)
) &&
(
TimeRecords == other.TimeRecords ||
TimeRecords != null &&
TimeRecords.Equals(other.TimeRecords)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + EquipmentCode.GetHashCode();
hash = hash * 59 + ProjectName.GetHashCode();
hash = hash * 59 + ProvincialProjectNumber.GetHashCode();
hash = hash * 59 + MaximumHours.GetHashCode();
if (HoursYtd != null)
{
hash = hash * 59 + HoursYtd.GetHashCode();
}
if (TimeRecords != null)
{
hash = hash * 59 + TimeRecords.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(TimeRecordViewModel left, TimeRecordViewModel right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(TimeRecordViewModel left, TimeRecordViewModel right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEngine.Experimental.Rendering
{
public class SkyboxHelper
{
public SkyboxHelper()
{
}
const int k_NumFullSubdivisions = 3; // 3 subdivs == 2048 triangles
const int k_NumHorizonSubdivisions = 2;
public void CreateMesh()
{
var vertData = new Vector3[8 * 3];
for (int i = 0; i < 8 * 3; i++)
{
vertData[i] = m_OctaVerts[i];
}
// Regular subdivisions
for (int i = 0; i < k_NumFullSubdivisions; i++)
{
var srcData = vertData.Clone() as Vector3[];
var verts = new List<Vector3>();
for (int k = 0; k < srcData.Length; k += 3)
{
Subdivide(verts, srcData[k], srcData[k + 1], srcData[k + 2]);
}
vertData = verts.ToArray();
}
// Horizon subdivisions
var horizonLimit = 1.0f;
for (int i = 0; i < k_NumHorizonSubdivisions; i++)
{
var srcData = vertData.Clone() as Vector3[];
var verts = new List<Vector3>();
horizonLimit *= 0.5f; // First iteration limit to y < +-0.5, next one 0.25 etc.
for (int k = 0; k < srcData.Length; k += 3)
{
var maxAbsY = Mathf.Max(Mathf.Abs(srcData[k].y), Mathf.Abs(srcData[k + 1].y), Mathf.Abs(srcData[k + 2].y));
if (maxAbsY > horizonLimit)
{
// Pass through existing triangle
verts.Add(srcData[k]);
verts.Add(srcData[k + 1]);
verts.Add(srcData[k + 2]);
}
else
{
SubdivideYOnly(verts, srcData[k], srcData[k + 1], srcData[k + 2]);
}
}
vertData = verts.ToArray();
}
// Write out the mesh
var vertexCount = vertData.Length;
var triangles = new int[vertexCount];
for (int i = 0; i < vertexCount; i++)
{
triangles[i] = i;
}
m_Mesh = new Mesh
{
vertices = vertData,
triangles = triangles
};
}
public UnityEngine.Mesh mesh
{
get { return m_Mesh; }
}
public void Draw(ScriptableRenderContext loop, Camera camera)
{
if (camera.clearFlags != CameraClearFlags.Skybox)
{
return;
}
var mat = RenderSettings.skybox;
if (mat == null)
{
return;
}
var cmd = new CommandBuffer { name = "Skybox" };
var looksLikeSixSidedShader = true;
looksLikeSixSidedShader &= (mat.passCount == 6); // should have six passes
//looksLikeSixSidedShader &= !mat.GetShader()->GetShaderLabShader()->HasLightingPasses();
if (looksLikeSixSidedShader)
{
Debug.LogWarning("Six sided skybox not yet supported.");
}
else
{
if (mesh == null)
{
CreateMesh();
}
var dist = camera.farClipPlane * 10.0f;
var world = Matrix4x4.TRS(camera.transform.position, Quaternion.identity, new Vector3(dist, dist, dist));
var skyboxProj = SkyboxHelper.GetProjectionMatrix(camera);
cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, skyboxProj);
cmd.DrawMesh(mesh, world, mat);
cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix);
}
loop.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
public static Matrix4x4 GetProjectionMatrix(Camera camera)
{
var skyboxProj = Matrix4x4.Perspective(camera.fieldOfView, camera.aspect, camera.nearClipPlane, camera.farClipPlane);
var nearPlane = camera.nearClipPlane * 0.01f;
skyboxProj = AdjustDepthRange(skyboxProj, camera.nearClipPlane, nearPlane, camera.farClipPlane);
return MakeProjectionInfinite(skyboxProj, nearPlane);
}
static Matrix4x4 MakeProjectionInfinite(Matrix4x4 m, float nearPlane)
{
const float epsilon = 1e-6f;
var r = m;
r[2, 2] = -1.0f + epsilon;
r[2, 3] = (-2.0f + epsilon) * nearPlane;
r[3, 2] = -1.0f;
return r;
}
static Matrix4x4 AdjustDepthRange(Matrix4x4 mat, float origNear, float newNear, float newFar)
{
var x = mat[0, 0];
var y = mat[1, 1];
var w = mat[0, 2];
var z = mat[1, 2];
var r = ((2.0f * origNear) / x) * ((w + 1) * 0.5f);
var t = ((2.0f * origNear) / y) * ((z + 1) * 0.5f);
var l = ((2.0f * origNear) / x) * (((w + 1) * 0.5f) - 1);
var b = ((2.0f * origNear) / y) * (((z + 1) * 0.5f) - 1);
var ratio = (newNear / origNear);
r *= ratio;
t *= ratio;
l *= ratio;
b *= ratio;
var ret = new Matrix4x4();
ret[0, 0] = (2.0f * newNear) / (r - l); ret[0, 1] = 0; ret[0, 2] = (r + l) / (r - l); ret[0, 3] = 0;
ret[1, 0] = 0; ret[1, 1] = (2.0f * newNear) / (t - b); ret[1, 2] = (t + b) / (t - b); ret[1, 3] = 0;
ret[2, 0] = 0; ret[2, 1] = 0; ret[2, 2] = -(newFar + newNear) / (newFar - newNear); ret[2, 3] = -(2.0f * newFar * newNear) / (newFar - newNear);
ret[3, 0] = 0; ret[3, 1] = 0; ret[3, 2] = -1.0f; ret[3, 3] = 0;
return ret;
}
// Octahedron vertices
readonly Vector3[] m_OctaVerts =
{
new Vector3(0.0f, 1.0f, 0.0f), new Vector3(0.0f, 0.0f, -1.0f), new Vector3(1.0f, 0.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f), new Vector3(1.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f),
new Vector3(0.0f, 1.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f), new Vector3(-1.0f, 0.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f), new Vector3(-1.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, -1.0f),
new Vector3(0.0f, -1.0f, 0.0f), new Vector3(1.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, -1.0f),
new Vector3(0.0f, -1.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f), new Vector3(1.0f, 0.0f, 0.0f),
new Vector3(0.0f, -1.0f, 0.0f), new Vector3(-1.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f),
new Vector3(0.0f, -1.0f, 0.0f), new Vector3(0.0f, 0.0f, -1.0f), new Vector3(-1.0f, 0.0f, 0.0f),
};
Vector3 SubDivVert(Vector3 v1, Vector3 v2)
{
return Vector3.Normalize(v1 + v2);
}
void Subdivide(ICollection<Vector3> dest, Vector3 v1, Vector3 v2, Vector3 v3)
{
var v12 = SubDivVert(v1, v2);
var v23 = SubDivVert(v2, v3);
var v13 = SubDivVert(v1, v3);
dest.Add(v1);
dest.Add(v12);
dest.Add(v13);
dest.Add(v12);
dest.Add(v2);
dest.Add(v23);
dest.Add(v23);
dest.Add(v13);
dest.Add(v12);
dest.Add(v3);
dest.Add(v13);
dest.Add(v23);
}
void SubdivideYOnly(ICollection<Vector3> dest, Vector3 v1, Vector3 v2, Vector3 v3)
{
// Find out which vertex is furthest out from the others on the y axis
var d12 = Mathf.Abs(v2.y - v1.y);
var d23 = Mathf.Abs(v2.y - v3.y);
var d31 = Mathf.Abs(v3.y - v1.y);
Vector3 top, va, vb;
if (d12 < d23 && d12 < d31)
{
top = v3;
va = v1;
vb = v2;
}
else if (d23 < d12 && d23 < d31)
{
top = v1;
va = v2;
vb = v3;
}
else
{
top = v2;
va = v3;
vb = v1;
}
var v12 = SubDivVert(top, va);
var v13 = SubDivVert(top, vb);
dest.Add(top);
dest.Add(v12);
dest.Add(v13);
// A bit of extra logic to prevent triangle slivers: choose the shorter of (13->va), (12->vb) as triangle base
if ((v13 - va).sqrMagnitude > (v12 - vb).sqrMagnitude)
{
dest.Add(v12);
dest.Add(va);
dest.Add(vb);
dest.Add(v13);
dest.Add(v12);
dest.Add(vb);
}
else
{
dest.Add(v13);
dest.Add(v12);
dest.Add(va);
dest.Add(v13);
dest.Add(va);
dest.Add(vb);
}
}
Mesh m_Mesh;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#if !SILVERLIGHT
#if !CLR2
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Dynamic;
using ComTypes = System.Runtime.InteropServices.ComTypes;
namespace System.Management.Automation.ComInterop
{
internal sealed class ComInvokeBinder
{
private readonly ComMethodDesc _methodDesc;
private readonly Expression _method; // ComMethodDesc to be called
private readonly Expression _dispatch; // IDispatch
private readonly CallInfo _callInfo;
private readonly DynamicMetaObject[] _args;
private readonly bool[] _isByRef;
private readonly Expression _instance;
private BindingRestrictions _restrictions;
private VarEnumSelector _varEnumSelector;
private string[] _keywordArgNames;
private int _totalExplicitArgs; // Includes the individual elements of ArgumentKind.Dictionary (if any)
private ParameterExpression _dispatchObject;
private ParameterExpression _dispatchPointer;
private ParameterExpression _dispId;
private ParameterExpression _dispParams;
private ParameterExpression _paramVariants;
private ParameterExpression _invokeResult;
private ParameterExpression _returnValue;
private ParameterExpression _dispIdsOfKeywordArgsPinned;
private ParameterExpression _propertyPutDispId;
internal ComInvokeBinder(
CallInfo callInfo,
DynamicMetaObject[] args,
bool[] isByRef,
BindingRestrictions restrictions,
Expression method,
Expression dispatch,
ComMethodDesc methodDesc
)
{
Debug.Assert(callInfo != null, "arguments");
Debug.Assert(args != null, "args");
Debug.Assert(isByRef != null, "isByRef");
Debug.Assert(method != null, "method");
Debug.Assert(dispatch != null, "dispatch");
Debug.Assert(TypeUtils.AreReferenceAssignable(typeof(ComMethodDesc), method.Type), "method");
Debug.Assert(TypeUtils.AreReferenceAssignable(typeof(IDispatch), dispatch.Type), "dispatch");
_method = method;
_dispatch = dispatch;
_methodDesc = methodDesc;
_callInfo = callInfo;
_args = args;
_isByRef = isByRef;
_restrictions = restrictions;
// Set Instance to some value so that CallBinderHelper has the right number of parameters to work with
_instance = dispatch;
}
private ParameterExpression DispatchObjectVariable
{
get { return EnsureVariable(ref _dispatchObject, typeof(IDispatch), "dispatchObject"); }
}
private ParameterExpression DispatchPointerVariable
{
get { return EnsureVariable(ref _dispatchPointer, typeof(IntPtr), "dispatchPointer"); }
}
private ParameterExpression DispIdVariable
{
get { return EnsureVariable(ref _dispId, typeof(int), "dispId"); }
}
private ParameterExpression DispParamsVariable
{
get { return EnsureVariable(ref _dispParams, typeof(ComTypes.DISPPARAMS), "dispParams"); }
}
private ParameterExpression InvokeResultVariable
{
get { return EnsureVariable(ref _invokeResult, typeof(Variant), "invokeResult"); }
}
private ParameterExpression ReturnValueVariable
{
get { return EnsureVariable(ref _returnValue, typeof(object), "returnValue"); }
}
private ParameterExpression DispIdsOfKeywordArgsPinnedVariable
{
get { return EnsureVariable(ref _dispIdsOfKeywordArgsPinned, typeof(GCHandle), "dispIdsOfKeywordArgsPinned"); }
}
private ParameterExpression PropertyPutDispIdVariable
{
get { return EnsureVariable(ref _propertyPutDispId, typeof(int), "propertyPutDispId"); }
}
private ParameterExpression ParamVariantsVariable
{
get {
return _paramVariants ??
(_paramVariants = Expression.Variable(VariantArray.GetStructType(_args.Length), "paramVariants"));
}
}
private static ParameterExpression EnsureVariable(ref ParameterExpression var, Type type, string name)
{
if (var != null)
{
return var;
}
return var = Expression.Variable(type, name);
}
private static Type MarshalType(DynamicMetaObject mo, bool isByRef)
{
Type marshalType = (mo.Value == null && mo.HasValue && !mo.LimitType.IsValueType) ? null : mo.LimitType;
// we are not checking that mo.Expression is writeable or whether evaluating it has no sideeffects
// the assumption is that whoever matched it with ByRef arginfo took care of this.
if (isByRef)
{
// Null just means that null was supplied.
if (marshalType == null)
{
marshalType = mo.Expression.Type;
}
marshalType = marshalType.MakeByRefType();
}
return marshalType;
}
internal DynamicMetaObject Invoke()
{
_keywordArgNames = _callInfo.ArgumentNames.ToArray();
_totalExplicitArgs = _args.Length;
Type[] marshalArgTypes = new Type[_args.Length];
// We already tested the instance, so no need to test it again
for (int i = 0; i < _args.Length; i++)
{
DynamicMetaObject curMo = _args[i];
marshalArgTypes[i] = MarshalType(curMo, _isByRef[i]);
}
_varEnumSelector = new VarEnumSelector(marshalArgTypes);
return new DynamicMetaObject(
CreateScope(MakeIDispatchInvokeTarget()),
BindingRestrictions.Combine(_args).Merge(_restrictions)
);
}
private static void AddNotNull(List<ParameterExpression> list, ParameterExpression var)
{
if (var != null) list.Add(var);
}
private Expression CreateScope(Expression expression)
{
List<ParameterExpression> vars = new List<ParameterExpression>();
AddNotNull(vars, _dispatchObject);
AddNotNull(vars, _dispatchPointer);
AddNotNull(vars, _dispId);
AddNotNull(vars, _dispParams);
AddNotNull(vars, _paramVariants);
AddNotNull(vars, _invokeResult);
AddNotNull(vars, _returnValue);
AddNotNull(vars, _dispIdsOfKeywordArgsPinned);
AddNotNull(vars, _propertyPutDispId);
return vars.Count > 0 ? Expression.Block(vars, expression) : expression;
}
private Expression GenerateTryBlock()
{
//
// Declare variables
//
ParameterExpression excepInfo = Expression.Variable(typeof(ExcepInfo), "excepInfo");
ParameterExpression argErr = Expression.Variable(typeof(uint), "argErr");
ParameterExpression hresult = Expression.Variable(typeof(int), "hresult");
List<Expression> tryStatements = new List<Expression>();
Expression expr;
if (_keywordArgNames.Length > 0)
{
string[] names = _keywordArgNames.AddFirst(_methodDesc.Name);
tryStatements.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("rgdispidNamedArgs")
),
Expression.Call(typeof(UnsafeMethods).GetMethod("GetIdsOfNamedParameters"),
DispatchObjectVariable,
Expression.Constant(names),
DispIdVariable,
DispIdsOfKeywordArgsPinnedVariable
)
)
);
}
//
// Marshal the arguments to Variants
//
// For a call like this:
// comObj.Foo(100, 101, 102, x=123, z=125)
// DISPPARAMS needs to be setup like this:
// cArgs: 5
// cNamedArgs: 2
// rgArgs: 123, 125, 102, 101, 100
// rgdispidNamedArgs: dispid x, dispid z (the dispids of x and z respectively)
Expression[] parameters = MakeArgumentExpressions();
int reverseIndex = _varEnumSelector.VariantBuilders.Length - 1;
int positionalArgs = _varEnumSelector.VariantBuilders.Length - _keywordArgNames.Length; // args passed by position order and not by name
for (int i = 0; i < _varEnumSelector.VariantBuilders.Length; i++, reverseIndex--)
{
int variantIndex;
if (i >= positionalArgs)
{
// Named arguments are in order at the start of rgArgs
variantIndex = i - positionalArgs;
}
else
{
// Positional arguments are in reverse order at the tail of rgArgs
variantIndex = reverseIndex;
}
VariantBuilder variantBuilder = _varEnumSelector.VariantBuilders[i];
Expression marshal = variantBuilder.InitializeArgumentVariant(
VariantArray.GetStructField(ParamVariantsVariable, variantIndex),
parameters[i + 1]
);
if (marshal != null)
{
tryStatements.Add(marshal);
}
}
//
// Call Invoke
//
ComTypes.INVOKEKIND invokeKind;
if (_methodDesc.IsPropertyPut)
{
if (_methodDesc.IsPropertyPutRef)
{
invokeKind = ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF;
}
else
{
invokeKind = ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT;
}
}
else
{
// INVOKE_PROPERTYGET should only be needed for COM objects without typeinfo, where we might have to treat properties as methods
invokeKind = ComTypes.INVOKEKIND.INVOKE_FUNC | ComTypes.INVOKEKIND.INVOKE_PROPERTYGET;
}
MethodCallExpression invoke = Expression.Call(
typeof(UnsafeMethods).GetMethod("IDispatchInvoke"),
DispatchPointerVariable,
DispIdVariable,
Expression.Constant(invokeKind),
DispParamsVariable,
InvokeResultVariable,
excepInfo,
argErr
);
expr = Expression.Assign(hresult, invoke);
tryStatements.Add(expr);
//
// ComRuntimeHelpers.CheckThrowException(int hresult, ref ExcepInfo excepInfo, ComMethodDesc method, object args, uint argErr)
List<Expression> args = new List<Expression>();
foreach (Expression parameter in parameters)
{
args.Add(Expression.TypeAs(parameter, typeof(object)));
}
expr = Expression.Call(
typeof(ComRuntimeHelpers).GetMethod("CheckThrowException"),
hresult,
excepInfo,
Expression.Constant(_methodDesc, typeof(ComMethodDesc)),
Expression.NewArrayInit(typeof(object), args),
argErr
);
tryStatements.Add(expr);
//
// _returnValue = (ReturnType)_invokeResult.ToObject();
//
Expression invokeResultObject =
Expression.Call(
InvokeResultVariable,
typeof(Variant).GetMethod("ToObject"));
VariantBuilder[] variants = _varEnumSelector.VariantBuilders;
Expression[] parametersForUpdates = MakeArgumentExpressions();
tryStatements.Add(Expression.Assign(ReturnValueVariable, invokeResultObject));
for (int i = 0, n = variants.Length; i < n; i++)
{
Expression updateFromReturn = variants[i].UpdateFromReturn(parametersForUpdates[i + 1]);
if (updateFromReturn != null)
{
tryStatements.Add(updateFromReturn);
}
}
tryStatements.Add(Expression.Empty());
return Expression.Block(new[] { excepInfo, argErr, hresult }, tryStatements);
}
private Expression GenerateFinallyBlock()
{
List<Expression> finallyStatements = new List<Expression>();
//
// UnsafeMethods.IUnknownRelease(dispatchPointer);
//
finallyStatements.Add(
Expression.Call(
typeof(UnsafeMethods).GetMethod("IUnknownRelease"),
DispatchPointerVariable
)
);
//
// Clear memory allocated for marshalling
//
for (int i = 0, n = _varEnumSelector.VariantBuilders.Length; i < n; i++)
{
Expression clear = _varEnumSelector.VariantBuilders[i].Clear();
if (clear != null)
{
finallyStatements.Add(clear);
}
}
//
// _invokeResult.Clear()
//
finallyStatements.Add(
Expression.Call(
InvokeResultVariable,
typeof(Variant).GetMethod("Clear")
)
);
//
// _dispIdsOfKeywordArgsPinned.Free()
//
if (_dispIdsOfKeywordArgsPinned != null)
{
finallyStatements.Add(
Expression.Call(
DispIdsOfKeywordArgsPinnedVariable,
typeof(GCHandle).GetMethod("Free")
)
);
}
finallyStatements.Add(Expression.Empty());
return Expression.Block(finallyStatements);
}
/// <summary>
/// Create a stub for the target of the optimized lopop.
/// </summary>
/// <returns></returns>
private Expression MakeIDispatchInvokeTarget()
{
Debug.Assert(_varEnumSelector.VariantBuilders.Length == _totalExplicitArgs);
List<Expression> exprs = new List<Expression>();
//
// _dispId = ((DispCallable)this).ComMethodDesc.DispId;
//
exprs.Add(
Expression.Assign(
DispIdVariable,
Expression.Property(_method, typeof(ComMethodDesc).GetProperty("DispId"))
)
);
//
// _dispParams.rgvararg = RuntimeHelpers.UnsafeMethods.ConvertVariantByrefToPtr(ref _paramVariants._element0)
//
if (_totalExplicitArgs != 0)
{
exprs.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("rgvarg")
),
Expression.Call(
typeof(UnsafeMethods).GetMethod("ConvertVariantByrefToPtr"),
VariantArray.GetStructField(ParamVariantsVariable, 0)
)
)
);
}
//
// _dispParams.cArgs = <number_of_params>;
//
exprs.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("cArgs")
),
Expression.Constant(_totalExplicitArgs)
)
);
if (_methodDesc.IsPropertyPut)
{
//
// dispParams.cNamedArgs = 1;
// dispParams.rgdispidNamedArgs = RuntimeHelpers.UnsafeMethods.GetNamedArgsForPropertyPut()
//
exprs.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("cNamedArgs")
),
Expression.Constant(1)
)
);
exprs.Add(
Expression.Assign(
PropertyPutDispIdVariable,
Expression.Constant(ComDispIds.DISPID_PROPERTYPUT)
)
);
exprs.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("rgdispidNamedArgs")
),
Expression.Call(
typeof(UnsafeMethods).GetMethod("ConvertInt32ByrefToPtr"),
PropertyPutDispIdVariable
)
)
);
}
else
{
//
// _dispParams.cNamedArgs = N;
//
exprs.Add(
Expression.Assign(
Expression.Field(
DispParamsVariable,
typeof(ComTypes.DISPPARAMS).GetField("cNamedArgs")
),
Expression.Constant(_keywordArgNames.Length)
)
);
}
//
// _dispatchObject = _dispatch
// _dispatchPointer = Marshal.GetIDispatchForObject(_dispatchObject);
//
exprs.Add(Expression.Assign(DispatchObjectVariable, _dispatch));
exprs.Add(
Expression.Assign(
DispatchPointerVariable,
Expression.Call(
typeof(Marshal).GetMethod("GetIDispatchForObject"),
DispatchObjectVariable
)
)
);
Expression tryStatements = GenerateTryBlock();
Expression finallyStatements = GenerateFinallyBlock();
exprs.Add(Expression.TryFinally(tryStatements, finallyStatements));
exprs.Add(ReturnValueVariable);
var vars = new List<ParameterExpression>();
foreach (var variant in _varEnumSelector.VariantBuilders)
{
if (variant.TempVariable != null)
{
vars.Add(variant.TempVariable);
}
}
// If the method returns void, return AutomationNull
if (_methodDesc.ReturnType == typeof(void))
{
exprs.Add(System.Management.Automation.Language.ExpressionCache.AutomationNullConstant);
}
return Expression.Block(vars, exprs); ;
}
/// <summary>
/// Gets expressions to access all the arguments. This includes the instance argument.
/// </summary>
private Expression[] MakeArgumentExpressions()
{
Expression[] res;
int copy = 0;
if (_instance != null)
{
res = new Expression[_args.Length + 1];
res[copy++] = _instance;
}
else
{
res = new Expression[_args.Length];
}
for (int i = 0; i < _args.Length; i++)
{
res[copy++] = _args[i].Expression;
}
return res;
}
}
}
#endif
| |
using System;
using System.Collections;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Signers
{
/// <summary> ISO9796-2 - mechanism using a hash function with recovery (scheme 2 and 3).
/// <p>
/// Note: the usual length for the salt is the length of the hash
/// function used in bytes.</p>
/// </summary>
public class Iso9796d2PssSigner
: ISignerWithRecovery
{
/// <summary>
/// Return a reference to the recoveredMessage message.
/// </summary>
/// <returns>The full/partial recoveredMessage message.</returns>
/// <seealso cref="ISignerWithRecovery.GetRecoveredMessage"/>
public byte[] GetRecoveredMessage()
{
return recoveredMessage;
}
public const int TrailerImplicit = 0xBC;
public const int TrailerRipeMD160 = 0x31CC;
public const int TrailerRipeMD128 = 0x32CC;
public const int TrailerSha1 = 0x33CC;
public const int TrailerSha256 = 0x34CC;
public const int TrailerSha512 = 0x35CC;
public const int TrailerSha384 = 0x36CC;
public const int TrailerWhirlpool = 0x37CC;
private static readonly IDictionary trailerMap = Platform.CreateHashtable();
static Iso9796d2PssSigner()
{
trailerMap.Add("RIPEMD128", TrailerRipeMD128);
trailerMap.Add("RIPEMD160", TrailerRipeMD160);
trailerMap.Add("SHA-1", TrailerSha1);
trailerMap.Add("SHA-256", TrailerSha256);
trailerMap.Add("SHA-384", TrailerSha384);
trailerMap.Add("SHA-512", TrailerSha512);
trailerMap.Add("Whirlpool", TrailerWhirlpool);
}
private IDigest digest;
private IAsymmetricBlockCipher cipher;
private SecureRandom random;
private byte[] standardSalt;
private int hLen;
private int trailer;
private int keyBits;
private byte[] block;
private byte[] mBuf;
private int messageLength;
private readonly int saltLength;
private bool fullMessage;
private byte[] recoveredMessage;
private byte[] preSig;
private byte[] preBlock;
private int preMStart;
private int preTLength;
/// <summary>
/// Generate a signer for the with either implicit or explicit trailers
/// for ISO9796-2, scheme 2 or 3.
/// </summary>
/// <param name="cipher">base cipher to use for signature creation/verification</param>
/// <param name="digest">digest to use.</param>
/// <param name="saltLength">length of salt in bytes.</param>
/// <param name="isImplicit">whether or not the trailer is implicit or gives the hash.</param>
public Iso9796d2PssSigner(
IAsymmetricBlockCipher cipher,
IDigest digest,
int saltLength,
bool isImplicit)
{
this.cipher = cipher;
this.digest = digest;
this.hLen = digest.GetDigestSize();
this.saltLength = saltLength;
if (isImplicit)
{
trailer = TrailerImplicit;
}
else
{
string digestAlg = digest.AlgorithmName;
if (!trailerMap.Contains(digestAlg))
throw new ArgumentException("no valid trailer for digest");
trailer = (int)trailerMap[digestAlg];
}
}
/// <summary> Constructor for a signer with an explicit digest trailer.
///
/// </summary>
/// <param name="cipher">cipher to use.
/// </param>
/// <param name="digest">digest to sign with.
/// </param>
/// <param name="saltLength">length of salt in bytes.
/// </param>
public Iso9796d2PssSigner(
IAsymmetricBlockCipher cipher,
IDigest digest,
int saltLength)
: this(cipher, digest, saltLength, false)
{
}
public virtual string AlgorithmName
{
get { return digest.AlgorithmName + "with" + "ISO9796-2S2"; }
}
/// <summary>Initialise the signer.</summary>
/// <param name="forSigning">true if for signing, false if for verification.</param>
/// <param name="parameters">parameters for signature generation/verification. If the
/// parameters are for generation they should be a ParametersWithRandom,
/// a ParametersWithSalt, or just an RsaKeyParameters object. If RsaKeyParameters
/// are passed in a SecureRandom will be created.
/// </param>
/// <exception cref="ArgumentException">if wrong parameter type or a fixed
/// salt is passed in which is the wrong length.
/// </exception>
public virtual void Init(
bool forSigning,
ICipherParameters parameters)
{
RsaKeyParameters kParam;
if (parameters is ParametersWithRandom)
{
ParametersWithRandom p = (ParametersWithRandom) parameters;
kParam = (RsaKeyParameters) p.Parameters;
if (forSigning)
{
random = p.Random;
}
}
else if (parameters is ParametersWithSalt)
{
if (!forSigning)
throw new ArgumentException("ParametersWithSalt only valid for signing", "parameters");
ParametersWithSalt p = (ParametersWithSalt) parameters;
kParam = (RsaKeyParameters) p.Parameters;
standardSalt = p.GetSalt();
if (standardSalt.Length != saltLength)
throw new ArgumentException("Fixed salt is of wrong length");
}
else
{
kParam = (RsaKeyParameters) parameters;
if (forSigning)
{
random = new SecureRandom();
}
}
cipher.Init(forSigning, kParam);
keyBits = kParam.Modulus.BitLength;
block = new byte[(keyBits + 7) / 8];
if (trailer == TrailerImplicit)
{
mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 1];
}
else
{
mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 2];
}
Reset();
}
/// <summary> compare two byte arrays - constant time.</summary>
private bool IsSameAs(byte[] a, byte[] b)
{
if (messageLength != b.Length)
{
return false;
}
bool isOkay = true;
for (int i = 0; i != b.Length; i++)
{
if (a[i] != b[i])
{
isOkay = false;
}
}
return isOkay;
}
/// <summary> clear possible sensitive data</summary>
private void ClearBlock(
byte[] block)
{
Array.Clear(block, 0, block.Length);
}
public virtual void UpdateWithRecoveredMessage(
byte[] signature)
{
byte[] block = cipher.ProcessBlock(signature, 0, signature.Length);
//
// adjust block size for leading zeroes if necessary
//
if (block.Length < (keyBits + 7) / 8)
{
byte[] tmp = new byte[(keyBits + 7) / 8];
Array.Copy(block, 0, tmp, tmp.Length - block.Length, block.Length);
ClearBlock(block);
block = tmp;
}
int tLength;
if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0)
{
tLength = 1;
}
else
{
int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF);
string digestAlg = digest.AlgorithmName;
if (!trailerMap.Contains(digestAlg))
throw new ArgumentException("unrecognised hash in signature");
if (sigTrail != (int)trailerMap[digestAlg])
throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail);
tLength = 2;
}
//
// calculate H(m2)
//
byte[] m2Hash = new byte[hLen];
digest.DoFinal(m2Hash, 0);
//
// remove the mask
//
byte[] dbMask = MaskGeneratorFunction1(block, block.Length - hLen - tLength, hLen, block.Length - hLen - tLength);
for (int i = 0; i != dbMask.Length; i++)
{
block[i] ^= dbMask[i];
}
block[0] &= 0x7f;
//
// find out how much padding we've got
//
int mStart = 0;
while (mStart < block.Length)
{
if (block[mStart++] == 0x01)
break;
}
if (mStart >= block.Length)
{
ClearBlock(block);
}
fullMessage = (mStart > 1);
recoveredMessage = new byte[dbMask.Length - mStart - saltLength];
Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
recoveredMessage.CopyTo(mBuf, 0);
preSig = signature;
preBlock = block;
preMStart = mStart;
preTLength = tLength;
}
/// <summary> update the internal digest with the byte b</summary>
public virtual void Update(
byte input)
{
if (preSig == null && messageLength < mBuf.Length)
{
mBuf[messageLength++] = input;
}
else
{
digest.Update(input);
}
}
/// <summary> update the internal digest with the byte array in</summary>
public virtual void BlockUpdate(
byte[] input,
int inOff,
int length)
{
if (preSig == null)
{
while (length > 0 && messageLength < mBuf.Length)
{
this.Update(input[inOff]);
inOff++;
length--;
}
}
if (length > 0)
{
digest.BlockUpdate(input, inOff, length);
}
}
/// <summary> reset the internal state</summary>
public virtual void Reset()
{
digest.Reset();
messageLength = 0;
if (mBuf != null)
{
ClearBlock(mBuf);
}
if (recoveredMessage != null)
{
ClearBlock(recoveredMessage);
recoveredMessage = null;
}
fullMessage = false;
if (preSig != null)
{
preSig = null;
ClearBlock(preBlock);
preBlock = null;
}
}
/// <summary> Generate a signature for the loaded message using the key we were
/// initialised with.
/// </summary>
public virtual byte[] GenerateSignature()
{
int digSize = digest.GetDigestSize();
byte[] m2Hash = new byte[digSize];
digest.DoFinal(m2Hash, 0);
byte[] C = new byte[8];
LtoOSP(messageLength * 8, C);
digest.BlockUpdate(C, 0, C.Length);
digest.BlockUpdate(mBuf, 0, messageLength);
digest.BlockUpdate(m2Hash, 0, m2Hash.Length);
byte[] salt;
if (standardSalt != null)
{
salt = standardSalt;
}
else
{
salt = new byte[saltLength];
random.NextBytes(salt);
}
digest.BlockUpdate(salt, 0, salt.Length);
byte[] hash = new byte[digest.GetDigestSize()];
digest.DoFinal(hash, 0);
int tLength = 2;
if (trailer == TrailerImplicit)
{
tLength = 1;
}
int off = block.Length - messageLength - salt.Length - hLen - tLength - 1;
block[off] = (byte) (0x01);
Array.Copy(mBuf, 0, block, off + 1, messageLength);
Array.Copy(salt, 0, block, off + 1 + messageLength, salt.Length);
byte[] dbMask = MaskGeneratorFunction1(hash, 0, hash.Length, block.Length - hLen - tLength);
for (int i = 0; i != dbMask.Length; i++)
{
block[i] ^= dbMask[i];
}
Array.Copy(hash, 0, block, block.Length - hLen - tLength, hLen);
if (trailer == TrailerImplicit)
{
block[block.Length - 1] = (byte)TrailerImplicit;
}
else
{
block[block.Length - 2] = (byte) ((uint)trailer >> 8);
block[block.Length - 1] = (byte) trailer;
}
block[0] &= (byte) (0x7f);
byte[] b = cipher.ProcessBlock(block, 0, block.Length);
ClearBlock(mBuf);
ClearBlock(block);
messageLength = 0;
return b;
}
/// <summary> return true if the signature represents a ISO9796-2 signature
/// for the passed in message.
/// </summary>
public virtual bool VerifySignature(
byte[] signature)
{
//
// calculate H(m2)
//
byte[] m2Hash = new byte[hLen];
digest.DoFinal(m2Hash, 0);
byte[] block;
int tLength;
int mStart = 0;
if (preSig == null)
{
try
{
UpdateWithRecoveredMessage(signature);
}
catch (Exception)
{
return false;
}
}
else
{
if (!Arrays.AreEqual(preSig, signature))
{
throw new InvalidOperationException("UpdateWithRecoveredMessage called on different signature");
}
}
block = preBlock;
mStart = preMStart;
tLength = preTLength;
preSig = null;
preBlock = null;
//
// check the hashes
//
byte[] C = new byte[8];
LtoOSP(recoveredMessage.Length * 8, C);
digest.BlockUpdate(C, 0, C.Length);
if (recoveredMessage.Length != 0)
{
digest.BlockUpdate(recoveredMessage, 0, recoveredMessage.Length);
}
digest.BlockUpdate(m2Hash, 0, m2Hash.Length);
// Update for the salt
digest.BlockUpdate(block, mStart + recoveredMessage.Length, saltLength);
byte[] hash = new byte[digest.GetDigestSize()];
digest.DoFinal(hash, 0);
int off = block.Length - tLength - hash.Length;
bool isOkay = true;
for (int i = 0; i != hash.Length; i++)
{
if (hash[i] != block[off + i])
{
isOkay = false;
}
}
ClearBlock(block);
ClearBlock(hash);
if (!isOkay)
{
fullMessage = false;
ClearBlock(recoveredMessage);
return false;
}
//
// if they've input a message check what we've recovered against
// what was input.
//
if (messageLength != 0)
{
if (!IsSameAs(mBuf, recoveredMessage))
{
ClearBlock(mBuf);
return false;
}
messageLength = 0;
}
ClearBlock(mBuf);
return true;
}
/// <summary>
/// Return true if the full message was recoveredMessage.
/// </summary>
/// <returns>true on full message recovery, false otherwise, or if not sure.</returns>
/// <seealso cref="ISignerWithRecovery.HasFullMessage"/>
public virtual bool HasFullMessage()
{
return fullMessage;
}
/// <summary> int to octet string.</summary>
/// <summary> int to octet string.</summary>
private void ItoOSP(
int i,
byte[] sp)
{
sp[0] = (byte)((uint)i >> 24);
sp[1] = (byte)((uint)i >> 16);
sp[2] = (byte)((uint)i >> 8);
sp[3] = (byte)((uint)i >> 0);
}
/// <summary> long to octet string.</summary>
private void LtoOSP(long l, byte[] sp)
{
sp[0] = (byte)((ulong)l >> 56);
sp[1] = (byte)((ulong)l >> 48);
sp[2] = (byte)((ulong)l >> 40);
sp[3] = (byte)((ulong)l >> 32);
sp[4] = (byte)((ulong)l >> 24);
sp[5] = (byte)((ulong)l >> 16);
sp[6] = (byte)((ulong)l >> 8);
sp[7] = (byte)((ulong)l >> 0);
}
/// <summary> mask generator function, as described in Pkcs1v2.</summary>
private byte[] MaskGeneratorFunction1(
byte[] Z,
int zOff,
int zLen,
int length)
{
byte[] mask = new byte[length];
byte[] hashBuf = new byte[hLen];
byte[] C = new byte[4];
int counter = 0;
digest.Reset();
do
{
ItoOSP(counter, C);
digest.BlockUpdate(Z, zOff, zLen);
digest.BlockUpdate(C, 0, C.Length);
digest.DoFinal(hashBuf, 0);
Array.Copy(hashBuf, 0, mask, counter * hLen, hLen);
}
while (++counter < (length / hLen));
if ((counter * hLen) < length)
{
ItoOSP(counter, C);
digest.BlockUpdate(Z, zOff, zLen);
digest.BlockUpdate(C, 0, C.Length);
digest.DoFinal(hashBuf, 0);
Array.Copy(hashBuf, 0, mask, counter * hLen, mask.Length - (counter * hLen));
}
return mask;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.Transformations
{
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public class ReduceNumberOfTemporaries
{
//
// State
//
private readonly ControlFlowGraphStateForCodeTransformation m_cfg;
private VariableExpression[] m_variables;
private VariableExpression.Property[] m_varProps;
private Operator[] m_operators;
private Operator[][] m_useChains; // Operator[<variable index>][<Operator set>]
private Operator[][] m_defChains; // Operator[<variable index>][<Operator set>]
//
// Constructor Methods
//
private ReduceNumberOfTemporaries( ControlFlowGraphStateForCodeTransformation cfg )
{
m_cfg = cfg;
}
//
// Helper Methods
//
public static void Execute( ControlFlowGraphStateForCodeTransformation cfg )
{
cfg.TraceToFile( "ReduceNumberOfTemporaries" );
using(new PerformanceCounters.ContextualTiming( cfg, "ReduceNumberOfTemporaries" ))
{
ReduceNumberOfTemporaries pThis = new ReduceNumberOfTemporaries( cfg );
while(pThis.ExecuteSteps() == true)
{
Transformations.RemoveDeadCode.Execute( cfg, true );
}
}
}
private bool ExecuteSteps()
{
using(m_cfg.GroupLock( m_cfg.LockSpanningTree () ,
m_cfg.LockPropertiesOfVariables() ,
m_cfg.LockUseDefinitionChains () ))
{
m_variables = m_cfg.DataFlow_SpanningTree_Variables;
m_operators = m_cfg.DataFlow_SpanningTree_Operators;
m_useChains = m_cfg.DataFlow_UseChains;
m_defChains = m_cfg.DataFlow_DefinitionChains;
m_varProps = m_cfg.DataFlow_PropertiesOfVariables;
if(PropagateTemporaries ()) return true;
if(StrengthReduceForConditionalControlOperators()) return true;
if(PropagateConstantToChecks ()) return true;
return false;
}
}
//--//
private bool PropagateTemporaries()
{
bool fChanged = false;
foreach (VariableExpression var in m_variables)
{
int idx = var.SpanningTreeIndex;
// Only process temporary variables with a single definition.
if (!(var is TemporaryVariableExpression) || (m_defChains[idx].Length != 1))
{
continue;
}
Operator opDef = m_defChains[idx][0];
Operator[] opUses = m_useChains[idx];
// Skip variables with multiple uses.
if (opUses.Length != 1)
{
continue;
}
Operator opUse = opUses[0];
// Skip variables that are defined and used across basic block boundaries.
if (opUse.BasicBlock != opDef.BasicBlock)
{
continue;
}
int start = opDef.SpanningTreeIndex;
int end = opUse.SpanningTreeIndex;
Debug.Assert(start < end, "Variable used before being defined.");
VariableExpression exDef = opDef.FirstResult;
if (opDef is SingleAssignmentOperator)
{
//
// Detect pattern:
//
// $Temp = <var1>
// <op>: $Temp
//
// Convert into:
//
// <op>: <var1>
//
Expression exDefSrc = opDef.FirstArgument;
if (!IsRedefinedInRange(exDefSrc, start, end) &&
opUse.CanPropagateCopy(exDef, exDefSrc) &&
exDef.Type.CanBeAssignedFrom(exDefSrc.Type, null))
{
opUse.SubstituteUsage(exDef, exDefSrc);
fChanged = true;
}
}
else if (opDef is ZeroExtendOperator && opUse is BinaryConditionalControlOperator)
{
//
// Detect pattern:
//
// $TempA = zeroextend bool <var> from 8 bits
// if $TempA != ZERO then goto BasicBlock(T) else goto BasicBlock(F)
//
// Convert into:
//
// if <var> != ZERO then goto BasicBlock(T) else goto BasicBlock(F)
//
Expression exDefSrc = opDef.FirstArgument;
if (!IsRedefinedInRange(exDefSrc, start, end))
{
opDef.Delete();
opUse.SubstituteUsage(exDef, exDefSrc);
fChanged = true;
}
}
else if (opDef is CompareAndSetOperator && opUse is CompareAndSetOperator)
{
//
// Detect pattern:
//
// $TempA = <var1> <rel> <var2>
// $TempB = $TempA EQ.signed $Const(int 0)
//
// Convert into:
//
// $TempB = <var1> !<rel> <var2>
//
CompareAndSetOperator opCmpDef = (CompareAndSetOperator)opDef;
CompareAndSetOperator opCmpUse = (CompareAndSetOperator)opUse;
if (opCmpUse.Condition == CompareAndSetOperator.ActionCondition.EQ)
{
opCmpUse.EnsureConstantToTheRight();
ConstantExpression exRight = opCmpUse.SecondArgument as ConstantExpression;
if (exRight != null && exRight.IsEqualToZero())
{
CompareAndSetOperator opNew = CompareAndSetOperator.New(
opCmpDef.DebugInfo,
opCmpDef.InvertedCondition,
opCmpDef.Signed,
opCmpUse.FirstResult,
opCmpDef.FirstArgument,
opCmpDef.SecondArgument);
opUse.SubstituteWithOperator(opNew, Operator.SubstitutionFlags.Default);
opDef.Delete();
fChanged = true;
}
}
}
}
return fChanged;
}
private bool IsRedefinedInRange( Expression ex ,
int start ,
int end )
{
VariableExpression var = ex as VariableExpression;
if(var != null)
{
bool fAddressTaken = (m_varProps[ex.SpanningTreeIndex] & VariableExpression.Property.AddressTaken) != 0;
for(int i = start + 1; i < end; i++)
{
Operator op = m_operators[i];
if(ArrayUtility.FindInNotNullArray( op.Results, var ) >= 0)
{
return true;
}
if(op.MayWriteThroughPointerOperands && fAddressTaken)
{
return true;
}
}
}
return false;
}
//--//
private bool StrengthReduceForConditionalControlOperators()
{
bool fChanged = false;
foreach(Operator op in m_operators)
{
BinaryConditionalControlOperator opCtrl = op as BinaryConditionalControlOperator;
if(opCtrl != null)
{
Operator opPrev = opCtrl.GetPreviousOperator();
if(opPrev is SingleAssignmentOperator)
{
//
// Detect pattern:
//
// <varA> = <varB>
// if <varA> != ZERO then goto BasicBlock(T) else goto BasicBlock(T)
//
// Convert into:
//
// <varA> = <varB>
// if <varB> != ZERO then goto BasicBlock(T) else goto BasicBlock(T)
//
VariableExpression exSrc = opPrev.FirstResult;
Expression exDst = opCtrl.FirstArgument;
if(exSrc == exDst)
{
opCtrl.SubstituteUsage( exDst, opPrev.FirstArgument );
fChanged = true;
}
}
else if(opPrev is CompareAndSetOperator)
{
//
// Detect pattern:
//
// <var3> = <var1> <rel> <var2>
// if <var3> != ZERO then goto BasicBlock(T) else goto BasicBlock(T)
//
// Convert into:
//
// <var3> = <var1> <rel> <var2>
// if <var1> <rel> <var2> then goto BasicBlock(T) else goto BasicBlock(T)
//
CompareAndSetOperator opPrevCmp = (CompareAndSetOperator)opPrev;
VariableExpression exSrc = opPrevCmp.FirstResult;
Expression exDst = opCtrl.FirstArgument;
if(exSrc == exDst)
{
CompareConditionalControlOperator ctrl = CompareConditionalControlOperator.New( opPrevCmp.DebugInfo, opPrevCmp.Condition, opPrevCmp.Signed, opPrevCmp.FirstArgument, opPrevCmp.SecondArgument, opCtrl.TargetBranchNotTaken, opCtrl.TargetBranchTaken );
opCtrl.SubstituteWithOperator( ctrl, Operator.SubstitutionFlags.Default );
fChanged = true;
}
}
}
}
return fChanged;
}
//--//
private bool PropagateConstantToChecks()
{
bool fChanged = false;
//
// If a variable is only used in a BinaryConditionalControlOperator,
// try to replicate the check close to all the definitions of the variable.
// Some definitions could be constants and the checks will straighten out.
//
foreach(VariableExpression var in m_variables)
{
BinaryConditionalControlOperator op = ControlFlowGraphState.CheckSingleUse( m_useChains, var ) as BinaryConditionalControlOperator;
if(op != null)
{
foreach(Operator def in m_defChains[var.SpanningTreeIndex])
{
if(CanPropagate( def, op ))
{
ControlOperator opCtrl = null;
if(def is SingleAssignmentOperator)
{
ConstantExpression exConst = def.FirstArgument as ConstantExpression;
if(exConst != null && exConst.IsValueInteger)
{
opCtrl = UnconditionalControlOperator.New( op.DebugInfo, exConst.IsEqualToZero() ? op.TargetBranchNotTaken : op.TargetBranchTaken );
}
}
if(opCtrl == null)
{
opCtrl = BinaryConditionalControlOperator.New( op.DebugInfo, op.FirstArgument, op.TargetBranchNotTaken, op.TargetBranchTaken );
}
def.BasicBlock.FlowControl.SubstituteWithOperator( opCtrl, Operator.SubstitutionFlags.Default );
fChanged = true;
}
}
}
}
return fChanged;
}
private static bool CanPropagate( Operator def ,
BinaryConditionalControlOperator op )
{
var defBB = def.BasicBlock;
var opBB = op .BasicBlock;
if(defBB == opBB)
{
return false;
}
if(!(defBB is NormalBasicBlock) ||
!(opBB is NormalBasicBlock) )
{
return false;
}
def = def.GetNextOperator();
//
// Make sure all the operators between 'def' and 'op' are either Nops or unconditional branches.
//
while(def != null)
{
if(def == op)
{
return true;
}
if(def is NopOperator)
{
def = def.GetNextOperator();
continue;
}
UnconditionalControlOperator ctrl = def as UnconditionalControlOperator;
if(ctrl != null)
{
def = ctrl.TargetBranch.Operators[0];
continue;
}
break;
}
return false;
}
}
}
| |
// 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.Collections.Generic;
using Xunit;
using Microsoft.Xunit.Performance;
namespace System.Text.RegularExpressions.Tests
{
/// <summary>
/// Performance tests for Regular Expressions
/// </summary>
public class Perf_Regex
{
private const int InnerIterations = 100;
[Benchmark]
[MeasureGCAllocations]
public void Match()
{
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
{
for (int i = 0; i < InnerIterations; i++)
{
foreach(var test in Match_TestData())
Regex.Match((string)test[1], (string)test[0], (RegexOptions)test[2]);
}
}
}
// A series of patterns (all valid and non pathological) and inputs (which they may or may not match)
public static IEnumerable<object[]> Match_TestData()
{
yield return new object[] { "[abcd-[d]]+", "dddaabbccddd", RegexOptions.None };
yield return new object[] { @"[\d-[357]]+", "33312468955", RegexOptions.None };
yield return new object[] { @"[\d-[357]]+", "51246897", RegexOptions.None };
yield return new object[] { @"[\d-[357]]+", "3312468977", RegexOptions.None };
yield return new object[] { @"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None };
yield return new object[] { @"[\w-[\d]]+", "0AZaz9", RegexOptions.None };
yield return new object[] { @"[\w-[\p{Ll}]]+", "a09AZz", RegexOptions.None };
yield return new object[] { @"[\d-[13579]]+", "1024689", RegexOptions.ECMAScript };
yield return new object[] { @"[\d-[13579]]+", "\x066102468\x0660", RegexOptions.ECMAScript };
yield return new object[] { @"[\d-[13579]]+", "\x066102468\x0660", RegexOptions.None };
yield return new object[] { @"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None };
yield return new object[] { @"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None };
yield return new object[] { @"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None };
yield return new object[] { @"[\p{Ll}-[ae-z]]+", "aaabbbcccdddeee", RegexOptions.None };
yield return new object[] { @"[\p{Nd}-[2468]]+", "20135798", RegexOptions.None };
yield return new object[] { @"[\P{Lu}-[ae-z]]+", "aaabbbcccdddeee", RegexOptions.None };
yield return new object[] { @"[\P{Nd}-[\p{Ll}]]+", "az09AZ'[]", RegexOptions.None };
yield return new object[] { "[abcd-[def]]+", "fedddaabbccddd", RegexOptions.None };
yield return new object[] { @"[\d-[357a-z]]+", "az33312468955", RegexOptions.None };
yield return new object[] { @"[\d-[de357fgA-Z]]+", "AZ51246897", RegexOptions.None };
yield return new object[] { @"[\d-[357\p{Ll}]]+", "az3312468977", RegexOptions.None };
yield return new object[] { @"[\w-[b-y\s]]+", " \tbbbaaaABCD09zzzyyy", RegexOptions.None };
yield return new object[] { @"[\w-[\d\p{Po}]]+", "!#0AZaz9", RegexOptions.None };
yield return new object[] { @"[\w-[\p{Ll}\s]]+", "a09AZz", RegexOptions.None };
yield return new object[] { @"[\d-[13579a-zA-Z]]+", "AZ1024689", RegexOptions.ECMAScript };
yield return new object[] { @"[\d-[13579abcd]]+", "abcd\x066102468\x0660", RegexOptions.ECMAScript };
yield return new object[] { @"[\d-[13579\s]]+", " \t\x066102468\x0660", RegexOptions.None };
yield return new object[] { @"[\w-[b-y\p{Po}]]+", "!#bbbaaaABCD09zzzyyy", RegexOptions.None };
yield return new object[] { @"[\w-[b-y!.,]]+", "!.,bbbaaaABCD09zzzyyy", RegexOptions.None };
yield return new object[] { "[\\w-[b-y\x00-\x0F]]+", "\0bbbaaaABCD09zzzyyy", RegexOptions.None };
yield return new object[] { @"[\p{Ll}-[ae-z0-9]]+", "09aaabbbcccdddeee", RegexOptions.None };
yield return new object[] { @"[\p{Nd}-[2468az]]+", "az20135798", RegexOptions.None };
yield return new object[] { @"[\P{Lu}-[ae-zA-Z]]+", "AZaaabbbcccdddeee", RegexOptions.None };
yield return new object[] { @"[\P{Nd}-[\p{Ll}0123456789]]+", "09az09AZ'[]", RegexOptions.None };
yield return new object[] { "[abc-[defg]]+", "dddaabbccddd", RegexOptions.None };
yield return new object[] { @"[\d-[abc]]+", "abc09abc", RegexOptions.None };
yield return new object[] { @"[\d-[a-zA-Z]]+", "az09AZ", RegexOptions.None };
yield return new object[] { @"[\d-[\p{Ll}]]+", "az09az", RegexOptions.None };
yield return new object[] { @"[\w-[\x00-\x0F]]+", "bbbaaaABYZ09zzzyyy", RegexOptions.None };
yield return new object[] { @"[\w-[\s]]+", "0AZaz9", RegexOptions.None };
yield return new object[] { @"[\w-[\W]]+", "0AZaz9", RegexOptions.None };
yield return new object[] { @"[\w-[\p{Po}]]+", "#a09AZz!", RegexOptions.None };
yield return new object[] { @"[\d-[\D]]+", "azAZ1024689", RegexOptions.ECMAScript };
yield return new object[] { @"[\d-[a-zA-Z]]+", "azAZ\x066102468\x0660", RegexOptions.ECMAScript };
yield return new object[] { @"[\d-[\p{Ll}]]+", "\x066102468\x0660", RegexOptions.None };
yield return new object[] { @"[a-zA-Z0-9-[\s]]+", " \tazAZ09", RegexOptions.None };
yield return new object[] { @"[a-zA-Z0-9-[\W]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None };
yield return new object[] { @"[a-zA-Z0-9-[^a-zA-Z0-9]]+", "bbbaaaABCD09zzzyyy", RegexOptions.None };
yield return new object[] { @"[\p{Ll}-[A-Z]]+", "AZaz09", RegexOptions.None };
yield return new object[] { @"[\p{Nd}-[a-z]]+", "az09", RegexOptions.None };
yield return new object[] { @"[\P{Lu}-[\p{Lu}]]+", "AZazAZ", RegexOptions.None };
yield return new object[] { @"[\P{Lu}-[A-Z]]+", "AZazAZ", RegexOptions.None };
yield return new object[] { @"[\P{Nd}-[\p{Nd}]]+", "azAZ09", RegexOptions.None };
yield return new object[] { @"[\P{Nd}-[2-8]]+", "1234567890azAZ1234567890", RegexOptions.None };
yield return new object[] { @"([ ]|[\w-[0-9]])+", "09az AZ90", RegexOptions.None };
yield return new object[] { @"([0-9-[02468]]|[0-9-[13579]])+", "az1234567890za", RegexOptions.None };
yield return new object[] { @"([^0-9-[a-zAE-Z]]|[\w-[a-zAF-Z]])+", "azBCDE1234567890BCDEFza", RegexOptions.None };
yield return new object[] { @"([\p{Ll}-[aeiou]]|[^\w-[\s]])+", "aeiobcdxyz!@#aeio", RegexOptions.None };
yield return new object[] { @"98[\d-[9]][\d-[8]][\d-[0]]", "98911 98881 98870 98871", RegexOptions.None };
yield return new object[] { @"m[\w-[^aeiou]][\w-[^aeiou]]t", "mbbt mect meet", RegexOptions.None };
yield return new object[] { "[abcdef-[^bce]]+", "adfbcefda", RegexOptions.None };
yield return new object[] { "[^cde-[ag]]+", "agbfxyzga", RegexOptions.None };
yield return new object[] { @"[\p{L}-[^\p{Lu}]]+", "09',.abcxyzABCXYZ", RegexOptions.None };
yield return new object[] { @"[\p{IsGreek}-[\P{Lu}]]+", "\u0390\u03FE\u0386\u0388\u03EC\u03EE\u0400", RegexOptions.None };
yield return new object[] { @"[\p{IsBasicLatin}-[G-L]]+", "GAFMZL", RegexOptions.None };
yield return new object[] { "[a-zA-Z-[aeiouAEIOU]]+", "aeiouAEIOUbcdfghjklmnpqrstvwxyz", RegexOptions.None };
yield return new object[] { @"^
(?<octet>^
(
(
(?<Octet2xx>[\d-[013-9]])
|
[\d-[2-9]]
)
(?(Octet2xx)
(
(?<Octet25x>[\d-[01-46-9]])
|
[\d-[5-9]]
)
(
(?(Octet25x)
[\d-[6-9]]
|
[\d]
)
)
|
[\d]{2}
)
)
|
([\d][\d])
|
[\d]
)$"
, "255", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { @"[abcd\-d-[bc]]+", "bbbaaa---dddccc", RegexOptions.None };
yield return new object[] { @"[abcd\-d-[bc]]+", "bbbaaa---dddccc", RegexOptions.None };
yield return new object[] { @"[^a-f-[\x00-\x60\u007B-\uFFFF]]+", "aaafffgggzzz{{{", RegexOptions.None };
yield return new object[] { @"[\[\]a-f-[[]]+", "gggaaafff]]][[[", RegexOptions.None };
yield return new object[] { @"[\[\]a-f-[]]]+", "gggaaafff[[[]]]", RegexOptions.None };
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "a]]", RegexOptions.None };
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "b]]", RegexOptions.None };
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "c]]", RegexOptions.None };
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "d]]", RegexOptions.None };
yield return new object[] { @"[ab\-\[cd-[[]]]]", "a]]", RegexOptions.None };
yield return new object[] { @"[ab\-\[cd-[[]]]]", "b]]", RegexOptions.None };
yield return new object[] { @"[ab\-\[cd-[[]]]]", "c]]", RegexOptions.None };
yield return new object[] { @"[ab\-\[cd-[[]]]]", "d]]", RegexOptions.None };
yield return new object[] { @"[ab\-\[cd-[[]]]]", "-]]", RegexOptions.None };
yield return new object[] { @"[a-[c-e]]+", "bbbaaaccc", RegexOptions.None };
yield return new object[] { @"[a-[c-e]]+", "```aaaccc", RegexOptions.None };
yield return new object[] { @"[a-d\--[bc]]+", "cccaaa--dddbbb", RegexOptions.None };
yield return new object[] { @"[\0- [bc]+", "!!!\0\0\t\t [[[[bbbcccaaa", RegexOptions.None };
yield return new object[] { "[[abcd]-[bc]]+", "a-b]", RegexOptions.None };
yield return new object[] { "[-[e-g]+", "ddd[[[---eeefffggghhh", RegexOptions.None };
yield return new object[] { "[-e-g]+", "ddd---eeefffggghhh", RegexOptions.None };
yield return new object[] { "[-e-g]+", "ddd---eeefffggghhh", RegexOptions.None };
yield return new object[] { "[a-e - m-p]+", "---a b c d e m n o p---", RegexOptions.None };
yield return new object[] { "[^-[bc]]", "b] c] -] aaaddd]", RegexOptions.None };
yield return new object[] { "[^-[bc]]", "b] c] -] aaa]ddd]", RegexOptions.None };
yield return new object[] { @"[a\-[bc]+", "```bbbaaa---[[[cccddd", RegexOptions.None };
yield return new object[] { @"[a\-[\-\-bc]+", "```bbbaaa---[[[cccddd", RegexOptions.None };
yield return new object[] { @"[a\-\[\-\[\-bc]+", "```bbbaaa---[[[cccddd", RegexOptions.None };
yield return new object[] { @"[abc\--[b]]+", "[[[```bbbaaa---cccddd", RegexOptions.None };
yield return new object[] { @"[abc\-z-[b]]+", "```aaaccc---zzzbbb", RegexOptions.None };
yield return new object[] { @"[a-d\-[b]+", "```aaabbbcccddd----[[[[]]]", RegexOptions.None };
yield return new object[] { @"[abcd\-d\-[bc]+", "bbbaaa---[[[dddccc", RegexOptions.None };
yield return new object[] { "[a - c - [ b ] ]+", "dddaaa ccc [[[[ bbb ]]]", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { "[a - c - [ b ] +", "dddaaa ccc [[[[ bbb ]]]", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { @"(\p{Lu}\w*)\s(\p{Lu}\w*)", "Hello World", RegexOptions.None };
yield return new object[] { @"(\p{Lu}\p{Ll}*)\s(\p{Lu}\p{Ll}*)", "Hello World", RegexOptions.None };
yield return new object[] { @"(\P{Ll}\p{Ll}*)\s(\P{Ll}\p{Ll}*)", "Hello World", RegexOptions.None };
yield return new object[] { @"(\P{Lu}+\p{Lu})\s(\P{Lu}+\p{Lu})", "hellO worlD", RegexOptions.None };
yield return new object[] { @"(\p{Lt}\w*)\s(\p{Lt}*\w*)", "\u01C5ello \u01C5orld", RegexOptions.None };
yield return new object[] { @"(\P{Lt}\w*)\s(\P{Lt}*\w*)", "Hello World", RegexOptions.None };
yield return new object[] { @"[@-D]+", "eE?@ABCDabcdeE", RegexOptions.IgnoreCase };
yield return new object[] { @"[>-D]+", "eE=>?@ABCDabcdeE", RegexOptions.IgnoreCase };
yield return new object[] { @"[\u0554-\u0557]+", "\u0583\u0553\u0554\u0555\u0556\u0584\u0585\u0586\u0557\u0558", RegexOptions.IgnoreCase };
yield return new object[] { @"[X-\]]+", "wWXYZxyz[\\]^", RegexOptions.IgnoreCase };
yield return new object[] { @"[X-\u0533]+", "\u0551\u0554\u0560AXYZaxyz\u0531\u0532\u0533\u0561\u0562\u0563\u0564", RegexOptions.IgnoreCase };
yield return new object[] { @"[X-a]+", "wWAXYZaxyz", RegexOptions.IgnoreCase };
yield return new object[] { @"[X-c]+", "wWABCXYZabcxyz", RegexOptions.IgnoreCase };
yield return new object[] { @"[X-\u00C0]+", "\u00C1\u00E1\u00C0\u00E0wWABCXYZabcxyz", RegexOptions.IgnoreCase };
yield return new object[] { @"[\u0100\u0102\u0104]+", "\u00FF \u0100\u0102\u0104\u0101\u0103\u0105\u0106", RegexOptions.IgnoreCase };
yield return new object[] { @"[B-D\u0130]+", "aAeE\u0129\u0131\u0068 BCDbcD\u0130\u0069\u0070", RegexOptions.IgnoreCase };
yield return new object[] { @"[\u013B\u013D\u013F]+", "\u013A\u013B\u013D\u013F\u013C\u013E\u0140\u0141", RegexOptions.IgnoreCase };
yield return new object[] { "(Cat)\r(Dog)", "Cat\rDog", RegexOptions.None };
yield return new object[] { "(Cat)\t(Dog)", "Cat\tDog", RegexOptions.None };
yield return new object[] { "(Cat)\f(Dog)", "Cat\fDog", RegexOptions.None };
yield return new object[] { @"{5", "hello {5 world", RegexOptions.None };
yield return new object[] { @"{5,", "hello {5, world", RegexOptions.None };
yield return new object[] { @"{5,6", "hello {5,6 world", RegexOptions.None };
yield return new object[] { @"(?n:(?<cat>cat)(\s+)(?<dog>dog))", "cat dog", RegexOptions.None };
yield return new object[] { @"(?n:(cat)(\s+)(dog))", "cat dog", RegexOptions.None };
yield return new object[] { @"(?n:(cat)(?<SpaceChars>\s+)(dog))", "cat dog", RegexOptions.None };
yield return new object[] { @"(?x:
(?<cat>cat) # Cat statement
(\s+) # Whitespace chars
(?<dog>dog # Dog statement
))", "cat dog", RegexOptions.None };
yield return new object[] { @"(?+i:cat)", "CAT", RegexOptions.None };
yield return new object[] { @"cat([\d]*)dog", "hello123cat230927dog1412d", RegexOptions.None };
yield return new object[] { @"([\D]*)dog", "65498catdog58719", RegexOptions.None };
yield return new object[] { @"cat([\s]*)dog", "wiocat dog3270", RegexOptions.None };
yield return new object[] { @"cat([\S]*)", "sfdcatdog 3270", RegexOptions.None };
yield return new object[] { @"cat([\w]*)", "sfdcatdog 3270", RegexOptions.None };
yield return new object[] { @"cat([\W]*)dog", "wiocat dog3270", RegexOptions.None };
yield return new object[] { @"([\p{Lu}]\w*)\s([\p{Lu}]\w*)", "Hello World", RegexOptions.None };
yield return new object[] { @"([\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", "Hello World", RegexOptions.None };
yield return new object[] { @"(cat)([\x41]*)(dog)", "catAAAdog", RegexOptions.None };
yield return new object[] { @"(cat)([\u0041]*)(dog)", "catAAAdog", RegexOptions.None };
yield return new object[] { @"(cat)([\a]*)(dog)", "cat\a\a\adog", RegexOptions.None };
yield return new object[] { @"(cat)([\b]*)(dog)", "cat\b\b\bdog", RegexOptions.None };
yield return new object[] { @"(cat)([\e]*)(dog)", "cat\u001B\u001B\u001Bdog", RegexOptions.None };
yield return new object[] { @"(cat)([\f]*)(dog)", "cat\f\f\fdog", RegexOptions.None };
yield return new object[] { @"(cat)([\r]*)(dog)", "cat\r\r\rdog", RegexOptions.None };
yield return new object[] { @"(cat)([\v]*)(dog)", "cat\v\v\vdog", RegexOptions.None };
yield return new object[] { @"cat([\d]*)dog", "hello123cat230927dog1412d", RegexOptions.ECMAScript };
yield return new object[] { @"([\D]*)dog", "65498catdog58719", RegexOptions.ECMAScript };
yield return new object[] { @"cat([\s]*)dog", "wiocat dog3270", RegexOptions.ECMAScript };
yield return new object[] { @"cat([\S]*)", "sfdcatdog 3270", RegexOptions.ECMAScript };
yield return new object[] { @"cat([\w]*)", "sfdcatdog 3270", RegexOptions.ECMAScript };
yield return new object[] { @"cat([\W]*)dog", "wiocat dog3270", RegexOptions.ECMAScript };
yield return new object[] { @"([\p{Lu}]\w*)\s([\p{Lu}]\w*)", "Hello World", RegexOptions.ECMAScript };
yield return new object[] { @"([\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", "Hello World", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)\d*dog", "hello123cat230927dog1412d", RegexOptions.ECMAScript };
yield return new object[] { @"\D*(dog)", "65498catdog58719", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)\s*(dog)", "wiocat dog3270", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)\S*", "sfdcatdog 3270", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)\w*", "sfdcatdog 3270", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)\W*(dog)", "wiocat dog3270", RegexOptions.ECMAScript };
yield return new object[] { @"\p{Lu}(\w*)\s\p{Lu}(\w*)", "Hello World", RegexOptions.ECMAScript };
yield return new object[] { @"\P{Ll}\p{Ll}*\s\P{Ll}\p{Ll}*", "Hello World", RegexOptions.ECMAScript };
yield return new object[] { @"cat(?<dog121>dog)", "catcatdogdogcat", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s*(?<cat>dog)", "catcat dogdogcat", RegexOptions.None };
yield return new object[] { @"(?<1>cat)\s*(?<1>dog)", "catcat dogdogcat", RegexOptions.None };
yield return new object[] { @"(?<2048>cat)\s*(?<2048>dog)", "catcat dogdogcat", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\w+(?<dog-cat>dog)", "cat_Hello_World_dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\w+(?<-cat>dog)", "cat_Hello_World_dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\w+(?<cat-cat>dog)", "cat_Hello_World_dog", RegexOptions.None };
yield return new object[] { @"(?<1>cat)\w+(?<dog-1>dog)", "cat_Hello_World_dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\w+(?<2-cat>dog)", "cat_Hello_World_dog", RegexOptions.None };
yield return new object[] { @"(?<1>cat)\w+(?<2-1>dog)", "cat_Hello_World_dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat){", "STARTcat{", RegexOptions.None };
yield return new object[] { @"(?<cat>cat){fdsa", "STARTcat{fdsa", RegexOptions.None };
yield return new object[] { @"(?<cat>cat){1", "STARTcat{1", RegexOptions.None };
yield return new object[] { @"(?<cat>cat){1END", "STARTcat{1END", RegexOptions.None };
yield return new object[] { @"(?<cat>cat){1,", "STARTcat{1,", RegexOptions.None };
yield return new object[] { @"(?<cat>cat){1,END", "STARTcat{1,END", RegexOptions.None };
yield return new object[] { @"(?<cat>cat){1,2", "STARTcat{1,2", RegexOptions.None };
yield return new object[] { @"(?<cat>cat){1,2END", "STARTcat{1,2END", RegexOptions.None };
yield return new object[] { @"(cat) #cat
\s+ #followed by 1 or more whitespace
(dog) #followed by dog
", "cat dog", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { @"(cat) #cat
\s+ #followed by 1 or more whitespace
(dog) #followed by dog", "cat dog", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { @"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace) (dog) (?#followed by dog)", "cat dog", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { @"(?<cat>cat)(?<dog>dog)\k<cat>", "asdfcatdogcatdog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\k<cat>", "asdfcat dogcat dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\k'cat'", "asdfcat dogcat dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\<cat>", "asdfcat dogcat dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\'cat'", "asdfcat dogcat dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\k<1>", "asdfcat dogcat dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\k'1'", "asdfcat dogcat dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\<1>", "asdfcat dogcat dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\'1'", "asdfcat dogcat dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\1", "asdfcat dogcat dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\1", "asdfcat dogcat dog", RegexOptions.ECMAScript };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\k<dog>", "asdfcat dogdog dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\2", "asdfcat dogdog dog", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\2", "asdfcat dogdog dog", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)(\077)", "hellocat?dogworld", RegexOptions.None };
yield return new object[] { @"(cat)(\77)", "hellocat?dogworld", RegexOptions.None };
yield return new object[] { @"(cat)(\176)", "hellocat~dogworld", RegexOptions.None };
yield return new object[] { @"(cat)(\400)", "hellocat\0dogworld", RegexOptions.None };
yield return new object[] { @"(cat)(\300)", "hellocat\u00C0dogworld", RegexOptions.None };
yield return new object[] { @"(cat)(\300)", "hellocat\u00C0dogworld", RegexOptions.None };
yield return new object[] { @"(cat)(\477)", "hellocat\u003Fdogworld", RegexOptions.None };
yield return new object[] { @"(cat)(\777)", "hellocat\u00FFdogworld", RegexOptions.None };
yield return new object[] { @"(cat)(\7770)", "hellocat\u00FF0dogworld", RegexOptions.None };
yield return new object[] { @"(cat)(\077)", "hellocat?dogworld", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)(\77)", "hellocat?dogworld", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)(\7)", "hellocat\adogworld", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)(\40)", "hellocat dogworld", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)(\040)", "hellocat dogworld", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)(\176)", "hellocatcat76dogworld", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)(\377)", "hellocat\u00FFdogworld", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)(\400)", "hellocat 0Fdogworld", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)\s+(?<2147483646>dog)", "asdlkcat dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)\s+(?<2147483647>dog)", "asdlkcat dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\x2a*)(dog)", "asdlkcat***dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\x2b*)(dog)", "asdlkcat+++dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\x2c*)(dog)", "asdlkcat,,,dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\x2d*)(dog)", "asdlkcat---dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\x2e*)(dog)", "asdlkcat...dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\x2A*)(dog)", "asdlkcat***dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\x2B*)(dog)", "asdlkcat+++dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\x2C*)(dog)", "asdlkcat,,,dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\x2D*)(dog)", "asdlkcat---dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\x2E*)(dog)", "asdlkcat...dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\c@*)(dog)", "asdlkcat\0\0dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\cA*)(dog)", "asdlkcat\u0001dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\ca*)(dog)", "asdlkcat\u0001dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\cC*)(dog)", "asdlkcat\u0003dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\cc*)(dog)", "asdlkcat\u0003dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\cD*)(dog)", "asdlkcat\u0004dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\cd*)(dog)", "asdlkcat\u0004dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\cX*)(dog)", "asdlkcat\u0018dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\cx*)(dog)", "asdlkcat\u0018dogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\cZ*)(dog)", "asdlkcat\u001adogiwod", RegexOptions.None };
yield return new object[] { @"(cat)(\cz*)(dog)", "asdlkcat\u001adogiwod", RegexOptions.None };
yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\n dog", RegexOptions.None };
yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\n dog", RegexOptions.Multiline };
yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\n dog", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog", RegexOptions.None };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog", RegexOptions.Multiline };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog\n", RegexOptions.None };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog\n", RegexOptions.Multiline };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat \n\n\n dog\n", RegexOptions.ECMAScript };
yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog", RegexOptions.None };
yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog", RegexOptions.Multiline };
yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog", RegexOptions.ECMAScript };
yield return new object[] { @"\b@cat", "123START123@catEND", RegexOptions.None };
yield return new object[] { @"\b\<cat", "123START123<catEND", RegexOptions.None };
yield return new object[] { @"\b,cat", "satwe,,,START,catEND", RegexOptions.None };
yield return new object[] { @"\b\[cat", "`12START123[catEND", RegexOptions.None };
yield return new object[] { @"\B@cat", "123START123;@catEND", RegexOptions.None };
yield return new object[] { @"\B\<cat", "123START123'<catEND", RegexOptions.None };
yield return new object[] { @"\B,cat", "satwe,,,START',catEND", RegexOptions.None };
yield return new object[] { @"\B\[cat", "`12START123'[catEND", RegexOptions.None };
yield return new object[] { @"(\w+)\s+(\w+)", "cat\u02b0 dog\u02b1", RegexOptions.None };
yield return new object[] { @"(cat\w+)\s+(dog\w+)", "STARTcat\u30FC dog\u3005END", RegexOptions.None };
yield return new object[] { @"(cat\w+)\s+(dog\w+)", "STARTcat\uff9e dog\uff9fEND", RegexOptions.None };
yield return new object[] { @"[^a]|d", "d", RegexOptions.None };
yield return new object[] { @"([^a]|[d])*", "Hello Worlddf", RegexOptions.None };
yield return new object[] { @"([^{}]|\n)+", "{{{{Hello\n World \n}END", RegexOptions.None };
yield return new object[] { @"([a-d]|[^abcd])+", "\tonce\n upon\0 a- ()*&^%#time?", RegexOptions.None };
yield return new object[] { @"([^a]|[a])*", "once upon a time", RegexOptions.None };
yield return new object[] { @"([a-d]|[^abcd]|[x-z]|^wxyz])+", "\tonce\n upon\0 a- ()*&^%#time?", RegexOptions.None };
yield return new object[] { @"([a-d]|[e-i]|[^e]|wxyz])+", "\tonce\n upon\0 a- ()*&^%#time?", RegexOptions.None };
yield return new object[] { @"^(([^b]+ )|(.* ))$", "aaa ", RegexOptions.None };
yield return new object[] { @"^(([^b]+ )|(.*))$", "aaa", RegexOptions.None };
yield return new object[] { @"^(([^b]+ )|(.* ))$", "bbb ", RegexOptions.None };
yield return new object[] { @"^(([^b]+ )|(.*))$", "bbb", RegexOptions.None };
yield return new object[] { @"^((a*)|(.*))$", "aaa", RegexOptions.None };
yield return new object[] { @"^((a*)|(.*))$", "aaabbb", RegexOptions.None };
yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))*", "{hello 1234567890 world}", RegexOptions.None };
yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))+", "{hello 1234567890 world}", RegexOptions.None };
yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))*", "{HELLO 1234567890 world}", RegexOptions.None };
yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))+", "{HELLO 1234567890 world}", RegexOptions.None };
yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))*", "{1234567890 hello world}", RegexOptions.None };
yield return new object[] { @"(([0-9])|([a-z])|([A-Z]))+", "{1234567890 hello world}", RegexOptions.None };
yield return new object[] { @"^(([a-d]*)|([a-z]*))$", "aaabbbcccdddeeefff", RegexOptions.None };
yield return new object[] { @"^(([d-f]*)|([c-e]*))$", "dddeeeccceee", RegexOptions.None };
yield return new object[] { @"^(([c-e]*)|([d-f]*))$", "dddeeeccceee", RegexOptions.None };
yield return new object[] { @"(([a-d]*)|([a-z]*))", "aaabbbcccdddeeefff", RegexOptions.None };
yield return new object[] { @"(([d-f]*)|([c-e]*))", "dddeeeccceee", RegexOptions.None };
yield return new object[] { @"(([c-e]*)|([d-f]*))", "dddeeeccceee", RegexOptions.None };
yield return new object[] { @"(([a-d]*)|(.*))", "aaabbbcccdddeeefff", RegexOptions.None };
yield return new object[] { @"(([d-f]*)|(.*))", "dddeeeccceee", RegexOptions.None };
yield return new object[] { @"(([c-e]*)|(.*))", "dddeeeccceee", RegexOptions.None };
yield return new object[] { @"\p{Pi}(\w*)\p{Pf}", "\u00ABCat\u00BB \u00BBDog\u00AB'", RegexOptions.None };
yield return new object[] { @"\p{Pi}(\w*)\p{Pf}", "\u2018Cat\u2019 \u2019Dog\u2018'", RegexOptions.None };
yield return new object[] { @"(?<cat>cat)\s+(?<dog>dog)\s+\123\s+\234", "asdfcat dog cat23 dog34eia", RegexOptions.ECMAScript };
yield return new object[] { @"<div>
(?>
<div>(?<DEPTH>) |
</div> (?<-DEPTH>) |
.?
)*?
(?(DEPTH)(?!))
</div>", "<div>this is some <div>red</div> text</div></div></div>", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { @"(
((?'open'<+)[^<>]*)+
((?'close-open'>+)[^<>]*)+
)+", "<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { @"(
(?<start><)?
[^<>]?
(?<end-start>>)?
)*", "<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { @"(
(?<start><[^/<>]*>)?
[^<>]?
(?<end-start></[^/<>]*>)?
)*", "<b><a>Cat</a></b>", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { @"(
(?<start><(?<TagName>[^/<>]*)>)?
[^<>]?
(?<end-start></\k<TagName>>)?
)*", "<b>cat</b><a>dog</a>", RegexOptions.IgnorePatternWhitespace };
yield return new object[] { @"([0-9]+?)([\w]+?)", "55488aheiaheiad", RegexOptions.ECMAScript };
yield return new object[] { @"([0-9]+?)([a-z]+?)", "55488aheiaheiad", RegexOptions.ECMAScript };
yield return new object[] { @"\G<%#(?<code>.*?)?%>", @"<%# DataBinder.Eval(this, ""MyNumber"") %>", RegexOptions.Singleline };
yield return new object[] { @"^[abcd]{0,0x10}*$", "a{0,0x10}}}", RegexOptions.None };
yield return new object[] { @"([a-z]*?)([\w])", "cat", RegexOptions.IgnoreCase };
yield return new object[] { @"^([a-z]*?)([\w])$", "cat", RegexOptions.IgnoreCase };
yield return new object[] { @"([a-z]*)([\w])", "cat", RegexOptions.IgnoreCase };
yield return new object[] { @"^([a-z]*)([\w])$", "cat", RegexOptions.IgnoreCase };
yield return new object[] { @"(cat){", "cat{", RegexOptions.None };
yield return new object[] { @"(cat){}", "cat{}", RegexOptions.None };
yield return new object[] { @"(cat){,", "cat{,", RegexOptions.None };
yield return new object[] { @"(cat){,}", "cat{,}", RegexOptions.None };
yield return new object[] { @"(cat){cat}", "cat{cat}", RegexOptions.None };
yield return new object[] { @"(cat){cat,5}", "cat{cat,5}", RegexOptions.None };
yield return new object[] { @"(cat){5,dog}", "cat{5,dog}", RegexOptions.None };
yield return new object[] { @"(cat){cat,dog}", "cat{cat,dog}", RegexOptions.None };
yield return new object[] { @"(cat){,}?", "cat{,}?", RegexOptions.None };
yield return new object[] { @"(cat){cat}?", "cat{cat}?", RegexOptions.None };
yield return new object[] { @"(cat){cat,5}?", "cat{cat,5}?", RegexOptions.None };
yield return new object[] { @"(cat){5,dog}?", "cat{5,dog}?", RegexOptions.None };
yield return new object[] { @"(cat){cat,dog}?", "cat{cat,dog}?", RegexOptions.None };
yield return new object[] { @"()", "cat", RegexOptions.None };
yield return new object[] { @"(?<cat>)", "cat", RegexOptions.None };
yield return new object[] { @"(?'cat')", "cat", RegexOptions.None };
yield return new object[] { @"(?:)", "cat", RegexOptions.None };
yield return new object[] { @"(?imn)", "cat", RegexOptions.None };
yield return new object[] { @"(?imn)cat", "(?imn)cat", RegexOptions.None };
yield return new object[] { @"(?=)", "cat", RegexOptions.None };
yield return new object[] { @"(?<=)", "cat", RegexOptions.None };
yield return new object[] { @"(?>)", "cat", RegexOptions.None };
yield return new object[] { @"(?()|)", "(?()|)", RegexOptions.None };
yield return new object[] { @"(?(cat)|)", "cat", RegexOptions.None };
yield return new object[] { @"(?(cat)|)", "dog", RegexOptions.None };
yield return new object[] { @"(?(cat)catdog|)", "catdog", RegexOptions.None };
yield return new object[] { @"(?(cat)catdog|)", "dog", RegexOptions.None };
yield return new object[] { @"(?(cat)dog|)", "dog", RegexOptions.None };
yield return new object[] { @"(?(cat)dog|)", "cat", RegexOptions.None };
yield return new object[] { @"(?(cat)|catdog)", "cat", RegexOptions.None };
yield return new object[] { @"(?(cat)|catdog)", "catdog", RegexOptions.None };
yield return new object[] { @"(?(cat)|dog)", "dog", RegexOptions.None };
yield return new object[] { "([\u0000-\uFFFF-[azAZ09]]|[\u0000-\uFFFF-[^azAZ09]])+", "azAZBCDE1234567890BCDEFAZza", RegexOptions.None };
yield return new object[] { "[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[a]]]]]]+", "abcxyzABCXYZ123890", RegexOptions.None };
yield return new object[] { "[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[a]]]]]]]+", "bcxyzABCXYZ123890a", RegexOptions.None };
yield return new object[] { "[\u0000-\uFFFF-[\\p{P}\\p{S}\\p{C}]]+", "!@`';.,$+<>=\x0001\x001FazAZ09", RegexOptions.None };
yield return new object[] { @"[\uFFFD-\uFFFF]+", "\uFFFC\uFFFD\uFFFE\uFFFF", RegexOptions.IgnoreCase };
yield return new object[] { @"[\uFFFC-\uFFFE]+", "\uFFFB\uFFFC\uFFFD\uFFFE\uFFFF", RegexOptions.IgnoreCase };
yield return new object[] { @"([a*]*)+?$", "ab", RegexOptions.None };
yield return new object[] { @"(a*)+?$", "b", RegexOptions.None };
}
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using Invio.Xunit;
using Xunit;
using static Invio.Immutable.ConstructorHelpers;
namespace Invio.Immutable {
[UnitTest]
public sealed class ConstructorTests {
[Fact]
public void GetImmutableSetterConstructor_NullPropertyMap() {
// Act
var exception = Record.Exception(
() => GetImmutableSetterConstructor<ValidTrivialExample>(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
private class ValidTrivialExample : ImmutableBase<ValidTrivialExample> {
public String Foo { get; }
public ValidTrivialExample(String foo) {
this.Foo = foo;
}
}
[Fact]
public void ThrowsOnMissingConstructor_TooFewParameters() {
// Arrange
var propertyMap = PropertyHelpers.GetPropertyMap<TooFewParameters>();
// Act
var exception = Record.Exception(
() => GetImmutableSetterConstructor<TooFewParameters>(propertyMap)
);
// Assert
Assert.IsType<NotSupportedException>(exception);
Assert.StartsWith(
"The TooFewParameters class lacks a constructor which is " +
"compatible with the following signature: TooFewParameters(",
exception.Message
);
Assert.Contains("String Foo", exception.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Guid Bar", exception.Message, StringComparison.OrdinalIgnoreCase);
}
private class TooFewParameters : ImmutableBase<TooFewParameters> {
public String Foo { get; }
public Guid Bar { get; }
public TooFewParameters(String foo) {
this.Foo = foo;
}
}
[Fact]
public void ThrowsOnMissingConstructor_TooManyParameters() {
// Arrange
var propertyMap = PropertyHelpers.GetPropertyMap<TooFewParameters>();
// Act
var exception = Record.Exception(
() => GetImmutableSetterConstructor<TooManyParameters>(propertyMap)
);
// Assert
Assert.IsType<NotSupportedException>(exception);
Assert.StartsWith(
"The TooManyParameters class lacks a constructor which is " +
"compatible with the following signature: TooManyParameters(",
exception.Message
);
Assert.Contains("String Foo", exception.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Guid Bar", exception.Message, StringComparison.OrdinalIgnoreCase);
}
private class TooManyParameters : ImmutableBase<TooManyParameters> {
public String Foo { get; }
public Guid Bar { get; }
public TooManyParameters(String foo, Guid bar, int bizz) {
this.Foo = foo;
this.Bar = bar;
}
}
[Fact]
public void ThrowsOnMissingConstructor_MismatchedParameterName() {
// Arrange
var propertyMap = PropertyHelpers.GetPropertyMap<MismatchedParameterName>();
// Act
var exception = Record.Exception(
() => GetImmutableSetterConstructor<MismatchedParameterName>(propertyMap)
);
// Assert
Assert.IsType<NotSupportedException>(exception);
Assert.StartsWith(
"The MismatchedParameterName class lacks a constructor which is " +
"compatible with the following signature: MismatchedParameterName(",
exception.Message
);
Assert.Contains("String Foo", exception.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Guid Bar", exception.Message, StringComparison.OrdinalIgnoreCase);
}
private class MismatchedParameterName : ImmutableBase<MismatchedParameterName> {
public String Foo { get; }
public Guid Bar { get; }
public MismatchedParameterName(String foo, Guid bizz) {
this.Foo = foo;
this.Bar = bizz;
}
}
[Fact]
public void ThrowsOnMissingConstructor_MismatchedParameterType() {
// Arrange
var propertyMap = PropertyHelpers.GetPropertyMap<MismatchedParameterType>();
// Act
var exception = Record.Exception(
() => GetImmutableSetterConstructor<MismatchedParameterType>(propertyMap)
);
// Assert
Assert.IsType<NotSupportedException>(exception);
Assert.StartsWith(
"The MismatchedParameterType class lacks a constructor which is " +
"compatible with the following signature: MismatchedParameterType(",
exception.Message
);
Assert.Contains("String Foo", exception.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("String Bar", exception.Message, StringComparison.OrdinalIgnoreCase);
}
private class MismatchedParameterType : ImmutableBase<MismatchedParameterType> {
public String Foo { get; }
public String Bar { get; }
public MismatchedParameterType(String foo, Guid bar) {
this.Foo = foo;
this.Bar = bar.ToString();
}
}
[Fact]
public void FindsMatching_WithManyConstructors() {
// Arrange
var propertyMap = PropertyHelpers.GetPropertyMap<WithManyConstructors>();
var expected = GetExpectedConstructor<WithManyConstructors>();
// Act
var actual = GetImmutableSetterConstructor<WithManyConstructors>(propertyMap);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
private class WithManyConstructors : ImmutableBase<WithManyConstructors> {
public String Foo { get; }
public Guid Bar { get; }
public WithManyConstructors(Tuple<String, Guid> tuple) :
this(tuple.Item1, tuple.Item2) {}
[Expected]
public WithManyConstructors(String foo, Guid bar) {
this.Foo = foo;
this.Bar = bar;
}
public WithManyConstructors SetFoo(String foo) {
return this.SetPropertyValueImpl(nameof(Foo), foo);
}
}
[Fact]
public void FindsMatching_WithPrivateConstructor() {
// Arrange
var propertyMap = PropertyHelpers.GetPropertyMap<WithPrivateConstructor>();
var expected = GetExpectedConstructor<WithPrivateConstructor>();
// Act
var actual = GetImmutableSetterConstructor<WithPrivateConstructor>(propertyMap);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
private class WithPrivateConstructor : ImmutableBase<WithPrivateConstructor> {
public static WithPrivateConstructor Empty { get; } =
new WithPrivateConstructor();
public String Foo { get; }
public Guid Bar { get; }
[Expected]
private WithPrivateConstructor(
String foo = default(String),
Guid bar = default(Guid)) {
this.Foo = foo;
this.Bar = bar;
}
public WithPrivateConstructor SetFoo(String foo) {
return this.SetPropertyValueImpl(nameof(Foo), foo);
}
}
[Fact]
public void FindsMatching_WithProtectedConstructor() {
// Arrange
var propertyMap = PropertyHelpers.GetPropertyMap<WithProtectedConstructor>();
var expected = GetExpectedConstructor<WithProtectedConstructor>();
// Act
var actual = GetImmutableSetterConstructor<WithProtectedConstructor>(propertyMap);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
private class WithProtectedConstructor : ImmutableBase<WithProtectedConstructor> {
public static WithProtectedConstructor Empty { get; } =
new WithProtectedConstructor();
public String Foo { get; }
public Guid Bar { get; }
[Expected]
private WithProtectedConstructor(
String foo = default(String),
Guid bar = default(Guid)) {
this.Foo = foo;
this.Bar = bar;
}
public WithProtectedConstructor SetFoo(String foo) {
return this.SetPropertyValueImpl(nameof(Foo), foo);
}
}
[Fact]
public void FindsMatching_IgnoresStaticMembers() {
// Arrange
var expected = GetExpectedConstructor<IgnoresStaticMembers>();
var propertyMap = PropertyHelpers.GetPropertyMap<IgnoresStaticMembers>();
// Act
var actual = GetImmutableSetterConstructor<IgnoresStaticMembers>(propertyMap);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
private class IgnoresStaticMembers : ImmutableBase<IgnoresStaticMembers> {
public static String StaticProperty { get; }
static IgnoresStaticMembers() {
StaticProperty = "SetViaStaticConstructor";
}
public String Foo { get; }
[Expected]
public IgnoresStaticMembers(String foo) {
this.Foo = foo;
}
public IgnoresStaticMembers SetFoo(String foo) {
return this.SetPropertyValueImpl(nameof(Foo), foo);
}
}
[Fact]
public void DecoratedConstructor_TooManyDecorated() {
// Arrange
var propertyMap = PropertyHelpers.GetPropertyMap<IgnoresStaticMembers>();
// Act
var exception = Record.Exception(
() => GetImmutableSetterConstructor<TooManyDecorated>(propertyMap)
);
// Assert
Assert.IsType<InvalidOperationException>(exception);
Assert.Equal(
"The TooManyDecorated class has 2 constructors decorated " +
"with the ImmutableSetterConstructorAttribute. Only one " +
"constructor is allowed to have this attribute at a time.",
exception.Message
);
}
private class TooManyDecorated : ImmutableBase<TooManyDecorated> {
public String Foo { get; }
public Guid Bar { get; }
[ImmutableSetterConstructor]
public TooManyDecorated(String foo, Guid bar) {
this.Foo = foo;
this.Bar = bar;
}
[ImmutableSetterConstructor]
public TooManyDecorated(Guid bar, String foo) {
this.Foo = foo;
this.Bar = bar;
}
}
[Fact]
public void DecoratedConstructor_DecoratedIncompatible() {
// Arrange
var propertyMap = PropertyHelpers.GetPropertyMap<DecoratedIncompatible>();
// Act
var exception = Record.Exception(
() => GetImmutableSetterConstructor<DecoratedIncompatible>(propertyMap)
);
// Assert
Assert.IsType<InvalidOperationException>(exception);
Assert.StartsWith(
"The DecoratedIncompatible class has a constructor decorated " +
"with ImmutableSetterConstructorAttribute that is incompatible " +
"with the following signature: DecoratedIncompatible(",
exception.Message
);
Assert.Contains("String Foo", exception.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Guid Bar", exception.Message, StringComparison.OrdinalIgnoreCase);
}
private class DecoratedIncompatible : ImmutableBase<DecoratedIncompatible> {
public String Foo { get; }
public Guid Bar { get; }
[ImmutableSetterConstructor]
public DecoratedIncompatible(String foo) {
this.Foo = foo;
}
public DecoratedIncompatible(String foo, Guid bar) {
this.Foo = foo;
this.Bar = bar;
}
}
[Fact]
public void DecoratedConstructor_ValidDecorated() {
// Arrange
var propertyMap = PropertyHelpers.GetPropertyMap<ValidDecorated>();
var expected = GetExpectedConstructor<ValidDecorated>();
// Act
var actual = GetImmutableSetterConstructor<ValidDecorated>(propertyMap);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
public class ValidDecorated : ImmutableBase<ValidDecorated> {
public String Foo { get; }
public Guid Bar { get; }
public Int32 Bizz { get; }
public ValidDecorated() {
this.Foo = null;
this.Bar = Guid.Empty;
this.Bizz = 0;
}
public ValidDecorated(String foo, Guid bar, Int32 bizz) {
this.Foo = foo;
this.Bar = bar;
this.Bizz = bizz;
}
public ValidDecorated(String foo, Int32 bizz, Guid bar) {
this.Foo = foo;
this.Bizz = bizz;
this.Bar = bar;
}
public ValidDecorated(Guid bar, String foo, Int32 bizz) {
this.Bar = bar;
this.Foo = foo;
this.Bizz = bizz;
}
[ImmutableSetterConstructor, Expected]
public ValidDecorated(Guid bar, Int32 bizz, String foo) {
this.Bizz = bizz;
this.Bar = bar;
this.Foo = foo;
}
public ValidDecorated(Int32 bizz, String foo, Guid bar) {
this.Bizz = bizz;
this.Foo = foo;
this.Bar = bar;
}
public ValidDecorated(Int32 bizz, Guid bar, String foo) {
this.Bizz = bizz;
this.Bar = bar;
this.Foo = foo;
}
public ValidDecorated SetFoo(String foo) {
return this.SetPropertyValueImpl(nameof(Foo), foo);
}
}
private static ConstructorInfo GetExpectedConstructor<TImmutable>() {
const BindingFlags flags =
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
return typeof(TImmutable).GetConstructors(flags).Single(IsExpectedConstructor);
}
private static bool IsExpectedConstructor(ConstructorInfo constructor) {
return constructor.GetCustomAttributes(typeof(ExpectedAttribute)).Any();
}
private class ExpectedAttribute : Attribute {}
}
}
| |
using System;
using System.Text;
using System.Xml;
using NUnit.Framework;
using Palaso.TestUtilities;
using Palaso.WritingSystems.Collation;
using Palaso.Xml;
namespace Palaso.Tests.WritingSystems.Collation
{
[TestFixture]
public class IcuRulesParserTests
{
private IcuRulesParser _icuParser;
private XmlWriter _writer;
private StringBuilder _xmlText;
[SetUp]
public void SetUp()
{
_icuParser = new IcuRulesParser();
_xmlText = new StringBuilder();
_writer = XmlWriter.Create(_xmlText, CanonicalXmlSettings.CreateXmlWriterSettings(ConformanceLevel.Fragment));
}
private string Environment_OutputString()
{
_writer.Close();
return _xmlText.ToString();
}
[Test]
public void EmptyString_ProducesNoRules()
{
_icuParser.WriteIcuRules(_writer, string.Empty);
string result = Environment_OutputString();
Assert.AreEqual("", result);
}
[Test]
public void WhiteSpace_ProducesNoRules()
{
_icuParser.WriteIcuRules(_writer, " \n\t");
string result = Environment_OutputString();
Assert.AreEqual("", result);
}
[Test]
public void Reset_ProducesResetNode()
{
_icuParser.WriteIcuRules(_writer, "&a");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
}
[Test]
public void PrimaryDifference_ProducesCorrectXml()
{
_icuParser.WriteIcuRules(_writer, "&a < b");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/p[text()='b']"
);
}
[Test]
public void SecondaryDifference_ProducesCorrectXml()
{
_icuParser.WriteIcuRules(_writer, "&a << b");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/s[text()='b']"
);
}
[Test]
public void TertiaryDifference_ProducesCorrectXml()
{
_icuParser.WriteIcuRules(_writer, "&a <<< b");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/t[text()='b']"
);
}
[Test]
public void NoDifference_ProducesCorrectXml()
{
_icuParser.WriteIcuRules(_writer, "&a = b");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/i[text()='b']"
);
}
[Test]
public void Prefix_ProducesCorrectXml()
{
_icuParser.WriteIcuRules(_writer, "&a < b|c");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/x/context[text()='b']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/x/p[text()='c']"
);
}
[Test]
public void Expansion_ProducesCorrectXml()
{
_icuParser.WriteIcuRules(_writer, "&a < b/ c");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/x/p[text()='b']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/x/extend[text()='c']"
);
}
[Test]
public void PrefixAndExpansion_ProducesCorrectXml()
{
_icuParser.WriteIcuRules(_writer, "&a < b|c/d");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/x/context[text()='b']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/x/p[text()='c']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/x/extend[text()='d']"
);
}
[Test]
public void Contraction_ProducesCorrectXml()
{
_icuParser.WriteIcuRules(_writer, "&ab < cd");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='ab']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/following-sibling::p[text()='cd']"
);
}
[Test]
public void EscapedUnicode_ProducesCorrectXml()
{
//Fieldworks issue LT-11999
_icuParser.WriteIcuRules(_writer, "&\\U00008000 < \\u0061");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='\\U00008000']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/following-sibling::p[text()='\\u0061']"
);
}
[Test]
public void MultiplePrimaryDifferences_ProducesOptimizedXml()
{
_icuParser.WriteIcuRules(_writer, "&a < b<c");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/pc[text()='bc']"
);
// Assert.AreEqual("<rules><reset>a</reset><pc>bc</pc></rules>", _xmlText.ToString());
}
[Test]
public void MultipleSecondaryDifferences_ProducesOptimizedXml()
{
_icuParser.WriteIcuRules(_writer, "&a << b<<c");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/sc[text()='bc']"
);
// Assert.AreEqual("<rules><reset>a</reset><sc>bc</sc></rules>", _xmlText.ToString());
}
[Test]
public void MultipleTertiaryDifferences_ProducesOptimizedXml()
{
_icuParser.WriteIcuRules(_writer, "&a <<< b<<<c");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/tc[text()='bc']"
);
// Assert.AreEqual("<rules><reset>a</reset><tc>bc</tc></rules>", _xmlText.ToString());
}
[Test]
public void MultipleNoDifferences_ProducesOptimizedXml()
{
_icuParser.WriteIcuRules(_writer, "&a = b=c");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/ic[text()='bc']"
);
// Assert.AreEqual("<rules><reset>a</reset><ic>bc</ic></rules>", _xmlText.ToString());
}
[Test]
public void FirstTertiaryIgnorable_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[first tertiary ignorable]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/first_tertiary_ignorable"
);
// Assert.AreEqual("<rules><reset><first_tertiary_ignorable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void LastTertiaryIgnorable_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[last tertiary ignorable]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/last_tertiary_ignorable"
);
// Assert.AreEqual("<rules><reset><last_tertiary_ignorable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void FirstSecondarygnorable_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[first secondary ignorable]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/first_secondary_ignorable"
);
// Assert.AreEqual("<rules><reset><first_secondary_ignorable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void LastSecondaryIgnorable_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[last secondary ignorable]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/last_secondary_ignorable"
);
// Assert.AreEqual("<rules><reset><last_secondary_ignorable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void FirstPrimaryIgnorable_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[first primary ignorable]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/first_primary_ignorable"
);
// Assert.AreEqual("<rules><reset><first_primary_ignorable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void LastPrimaryIgnorable_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[last primary ignorable]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/last_primary_ignorable"
);
// Assert.AreEqual("<rules><reset><last_primary_ignorable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void FirstVariable_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[first variable]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/first_variable"
);
// Assert.AreEqual("<rules><reset><first_variable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void LastVariable_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[last variable]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/last_variable"
);
// Assert.AreEqual("<rules><reset><last_variable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void FirstRegular_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[first regular]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/first_non_ignorable"
);
// Assert.AreEqual("<rules><reset><first_non_ignorable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void LastRegular_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[last regular]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/last_non_ignorable"
);
// Assert.AreEqual("<rules><reset><last_non_ignorable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void FirstTrailing_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[first trailing]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/first_trailing"
);
// Assert.AreEqual("<rules><reset><first_trailing /></reset></rules>", _xmlText.ToString());
}
[Test]
public void LastTrailing_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[last trailing]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/last_trailing"
);
// Assert.AreEqual("<rules><reset><last_trailing /></reset></rules>", _xmlText.ToString());
}
[Test]
public void FirstImplicit_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&a < [first implicit]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/p/first_implicit"
);
// Assert.AreEqual("<rules><reset>a</reset><p><first_implicit /></p></rules>", _xmlText.ToString());
}
[Test]
public void LastImplicit_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&a < [last implicit]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/p/last_implicit"
);
// Assert.AreEqual("<rules><reset>a</reset><p><last_implicit /></p></rules>", _xmlText.ToString());
}
[Test]
public void Top_ProducesCorrectIndirectNode()
{
_icuParser.WriteIcuRules(_writer, "&[top]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset/last_non_ignorable"
);
// Assert.AreEqual("<rules><reset><last_non_ignorable /></reset></rules>", _xmlText.ToString());
}
[Test]
public void Before1_ProducesCorrectResetNode()
{
_icuParser.WriteIcuRules(_writer, "&[before 1]a");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[@before='primary' and text()='a']"
);
// Assert.AreEqual("<rules><reset before=\"primary\">a</reset></rules>", _xmlText.ToString());
}
[Test]
public void Before2_ProducesCorrectResetNode()
{
_icuParser.WriteIcuRules(_writer, "&[before 2]a");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[@before='secondary' and text()='a']"
);
// Assert.AreEqual("<rules><reset before=\"secondary\">a</reset></rules>", _xmlText.ToString());
}
[Test]
public void Before3_ProducesCorrectResetNode()
{
_icuParser.WriteIcuRules(_writer, "&[before 3]a");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[@before='tertiary' and text()='a']"
);
// Assert.AreEqual("<rules><reset before=\"tertiary\">a</reset></rules>", _xmlText.ToString());
}
[Test]
public void TwoRules_ProducesCorrectXml()
{
_icuParser.WriteIcuRules(_writer, "&a<b \n&c<<d");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[1 and text()='a']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[1]/following-sibling::p[text()='b']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[2 and text()='c']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[2]/following-sibling::s[text()='d']"
);
// Assert.AreEqual("<rules><reset>a</reset><p>b</p><reset>c</reset><s>d</s></rules>", _xmlText.ToString());
}
[Test]
public void AlternateShiftedOption_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[alternate shifted]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath("/settings[@alternate='shifted']");
}
[Test]
public void AlternateNonIgnorableOption_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[alternate non-ignorable]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath("/settings[@alternate='non-ignorable']");
}
[Test]
public void Strength1Option_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[strength 1]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@strength='primary']"
);
// Assert.AreEqual("<settings strength=\"primary\" />", _xmlText.ToString());
}
[Test]
public void Strength2Option_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[strength 2]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@strength='secondary']"
);
// Assert.AreEqual("<settings strength=\"secondary\" />", _xmlText.ToString());
}
[Test]
public void Strength3Option_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[strength 3]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@strength='tertiary']"
);
// Assert.AreEqual("<settings strength=\"tertiary\" />", _xmlText.ToString());
}
[Test]
public void Strength4Option_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[strength 4]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@strength='quaternary']"
);
// Assert.AreEqual("<settings strength=\"quaternary\" />", _xmlText.ToString());
}
[Test]
public void Strength5Option_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[strength 5]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@strength='identical']"
);
// Assert.AreEqual("<settings strength=\"identical\" />", _xmlText.ToString());
}
[Test]
public void StrengthIOption_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[strength I]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@strength='identical']"
);
// Assert.AreEqual("<settings strength=\"identical\" />", _xmlText.ToString());
}
[Test]
public void Backwards1_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[backwards 1]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@backwards='off']"
);
// Assert.AreEqual("<settings backwards=\"off\" />", _xmlText.ToString());
}
[Test]
public void Backwards2_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[backwards 2]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@backwards='on']"
);
// Assert.AreEqual("<settings backwards=\"on\" />", _xmlText.ToString());
}
[Test]
public void NormalizationOn_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[normalization on]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@normalization='on']"
);
// Assert.AreEqual("<settings normalization=\"on\" />", _xmlText.ToString());
}
[Test]
public void NormalizationOff_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[normalization off]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@normalization='off']"
);
// Assert.AreEqual("<settings normalization=\"off\" />", _xmlText.ToString());
}
[Test]
public void CaseLevelOn_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[caseLevel on]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@caseLevel='on']"
);
// Assert.AreEqual("<settings caseLevel=\"on\" />", _xmlText.ToString());
}
[Test]
public void CaseLevelOff_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[caseLevel off]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@caseLevel='off']"
);
// Assert.AreEqual("<settings caseLevel=\"off\" />", _xmlText.ToString());
}
[Test]
public void CaseFirstOff_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[caseFirst off]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@caseFirst='off']"
);
// Assert.AreEqual("<settings caseFirst=\"off\" />", _xmlText.ToString());
}
[Test]
public void CaseFirstLower_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[caseFirst lower]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@caseFirst='lower']"
);
// Assert.AreEqual("<settings caseFirst=\"lower\" />", _xmlText.ToString());
}
[Test]
public void CaseFirstUpper_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[caseFirst upper]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@caseFirst='upper']"
);
// Assert.AreEqual("<settings caseFirst=\"upper\" />", _xmlText.ToString());
}
[Test]
public void HiraganaQOff_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[hiraganaQ off]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@hiraganaQuaternary='off']"
);
// Assert.AreEqual("<settings hiraganaQuaternary=\"off\" />", _xmlText.ToString());
}
[Test]
public void HiraganaQOn_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[hiraganaQ on]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@hiraganaQuaternary='on']"
);
// Assert.AreEqual("<settings hiraganaQuaternary=\"on\" />", _xmlText.ToString());
}
[Test]
public void NumericOff_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[numeric off]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@numeric='off']"
);
// Assert.AreEqual("<settings numeric=\"off\" />", _xmlText.ToString());
}
[Test]
public void NumericOn_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "[numeric on]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/settings[@numeric='on']"
);
// Assert.AreEqual("<settings numeric=\"on\" />", _xmlText.ToString());
}
[Test]
public void VariableTop_ProducesCorrectSettingsNode()
{
_icuParser.WriteIcuRules(_writer, "& A < [variable top]");
string result = "<root>" + Environment_OutputString() + "</root>";
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/root/settings[@variableTop='u41']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/root/rules/reset[text()='A']"
);
// Assert.AreEqual("<settings variableTop=\"u41\" /><rules><reset>A</reset></rules>", _xmlText.ToString());
}
[Test]
public void SuppressContractions_ProducesCorrectNode()
{
_icuParser.WriteIcuRules(_writer, "[suppress contractions [abc]]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/suppress_contractions[text()='[abc]']"
);
// Assert.AreEqual("<suppress_contractions>[abc]</suppress_contractions>", _xmlText.ToString());
}
[Test]
public void Optimize_ProducesCorrectNode()
{
_icuParser.WriteIcuRules(_writer, "[optimize [abc]]");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/optimize[text()='[abc]']"
);
// Assert.AreEqual("<optimize>[abc]</optimize>", _xmlText.ToString());
}
// Most of these escapes aren't actually handled by ICU - it just treats the character
// following backslash as a literal. These tests just check for no other special escape
// handling that is invalid.
[Test]
public void Escape_x_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\x41");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='x41']"
);
// Assert.AreEqual("<rules><reset>x41</reset></rules>", _xmlText.ToString());
}
[Test]
public void Escape_octal_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\102");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='102']"
);
// Assert.AreEqual("<rules><reset>102</reset></rules>", _xmlText.ToString());
}
[Test]
public void Escape_c_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\c\u0083");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='c\u0083']"
);
// Assert.AreEqual("<rules><reset>c\u0083</reset></rules>", _xmlText.ToString());
}
[Test]
public void Escape_a_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\a");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='a']"
);
// Assert.AreEqual("<rules><reset>a</reset></rules>", _xmlText.ToString());
}
[Test]
public void Escape_b_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\b");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='b']"
);
// Assert.AreEqual("<rules><reset>b</reset></rules>", _xmlText.ToString());
}
[Test]
public void Escape_t_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\t");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='t']"
);
// Assert.AreEqual("<rules><reset>t</reset></rules>", _xmlText.ToString());
}
[Test]
public void Escape_n_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\n");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='n']"
);
// Assert.AreEqual(String.Format("<rules><reset>n</reset></rules>", _writer.Settings.NewLineChars), _xmlText.ToString());
}
[Test]
public void Escape_v_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\v");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='v']"
);
// Assert.AreEqual("<rules><reset>v</reset></rules>", _xmlText.ToString());
}
[Test]
public void Escape_f_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\f");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='f']"
);
// Assert.AreEqual("<rules><reset>f</reset></rules>", _xmlText.ToString());
}
[Test]
public void Escape_r_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\r");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='r']"
);
// Assert.AreEqual("<rules><reset>r</reset></rules>", _xmlText.ToString());
}
[Test]
public void Escape_OtherChar_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&\\\\");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()='\\']"
);
// Assert.AreEqual("<rules><reset>\\</reset></rules>", _xmlText.ToString());
}
[Test]
public void TwoSingleQuotes_ProducesCorrectCharacter()
{
_icuParser.WriteIcuRules(_writer, "&''");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()=\"'\"]"
);
// Assert.AreEqual("<rules><reset>'</reset></rules>", _xmlText.ToString());
}
[Test]
public void QuotedString_ProducesCorrectString()
{
_icuParser.WriteIcuRules(_writer, "&'''\\<&'");
string result = Environment_OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/rules/reset[text()=\"'\\<&\"]"
);
// Assert.AreEqual("<rules><reset>'\\<&</reset></rules>", _xmlText.ToString());
}
[Test]
public void InvalidIcu_Throws()
{
Assert.Throws<ApplicationException>(
() => _icuParser.WriteIcuRules(_writer, "&a <<<< b"));
_writer.Close();
}
[Test]
public void InvalidIcu_NoXmlProduced()
{
try
{
_icuParser.WriteIcuRules(_writer, "&a <<<< b");
}
// ReSharper disable EmptyGeneralCatchClause
catch {}
// ReSharper restore EmptyGeneralCatchClause
string result = Environment_OutputString();
Assert.IsTrue(String.IsNullOrEmpty(result));
}
[Test]
public void ValidateIcuRules_ValidIcu_ReturnsTrue()
{
string message;
Assert.IsTrue(_icuParser.ValidateIcuRules("&a < b <<< c < e/g\n&[before 1]m<z", out message));
Assert.AreEqual(string.Empty, message);
}
[Test]
public void ValidateIcuRules_InvalidIcu_ReturnsFalse()
{
string message;
Assert.IsFalse(_icuParser.ValidateIcuRules("&a < b < c(", out message));
Assert.IsNotEmpty(message);
}
[Test]
public void BigCombinedRule_ParsesCorrectly()
{
// certainly some of this actually doesn't form semantically vaild ICU, but it should be syntactically correct
const string icu = "[strength 3] [alternate shifted]\n[backwards 2]&[before 1][ first regular]<b<\\u"
+ "<'cde'&gh<<p<K|Q/\\<<[last variable]<<4<[variable\ttop]\t<9";
_icuParser.WriteIcuRules(_writer, icu);
string result = Environment_OutputString();
string expected = CanonicalXml.ToCanonicalStringFragment(
"<settings alternate=\"shifted\" backwards=\"on\" variableTop=\"u34\" strength=\"tertiary\" />"
+ "<rules><reset before=\"primary\"><first_non_ignorable /></reset>"
+ "<pc>bu</pc><p>cde</p><reset>gh</reset><s>p</s>"
+ "<x><context>K</context><p>Q</p><extend><</extend></x>"
+ "<p><last_variable /></p><s>4</s><p>9</p></rules>"
);
Assert.AreEqual(expected, result);
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Framework;
using System.Diagnostics;
namespace Mosa.Platform.x86.Stages
{
/// <summary>
///
/// </summary>
public sealed class TweakTransformationStage : BaseTransformationStage
{
protected override void PopulateVisitationDictionary()
{
visitationDictionary[X86.Mov] = Mov;
visitationDictionary[X86.Cvttsd2si] = Cvttsd2si;
visitationDictionary[X86.Cvttss2si] = Cvttss2si;
visitationDictionary[X86.Cvtss2sd] = Cvtss2sd;
visitationDictionary[X86.Cvtsd2ss] = Cvtsd2ss;
visitationDictionary[X86.Movsx] = Movsx;
visitationDictionary[X86.Movzx] = Movzx;
visitationDictionary[X86.Cmp] = Cmp;
visitationDictionary[X86.Sar] = Sar;
visitationDictionary[X86.Shl] = Shl;
visitationDictionary[X86.Shr] = Shr;
visitationDictionary[X86.Call] = Call;
}
#region Visitation Methods
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Mov"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Mov(Context context)
{
Debug.Assert(!context.Result.IsConstant);
// Convert moves to float moves, if necessary
if (context.Result.IsR4)
{
context.SetInstruction(X86.Movss, InstructionSize.Size32, context.Result, context.Operand1);
}
else if (context.Result.IsR8)
{
context.SetInstruction(X86.Movsd, InstructionSize.Size64, context.Result, context.Operand1);
}
else if (context.Operand1.IsConstant && (context.Result.Type.IsUI1 || context.Result.Type.IsUI2 || context.Result.IsBoolean || context.Result.IsChar))
{
// Correct source size of constant based on destination size
context.Operand1 = Operand.CreateConstant(context.Result.Type, context.Operand1.ConstantUnsignedLongInteger);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Cvttsd2si"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Cvttsd2si(Context context)
{
Operand result = context.Result;
if (!result.IsRegister)
{
Operand register = AllocateVirtualRegister(result.Type);
context.Result = register;
context.AppendInstruction(X86.Mov, result, register);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Cvttss2si"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Cvttss2si(Context context)
{
Operand result = context.Result;
Operand register = AllocateVirtualRegister(result.Type);
if (!result.IsRegister)
{
context.Result = register;
context.AppendInstruction(X86.Mov, result, register);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Cvtss2sd" /> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Cvtss2sd(Context context)
{
Operand result = context.Result;
if (!result.IsRegister)
{
Operand register = AllocateVirtualRegister(result.Type);
context.Result = register;
context.AppendInstruction(X86.Movsd, InstructionSize.Size64, result, register);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Cvtsd2ss"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Cvtsd2ss(Context context)
{
Operand result = context.Result;
if (!result.IsRegister)
{
Operand register = AllocateVirtualRegister(result.Type);
context.Result = register;
context.AppendInstruction(X86.Movss, InstructionSize.Size32, result, register);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Movsx"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Movsx(Context context)
{
if (context.Operand1.IsInt || context.Operand1.IsPointer || !context.Operand1.IsValueType)
{
context.ReplaceInstructionOnly(X86.Mov);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Movzx"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Movzx(Context context)
{
if (context.Operand1.IsInt || context.Operand1.IsPointer || !context.Operand1.IsValueType)
{
context.ReplaceInstructionOnly(X86.Mov);
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Cmp"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Cmp(Context context)
{
Operand left = context.Operand1;
Operand right = context.Operand2;
if (left.IsConstant)
{
Operand v1 = AllocateVirtualRegister(left.Type);
Context before = context.InsertBefore();
before.AppendInstruction(X86.Mov, v1, left);
context.Operand1 = v1;
}
if (right.IsConstant && (left.IsChar || left.IsShort || left.IsByte))
{
Operand v2 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4);
InstructionSize size = left.IsByte ? InstructionSize.Size8 : InstructionSize.Size16;
if (left.IsSigned)
{
context.InsertBefore().AppendInstruction(X86.Movsx, size, v2, left);
}
else
{
context.InsertBefore().AppendInstruction(X86.Movzx, size, v2, left);
}
context.Operand1 = v2;
}
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Sar"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Sar(Context context)
{
ConvertShiftConstantToByte(context);
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Shl"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Shl(Context context)
{
ConvertShiftConstantToByte(context);
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Shr"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Shr(Context context)
{
ConvertShiftConstantToByte(context);
}
/// <summary>
/// Visitation function for <see cref="IX86Visitor.Call"/> instructions.
/// </summary>
/// <param name="context">The context.</param>
public void Call(Context context)
{
// FIXME: Result operand should be used instead of Operand1 for the result
// FIXME: Move to FixedRegisterAssignmentStage
Operand destinationOperand = context.Operand1;
if (destinationOperand == null || destinationOperand.IsSymbol)
return;
if (!destinationOperand.IsRegister)
{
Context before = context.InsertBefore();
Operand eax = AllocateVirtualRegister(destinationOperand.Type);
before.SetInstruction(X86.Mov, eax, destinationOperand);
context.Operand1 = eax;
}
}
#endregion Visitation Methods
/// <summary>
/// Adjusts the shift constant.
/// </summary>
/// <param name="context">The context.</param>
private void ConvertShiftConstantToByte(Context context)
{
if (!context.Operand2.IsConstant)
return;
if (context.Operand2.IsByte)
return;
context.Operand2 = Operand.CreateConstant(TypeSystem.BuiltIn.U1, context.Operand2.ConstantUnsignedLongInteger);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace CodeJewelApi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// AccountIdentityVerificationWorkflow
/// </summary>
[DataContract]
public partial class AccountIdentityVerificationWorkflow : IEquatable<AccountIdentityVerificationWorkflow>, IValidatableObject
{
public AccountIdentityVerificationWorkflow()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="AccountIdentityVerificationWorkflow" /> class.
/// </summary>
/// <param name="DefaultDescription">DefaultDescription.</param>
/// <param name="DefaultName">DefaultName.</param>
/// <param name="InputOptions">InputOptions.</param>
/// <param name="SignatureProvider">SignatureProvider.</param>
/// <param name="Steps">Steps.</param>
/// <param name="WorkflowId">WorkflowId.</param>
/// <param name="WorkflowResourceKey">WorkflowResourceKey.</param>
public AccountIdentityVerificationWorkflow(string DefaultDescription = default(string), string DefaultName = default(string), List<AccountIdentityInputOption> InputOptions = default(List<AccountIdentityInputOption>), AccountSignatureProvider SignatureProvider = default(AccountSignatureProvider), List<AccountIdentityVerificationStep> Steps = default(List<AccountIdentityVerificationStep>), string WorkflowId = default(string), string WorkflowResourceKey = default(string))
{
this.DefaultDescription = DefaultDescription;
this.DefaultName = DefaultName;
this.InputOptions = InputOptions;
this.SignatureProvider = SignatureProvider;
this.Steps = Steps;
this.WorkflowId = WorkflowId;
this.WorkflowResourceKey = WorkflowResourceKey;
}
/// <summary>
/// Gets or Sets DefaultDescription
/// </summary>
[DataMember(Name="defaultDescription", EmitDefaultValue=false)]
public string DefaultDescription { get; set; }
/// <summary>
/// Gets or Sets DefaultName
/// </summary>
[DataMember(Name="defaultName", EmitDefaultValue=false)]
public string DefaultName { get; set; }
/// <summary>
/// Gets or Sets InputOptions
/// </summary>
[DataMember(Name="inputOptions", EmitDefaultValue=false)]
public List<AccountIdentityInputOption> InputOptions { get; set; }
/// <summary>
/// Gets or Sets SignatureProvider
/// </summary>
[DataMember(Name="signatureProvider", EmitDefaultValue=false)]
public AccountSignatureProvider SignatureProvider { get; set; }
/// <summary>
/// Gets or Sets Steps
/// </summary>
[DataMember(Name="steps", EmitDefaultValue=false)]
public List<AccountIdentityVerificationStep> Steps { get; set; }
/// <summary>
/// Gets or Sets WorkflowId
/// </summary>
[DataMember(Name="workflowId", EmitDefaultValue=false)]
public string WorkflowId { get; set; }
/// <summary>
/// Gets or Sets WorkflowResourceKey
/// </summary>
[DataMember(Name="workflowResourceKey", EmitDefaultValue=false)]
public string WorkflowResourceKey { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AccountIdentityVerificationWorkflow {\n");
sb.Append(" DefaultDescription: ").Append(DefaultDescription).Append("\n");
sb.Append(" DefaultName: ").Append(DefaultName).Append("\n");
sb.Append(" InputOptions: ").Append(InputOptions).Append("\n");
sb.Append(" SignatureProvider: ").Append(SignatureProvider).Append("\n");
sb.Append(" Steps: ").Append(Steps).Append("\n");
sb.Append(" WorkflowId: ").Append(WorkflowId).Append("\n");
sb.Append(" WorkflowResourceKey: ").Append(WorkflowResourceKey).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as AccountIdentityVerificationWorkflow);
}
/// <summary>
/// Returns true if AccountIdentityVerificationWorkflow instances are equal
/// </summary>
/// <param name="other">Instance of AccountIdentityVerificationWorkflow to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AccountIdentityVerificationWorkflow other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.DefaultDescription == other.DefaultDescription ||
this.DefaultDescription != null &&
this.DefaultDescription.Equals(other.DefaultDescription)
) &&
(
this.DefaultName == other.DefaultName ||
this.DefaultName != null &&
this.DefaultName.Equals(other.DefaultName)
) &&
(
this.InputOptions == other.InputOptions ||
this.InputOptions != null &&
this.InputOptions.SequenceEqual(other.InputOptions)
) &&
(
this.SignatureProvider == other.SignatureProvider ||
this.SignatureProvider != null &&
this.SignatureProvider.Equals(other.SignatureProvider)
) &&
(
this.Steps == other.Steps ||
this.Steps != null &&
this.Steps.SequenceEqual(other.Steps)
) &&
(
this.WorkflowId == other.WorkflowId ||
this.WorkflowId != null &&
this.WorkflowId.Equals(other.WorkflowId)
) &&
(
this.WorkflowResourceKey == other.WorkflowResourceKey ||
this.WorkflowResourceKey != null &&
this.WorkflowResourceKey.Equals(other.WorkflowResourceKey)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.DefaultDescription != null)
hash = hash * 59 + this.DefaultDescription.GetHashCode();
if (this.DefaultName != null)
hash = hash * 59 + this.DefaultName.GetHashCode();
if (this.InputOptions != null)
hash = hash * 59 + this.InputOptions.GetHashCode();
if (this.SignatureProvider != null)
hash = hash * 59 + this.SignatureProvider.GetHashCode();
if (this.Steps != null)
hash = hash * 59 + this.Steps.GetHashCode();
if (this.WorkflowId != null)
hash = hash * 59 + this.WorkflowId.GetHashCode();
if (this.WorkflowResourceKey != null)
hash = hash * 59 + this.WorkflowResourceKey.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections;
using System.Data.Odbc;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace BaamStudios.SharpAngie
{
static internal class ReflectionsHelper
{
private static readonly Regex NumberRegex = new Regex(@"^\d+$");
/// <summary>
/// Gets the object and property from the view model that are described by the path.
/// </summary>
/// <param name="rootObject"></param>
/// <param name="propertyPath">
/// Supported value patterns: <br/>
/// - myprop <br/>
/// - myobj.myprop <br/>
/// - myobj.myarrayprop[123] <br/>
/// - myobj.myarrayprop.123 <br/>
/// - myobj.myarrayprop[123].prop1 <br/>
/// - myobj.myarrayprop.123.prop1 <br/>
/// </param>
public static void GetDeepProperty(object rootObject, string propertyPath, out object targetPropertyOwner, out PropertyInfo targetProperty, out object targetPropertyIndex)
{
targetPropertyOwner = null;
targetProperty = null;
targetPropertyIndex = null;
object currentObject = rootObject;
// the javascript side may separate the index of array properties with property.1234 instead of property[1234] for simplicity of the javascript code.
// replacing the [] with . is not really necessary when calling only from javascript but it makes this method more compatible with calls from c#.
var propertyNames = propertyPath.Replace('[', '.').Replace(']', '.').Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (propertyNames.Length == 0)
return;
for (int i = 0; i < propertyNames.Length; i++)
{
if (i < propertyNames.Length - 1)
{
var propertyName = propertyNames[i];
var currentProperty = GetProperty(currentObject, propertyName);
if (currentProperty == null)
return;
var value = currentProperty.GetValue(currentObject);
if (value == null)
return;
if (value is IEnumerable)
{
var possiblePropertyIndex = propertyNames[i + 1];
if (value is IDictionary)
{
var key = ((IDictionary) value).Keys.Cast<object>()
.FirstOrDefault(x => x.ToString() == possiblePropertyIndex);
if (i + 1 == propertyNames.Length - 1)
{
targetPropertyOwner = currentObject;
targetProperty = currentProperty;
targetPropertyIndex = key;
return;
}
currentObject = ((IDictionary)value)[key];
i++;
continue;
}
if (NumberRegex.IsMatch(possiblePropertyIndex))
{
var key = Int32.Parse(possiblePropertyIndex);
if (i + 1 == propertyNames.Length - 1)
{
targetPropertyOwner = currentObject;
targetProperty = currentProperty;
targetPropertyIndex = key;
return;
}
currentObject = ((IEnumerable)value).Cast<object>().ElementAt(key);
i++;
continue;
}
return;
}
else
{
currentObject = value;
}
}
else
{
targetPropertyOwner = currentObject;
targetProperty = GetProperty(targetPropertyOwner, propertyNames.Last());
targetPropertyIndex = null;
}
}
}
public static PropertyInfo GetProperty(object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName);
}
public static void SetDeepProperty(object rootObject, string propertyPath, object value, Action beforeSet = null, Action afterSet = null)
{
object targetPropertyOwner;
PropertyInfo targetProperty;
object targetPropertyIndex;
GetDeepProperty(rootObject, propertyPath, out targetPropertyOwner, out targetProperty,
out targetPropertyIndex);
if (targetProperty == null) return;
var oldValue = GetPropertyValue(targetPropertyOwner, targetProperty, targetPropertyIndex);
if (!Equals(oldValue, value))
{
if (beforeSet != null) beforeSet();
try
{
SetPropertyValue(targetPropertyOwner, targetProperty, targetPropertyIndex, value);
}
finally
{
if (afterSet != null) afterSet();
}
}
}
private static object GetPropertyValue(object propertyOwner, PropertyInfo property, object propertyIndex)
{
var value = property.GetValue(propertyOwner);
if (propertyIndex == null)
return value;
var dictionary = value as IDictionary;
if (dictionary != null)
{
return dictionary[propertyIndex];
}
if (propertyIndex is int)
{
var enumerable = value as IEnumerable;
if (enumerable == null)
return null;
return enumerable.Cast<object>().ElementAt((int) propertyIndex);
}
return null;
}
private static void SetPropertyValue(object propertyOwner, PropertyInfo property, object propertyIndex, object value)
{
if (propertyIndex == null)
{
property.SetValue(propertyOwner, Convert.ChangeType(value, property.PropertyType));
return;
}
var enumerable = property.GetValue(propertyOwner);
var dictionary = enumerable as IDictionary;
if (dictionary != null)
{
dictionary[propertyIndex] = Convert.ChangeType(value, dictionary.GetType().GenericTypeArguments[1]);
}
if (propertyIndex is int)
{
var list = enumerable as IList;
if (list == null)
return;
list[(int) propertyIndex] = Convert.ChangeType(value, list.GetType().GenericTypeArguments[0]);
}
}
private static void GetDeepMethod(object rootObject, string methodPath, out object methodOwner, out string methodName)
{
methodOwner = null;
methodName = null;
var lastDot = methodPath.LastIndexOf('.');
if (lastDot >= 0)
{
var propertyPath = methodPath.Substring(0, lastDot);
object targetPropertyOwner;
PropertyInfo targetProperty;
object targetPropertyIndex;
GetDeepProperty(rootObject, propertyPath, out targetPropertyOwner, out targetProperty,
out targetPropertyIndex);
if (targetProperty == null) return;
methodOwner = GetPropertyValue(targetPropertyOwner, targetProperty, targetPropertyIndex);
methodName = methodPath.Substring(lastDot + 1);
}
else
{
methodOwner = rootObject;
methodName = methodPath;
}
}
private static MethodInfo GetMethod(object methodOwner, string methodName, object[] args)
{
return methodOwner.GetType().GetMethods()
.FirstOrDefault(x => x.Name == methodName && x.GetParameters().Length == args.Length);
}
public static void InvokeDeepMethod(object rootObject, string methodPath, object[] args)
{
object methodOwner;
string methodName;
GetDeepMethod(rootObject, methodPath, out methodOwner, out methodName);
if (methodOwner == null)
return;
var method = GetMethod(methodOwner, methodName, args);
if (method == null)
return;
InvokeMethod(methodOwner, method, args);
}
private static void InvokeMethod(object methodOwner, MethodInfo method, object[] args)
{
var parameterInfos = method.GetParameters();
var parameters = new object[parameterInfos.Length];
for (var i = 0; i < parameters.Length; i++)
{
var arg = args[i];
var parameterType = parameterInfos[i].ParameterType;
if (parameterType == typeof (string))
parameters[i] = arg != null ? arg.ToString() : null;
else if (parameterType == typeof (Guid))
parameters[i] = arg != null ? Guid.Parse(arg.ToString()) : Guid.Empty;
else
parameters[i] = Convert.ChangeType(arg, parameterType);
}
method.Invoke(methodOwner, parameters);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace JsonDiffPatchDotNet.UnitTests
{
[TestFixture]
public class DiffUnitTests
{
[Test]
public void Diff_EmptyObjects_EmptyPatch()
{
var jdp = new JsonDiffPatch();
var empty = JObject.Parse(@"{}");
JToken result = jdp.Diff(empty, empty);
Assert.IsNull(result);
}
[Test]
public void Diff_EqualBooleanProperty_NoDiff()
{
var jdp = new JsonDiffPatch();
var left = JObject.Parse(@"{""p"": true }");
var right = JObject.Parse(@"{""p"": true }");
JToken result = jdp.Diff(left, right);
Assert.IsNull(result);
}
[Test]
public void Diff_DiffBooleanProperty_ValidPatch()
{
var jdp = new JsonDiffPatch();
var left = JObject.Parse(@"{""p"": true }");
var right = JObject.Parse(@"{""p"": false }");
JToken result = jdp.Diff(left, right);
Assert.AreEqual(JTokenType.Object, result.Type);
JObject obj = (JObject)result;
Assert.IsNotNull(obj.Property("p"), "Property Name");
Assert.AreEqual(JTokenType.Array, obj.Property("p").Value.Type, "Array Value");
Assert.AreEqual(2, ((JArray)obj.Property("p").Value).Count, "Array Length");
Assert.IsTrue(((JArray)obj.Property("p").Value)[0].ToObject<bool>(), "Array Old Value");
Assert.IsFalse(((JArray)obj.Property("p").Value)[1].ToObject<bool>(), "Array New Value");
}
[Test]
public void Diff_BooleanPropertyDeleted_ValidPatch()
{
var jdp = new JsonDiffPatch();
var left = JObject.Parse(@"{ ""p"": true }");
var right = JObject.Parse(@"{ }");
JToken result = jdp.Diff(left, right);
Assert.AreEqual(JTokenType.Object, result.Type);
JObject obj = (JObject)result;
Assert.IsNotNull(obj.Property("p"), "Property Name");
Assert.AreEqual(JTokenType.Array, obj.Property("p").Value.Type, "Array Value");
Assert.AreEqual(3, ((JArray)obj.Property("p").Value).Count, "Array Length");
Assert.IsTrue(((JArray)obj.Property("p").Value)[0].ToObject<bool>(), "Array Old Value");
Assert.AreEqual(0, ((JArray)obj.Property("p").Value)[1].ToObject<int>(), "Array New Value");
Assert.AreEqual(0, ((JArray)obj.Property("p").Value)[2].ToObject<int>(), "Array Deleted Indicator");
}
[Test]
public void Diff_BooleanPropertyAdded_ValidPatch()
{
var jdp = new JsonDiffPatch();
var left = JObject.Parse(@"{ }");
var right = JObject.Parse(@"{ ""p"": true }");
JToken result = jdp.Diff(left, right);
Assert.AreEqual(JTokenType.Object, result.Type);
JObject obj = (JObject)result;
Assert.IsNotNull(obj.Property("p"), "Property Name");
Assert.AreEqual(JTokenType.Array, obj.Property("p").Value.Type, "Array Value");
Assert.AreEqual(1, ((JArray)obj.Property("p").Value).Count, "Array Length");
Assert.IsTrue(((JArray)obj.Property("p").Value)[0].ToObject<bool>(), "Array Added Value");
}
[Test]
public void Diff_EfficientStringDiff_ValidPatch()
{
var jdp = new JsonDiffPatch(new Options { TextDiff = TextDiffMode.Efficient });
var left = JObject.Parse(@"{ ""p"": ""lp.Value.ToString().Length > _options.MinEfficientTextDiffLength"" }");
var right = JObject.Parse(@"{ ""p"": ""blah1"" }");
JToken result = jdp.Diff(left, right);
Assert.AreEqual(JTokenType.Object, result.Type);
JObject obj = (JObject)result;
Assert.IsNotNull(obj.Property("p"), "Property Name");
Assert.AreEqual(JTokenType.Array, obj.Property("p").Value.Type, "Array Value");
Assert.AreEqual(3, ((JArray)obj.Property("p").Value).Count, "Array Length");
Assert.AreEqual("@@ -1,64 +1,5 @@\n-lp.Value.ToString().Length %3e _options.MinEfficientTextDiffLength\n+blah1\n", ((JArray)obj.Property("p").Value)[0].ToString(), "Array Added Value");
Assert.AreEqual(0, ((JArray)obj.Property("p").Value)[1].ToObject<int>(), "Array Added Value");
Assert.AreEqual(2, ((JArray)obj.Property("p").Value)[2].ToObject<int>(), "Array String Diff Indicator");
}
[Test]
public void Diff_EfficientStringDiff_NoChanges()
{
var jdp = new JsonDiffPatch(new Options { TextDiff = TextDiffMode.Efficient });
var left = JObject.Parse(@"{ ""p"": ""lp.Value.ToString().Length > _options.MinEfficientTextDiffLength"" }");
var right = JObject.Parse(@"{ ""p"": ""lp.Value.ToString().Length > _options.MinEfficientTextDiffLength"" }");
JToken result = jdp.Diff(left, right);
Assert.IsNull(result, "No Changes");
}
[Test]
public void Diff_LeftNull_Exception()
{
var jdp = new JsonDiffPatch();
var obj = JObject.Parse(@"{ }");
JToken result = jdp.Diff(null, obj);
Assert.AreEqual(JTokenType.Array, result.Type);
}
[Test]
public void Diff_RightNull_Exception()
{
var jdp = new JsonDiffPatch();
var obj = JObject.Parse(@"{ }");
JToken result = jdp.Diff(obj, null);
Assert.AreEqual(JTokenType.Array, result.Type);
}
[Test]
public void Diff_EfficientArrayDiffSame_NullDiff()
{
var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
var array = JToken.Parse(@"[1,2,3]");
JToken diff = jdp.Diff(array, array);
Assert.IsNull(diff);
}
[Test]
public void Diff_EfficientArrayDiffDifferentHeadRemoved_ValidDiff()
{
var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
var left = JToken.Parse(@"[1,2,3,4]");
var right = JToken.Parse(@"[2,3,4]");
JObject diff = jdp.Diff(left, right) as JObject;
Assert.IsNotNull(diff);
Assert.AreEqual(2, diff.Properties().Count());
Assert.IsNotNull(diff["_0"]);
}
[Test]
public void Diff_EfficientArrayDiffDifferentTailRemoved_ValidDiff()
{
var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
var left = JToken.Parse(@"[1,2,3,4]");
var right = JToken.Parse(@"[1,2,3]");
JObject diff = jdp.Diff(left, right) as JObject;
Assert.IsNotNull(diff);
Assert.AreEqual(2, diff.Properties().Count());
Assert.IsNotNull(diff["_3"]);
}
[Test]
public void Diff_EfficientArrayDiffDifferentHeadAdded_ValidDiff()
{
var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
var left = JToken.Parse(@"[1,2,3,4]");
var right = JToken.Parse(@"[0,1,2,3,4]");
JObject diff = jdp.Diff(left, right) as JObject;
Assert.IsNotNull(diff);
Assert.AreEqual(2, diff.Properties().Count());
Assert.IsNotNull(diff["0"]);
}
[Test]
public void Diff_EfficientArrayDiffDifferentTailAdded_ValidDiff()
{
var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
var left = JToken.Parse(@"[1,2,3,4]");
var right = JToken.Parse(@"[1,2,3,4,5]");
JObject diff = jdp.Diff(left, right) as JObject;
Assert.IsNotNull(diff);
Assert.AreEqual(2, diff.Properties().Count());
Assert.IsNotNull(diff["4"]);
}
[Test]
public void Diff_EfficientArrayDiffDifferentHeadTailAdded_ValidDiff()
{
var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
var left = JToken.Parse(@"[1,2,3,4]");
var right = JToken.Parse(@"[0,1,2,3,4,5]");
JObject diff = jdp.Diff(left, right) as JObject;
Assert.IsNotNull(diff);
Assert.AreEqual(3, diff.Properties().Count());
Assert.IsNotNull(diff["0"]);
Assert.IsNotNull(diff["5"]);
}
[Test]
public void Diff_EfficientArrayDiffSameLengthNested_ValidDiff()
{
var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
var left = JToken.Parse(@"[1,2,{""p"":false},4]");
var right = JToken.Parse(@"[1,2,{""p"":true},4]");
JObject diff = jdp.Diff(left, right) as JObject;
Assert.IsNotNull(diff);
Assert.AreEqual(2, diff.Properties().Count());
Assert.IsNotNull(diff["2"]);
}
[Test]
public void Diff_EfficientArrayDiffSameWithObject_NoDiff()
{
var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
var left = JToken.Parse(@"
{
""@context"": [
""http://www.w3.org/ns/csvw"",
{
""@language"": ""en"",
""@base"": ""http://example.org""
}
]
}");
var right = left.DeepClone();
JToken diff = jdp.Diff(left, right);
Assert.IsNull(diff);
}
[Test]
public void Diff_EfficientArrayDiffHugeArrays_NoStackOverflow()
{
const int arraySize = 1000;
Func<int, int, JToken> hugeArrayFunc = (startIndex, count) =>
{
var builder = new StringBuilder("[");
foreach (var i in Enumerable.Range(startIndex, count))
{
builder.Append($"{i},");
}
builder.Append("]");
return JToken.Parse(builder.ToString());
};
var jdp = new JsonDiffPatch();
var left = hugeArrayFunc(0, arraySize);
var right = hugeArrayFunc(arraySize / 2, arraySize);
JToken diff = jdp.Diff(left, right);
var restored = jdp.Patch(left, diff);
Assert.That(JToken.DeepEquals(restored, right));
}
[Test]
public void Diff_IntStringDiff_ValidPatch()
{
var jdp = new JsonDiffPatch();
var left = JToken.Parse(@"1");
var right = JToken.Parse(@"""hello""");
JToken result = jdp.Diff(left, right);
Assert.AreEqual(JTokenType.Array, result.Type);
JArray array = (JArray)result;
Assert.AreEqual(2, array.Count);
Assert.AreEqual(left, array[0]);
Assert.AreEqual(right, array[1]);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Cryptography {
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum CryptoStreamMode {
Read = 0,
Write = 1,
}
[System.Runtime.InteropServices.ComVisible(true)]
public class CryptoStream : Stream, IDisposable {
// Member veriables
private Stream _stream;
private ICryptoTransform _Transform;
private byte[] _InputBuffer; // read from _stream before _Transform
private int _InputBufferIndex = 0;
private int _InputBlockSize;
private byte[] _OutputBuffer; // buffered output of _Transform
private int _OutputBufferIndex = 0;
private int _OutputBlockSize;
private CryptoStreamMode _transformMode;
private bool _canRead = false;
private bool _canWrite = false;
private bool _finalBlockTransformed = false;
// Constructors
public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) {
_stream = stream;
_transformMode = mode;
_Transform = transform;
switch (_transformMode) {
case CryptoStreamMode.Read:
if (!(_stream.CanRead)) throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"),"stream");
_canRead = true;
break;
case CryptoStreamMode.Write:
if (!(_stream.CanWrite)) throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"),"stream");
_canWrite = true;
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
}
InitializeBuffer();
}
public override bool CanRead {
[Pure]
get { return _canRead; }
}
// For now, assume we can never seek into the middle of a cryptostream
// and get the state right. This is too strict.
public override bool CanSeek {
[Pure]
get { return false; }
}
public override bool CanWrite {
[Pure]
get { return _canWrite; }
}
public override long Length {
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); }
}
public override long Position {
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); }
set { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); }
}
public bool HasFlushedFinalBlock
{
get { return _finalBlockTransformed; }
}
// The flush final block functionality used to be part of close, but that meant you couldn't do something like this:
// MemoryStream ms = new MemoryStream();
// CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
// cs.Write(foo, 0, foo.Length);
// cs.Close();
// and get the encrypted data out of ms, because the cs.Close also closed ms and the data went away.
// so now do this:
// cs.Write(foo, 0, foo.Length);
// cs.FlushFinalBlock() // which can only be called once
// byte[] ciphertext = ms.ToArray();
// cs.Close();
public void FlushFinalBlock() {
if (_finalBlockTransformed)
throw new NotSupportedException(Environment.GetResourceString("Cryptography_CryptoStream_FlushFinalBlockTwice"));
// We have to process the last block here. First, we have the final block in _InputBuffer, so transform it
byte[] finalBytes = _Transform.TransformFinalBlock(_InputBuffer, 0, _InputBufferIndex);
_finalBlockTransformed = true;
// Now, write out anything sitting in the _OutputBuffer...
if (_canWrite && _OutputBufferIndex > 0) {
_stream.Write(_OutputBuffer, 0, _OutputBufferIndex);
_OutputBufferIndex = 0;
}
// Write out finalBytes
if (_canWrite)
_stream.Write(finalBytes, 0, finalBytes.Length);
// If the inner stream is a CryptoStream, then we want to call FlushFinalBlock on it too, otherwise just Flush.
CryptoStream innerCryptoStream = _stream as CryptoStream;
if (innerCryptoStream != null) {
if (!innerCryptoStream.HasFlushedFinalBlock) {
innerCryptoStream.FlushFinalBlock();
}
} else {
_stream.Flush();
}
// zeroize plain text material before returning
if (_InputBuffer != null)
Array.Clear(_InputBuffer, 0, _InputBuffer.Length);
if (_OutputBuffer != null)
Array.Clear(_OutputBuffer, 0, _OutputBuffer.Length);
return;
}
public override void Flush() {
return;
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() which a subclass might have overriden. To be safe
// we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Flush) when we are not sure.
if (this.GetType() != typeof(CryptoStream))
return base.FlushAsync(cancellationToken);
return cancellationToken.IsCancellationRequested ?
Task.FromCancellation(cancellationToken) :
Task.CompletedTask;
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream"));
}
public override void SetLength(long value) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream"));
}
public override int Read([In, Out] byte[] buffer, int offset, int count) {
// argument checking
if (!CanRead)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// read <= count bytes from the input stream, transforming as we go.
// Basic idea: first we deliver any bytes we already have in the
// _OutputBuffer, because we know they're good. Then, if asked to deliver
// more bytes, we read & transform a block at a time until either there are
// no bytes ready or we've delivered enough.
int bytesToDeliver = count;
int currentOutputIndex = offset;
if (_OutputBufferIndex != 0) {
// we have some already-transformed bytes in the output buffer
if (_OutputBufferIndex <= count) {
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, offset, _OutputBufferIndex);
bytesToDeliver -= _OutputBufferIndex;
currentOutputIndex += _OutputBufferIndex;
_OutputBufferIndex = 0;
} else {
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, offset, count);
Buffer.InternalBlockCopy(_OutputBuffer, count, _OutputBuffer, 0, _OutputBufferIndex - count);
_OutputBufferIndex -= count;
return(count);
}
}
// _finalBlockTransformed == true implies we're at the end of the input stream
// if we got through the previous if block then _OutputBufferIndex = 0, meaning
// we have no more transformed bytes to give
// so return count-bytesToDeliver, the amount we were able to hand back
// eventually, we'll just always return 0 here because there's no more to read
if (_finalBlockTransformed) {
return(count - bytesToDeliver);
}
// ok, now loop until we've delivered enough or there's nothing available
int amountRead = 0;
int numOutputBytes;
// OK, see first if it's a multi-block transform and we can speed up things
if (bytesToDeliver > _OutputBlockSize)
{
if (_Transform.CanTransformMultipleBlocks) {
int BlocksToProcess = bytesToDeliver / _OutputBlockSize;
int numWholeBlocksInBytes = BlocksToProcess * _InputBlockSize;
byte[] tempInputBuffer = new byte[numWholeBlocksInBytes];
// get first the block already read
Buffer.InternalBlockCopy(_InputBuffer, 0, tempInputBuffer, 0, _InputBufferIndex);
amountRead = _InputBufferIndex;
amountRead += _stream.Read(tempInputBuffer, _InputBufferIndex, numWholeBlocksInBytes - _InputBufferIndex);
_InputBufferIndex = 0;
if (amountRead <= _InputBlockSize) {
_InputBuffer = tempInputBuffer;
_InputBufferIndex = amountRead;
goto slow;
}
// Make amountRead an integral multiple of _InputBlockSize
int numWholeReadBlocksInBytes = (amountRead / _InputBlockSize) * _InputBlockSize;
int numIgnoredBytes = amountRead - numWholeReadBlocksInBytes;
if (numIgnoredBytes != 0) {
_InputBufferIndex = numIgnoredBytes;
Buffer.InternalBlockCopy(tempInputBuffer, numWholeReadBlocksInBytes, _InputBuffer, 0, numIgnoredBytes);
}
byte[] tempOutputBuffer = new byte[(numWholeReadBlocksInBytes / _InputBlockSize) * _OutputBlockSize];
numOutputBytes = _Transform.TransformBlock(tempInputBuffer, 0, numWholeReadBlocksInBytes, tempOutputBuffer, 0);
Buffer.InternalBlockCopy(tempOutputBuffer, 0, buffer, currentOutputIndex, numOutputBytes);
// Now, tempInputBuffer and tempOutputBuffer are no more needed, so zeroize them to protect plain text
Array.Clear(tempInputBuffer, 0, tempInputBuffer.Length);
Array.Clear(tempOutputBuffer, 0, tempOutputBuffer.Length);
bytesToDeliver -= numOutputBytes;
currentOutputIndex += numOutputBytes;
}
}
slow:
// try to fill _InputBuffer so we have something to transform
while (bytesToDeliver > 0) {
while (_InputBufferIndex < _InputBlockSize) {
amountRead = _stream.Read(_InputBuffer, _InputBufferIndex, _InputBlockSize - _InputBufferIndex);
// first, check to see if we're at the end of the input stream
if (amountRead == 0) goto ProcessFinalBlock;
_InputBufferIndex += amountRead;
}
numOutputBytes = _Transform.TransformBlock(_InputBuffer, 0, _InputBlockSize, _OutputBuffer, 0);
_InputBufferIndex = 0;
if (bytesToDeliver >= numOutputBytes) {
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, numOutputBytes);
currentOutputIndex += numOutputBytes;
bytesToDeliver -= numOutputBytes;
} else {
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver);
_OutputBufferIndex = numOutputBytes - bytesToDeliver;
Buffer.InternalBlockCopy(_OutputBuffer, bytesToDeliver, _OutputBuffer, 0, _OutputBufferIndex);
return count;
}
}
return count;
ProcessFinalBlock:
// if so, then call TransformFinalBlock to get whatever is left
byte[] finalBytes = _Transform.TransformFinalBlock(_InputBuffer, 0, _InputBufferIndex);
// now, since _OutputBufferIndex must be 0 if we're in the while loop at this point,
// reset it to be what we just got back
_OutputBuffer = finalBytes;
_OutputBufferIndex = finalBytes.Length;
// set the fact that we've transformed the final block
_finalBlockTransformed = true;
// now, return either everything we just got or just what's asked for, whichever is smaller
if (bytesToDeliver < _OutputBufferIndex) {
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver);
_OutputBufferIndex -= bytesToDeliver;
Buffer.InternalBlockCopy(_OutputBuffer, bytesToDeliver, _OutputBuffer, 0, _OutputBufferIndex);
return(count);
} else {
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, _OutputBufferIndex);
bytesToDeliver -= _OutputBufferIndex;
_OutputBufferIndex = 0;
return(count - bytesToDeliver);
}
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// argument checking
if (!CanRead)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() or BeginRead() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read/BeginRead) when we are not sure.
if (this.GetType() != typeof(CryptoStream))
return base.ReadAsync(buffer, offset, count, cancellationToken);
// Fast path check for cancellation already requested
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation<int>(cancellationToken);
return ReadAsyncInternal(buffer, offset, count, cancellationToken);
}
// simple awaitable that allows for hopping to the thread pool
private struct HopToThreadPoolAwaitable : INotifyCompletion
{
public HopToThreadPoolAwaitable GetAwaiter() { return this; }
public bool IsCompleted { get { return false; } }
public void OnCompleted(Action continuation) { Task.Run(continuation); }
public void GetResult() {}
}
private async Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// Same conditions validated with exceptions in ReadAsync
Contract.Requires(CanRead);
Contract.Requires(offset >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer.Length - offset >= count);
await default(HopToThreadPoolAwaitable); // computationally-intensive operation follows, so force execution to run asynchronously
var sem = base.EnsureAsyncActiveSemaphoreInitialized();
await sem.WaitAsync().ConfigureAwait(false);
try
{
// The following logic is identical to that in Read, except calling async
// methods instead of synchronous on the underlying stream.
// read <= count bytes from the input stream, transforming as we go.
// Basic idea: first we deliver any bytes we already have in the
// _OutputBuffer, because we know they're good. Then, if asked to deliver
// more bytes, we read & transform a block at a time until either there are
// no bytes ready or we've delivered enough.
int bytesToDeliver = count;
int currentOutputIndex = offset;
if (_OutputBufferIndex != 0)
{
// we have some already-transformed bytes in the output buffer
if (_OutputBufferIndex <= count)
{
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, offset, _OutputBufferIndex);
bytesToDeliver -= _OutputBufferIndex;
currentOutputIndex += _OutputBufferIndex;
_OutputBufferIndex = 0;
}
else
{
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, offset, count);
Buffer.InternalBlockCopy(_OutputBuffer, count, _OutputBuffer, 0, _OutputBufferIndex - count);
_OutputBufferIndex -= count;
return (count);
}
}
// _finalBlockTransformed == true implies we're at the end of the input stream
// if we got through the previous if block then _OutputBufferIndex = 0, meaning
// we have no more transformed bytes to give
// so return count-bytesToDeliver, the amount we were able to hand back
// eventually, we'll just always return 0 here because there's no more to read
if (_finalBlockTransformed)
{
return (count - bytesToDeliver);
}
// ok, now loop until we've delivered enough or there's nothing available
int amountRead = 0;
int numOutputBytes;
// OK, see first if it's a multi-block transform and we can speed up things
if (bytesToDeliver > _OutputBlockSize)
{
if (_Transform.CanTransformMultipleBlocks)
{
int BlocksToProcess = bytesToDeliver / _OutputBlockSize;
int numWholeBlocksInBytes = BlocksToProcess * _InputBlockSize;
byte[] tempInputBuffer = new byte[numWholeBlocksInBytes];
// get first the block already read
Buffer.InternalBlockCopy(_InputBuffer, 0, tempInputBuffer, 0, _InputBufferIndex);
amountRead = _InputBufferIndex;
amountRead += await _stream.ReadAsync(tempInputBuffer, _InputBufferIndex, numWholeBlocksInBytes - _InputBufferIndex, cancellationToken).ConfigureAwait(false);
_InputBufferIndex = 0;
if (amountRead <= _InputBlockSize)
{
_InputBuffer = tempInputBuffer;
_InputBufferIndex = amountRead;
goto slow;
}
// Make amountRead an integral multiple of _InputBlockSize
int numWholeReadBlocksInBytes = (amountRead / _InputBlockSize) * _InputBlockSize;
int numIgnoredBytes = amountRead - numWholeReadBlocksInBytes;
if (numIgnoredBytes != 0)
{
_InputBufferIndex = numIgnoredBytes;
Buffer.InternalBlockCopy(tempInputBuffer, numWholeReadBlocksInBytes, _InputBuffer, 0, numIgnoredBytes);
}
byte[] tempOutputBuffer = new byte[(numWholeReadBlocksInBytes / _InputBlockSize) * _OutputBlockSize];
numOutputBytes = _Transform.TransformBlock(tempInputBuffer, 0, numWholeReadBlocksInBytes, tempOutputBuffer, 0);
Buffer.InternalBlockCopy(tempOutputBuffer, 0, buffer, currentOutputIndex, numOutputBytes);
// Now, tempInputBuffer and tempOutputBuffer are no more needed, so zeroize them to protect plain text
Array.Clear(tempInputBuffer, 0, tempInputBuffer.Length);
Array.Clear(tempOutputBuffer, 0, tempOutputBuffer.Length);
bytesToDeliver -= numOutputBytes;
currentOutputIndex += numOutputBytes;
}
}
slow:
// try to fill _InputBuffer so we have something to transform
while (bytesToDeliver > 0)
{
while (_InputBufferIndex < _InputBlockSize)
{
amountRead = await _stream.ReadAsync(_InputBuffer, _InputBufferIndex, _InputBlockSize - _InputBufferIndex, cancellationToken).ConfigureAwait(false);
// first, check to see if we're at the end of the input stream
if (amountRead == 0) goto ProcessFinalBlock;
_InputBufferIndex += amountRead;
}
numOutputBytes = _Transform.TransformBlock(_InputBuffer, 0, _InputBlockSize, _OutputBuffer, 0);
_InputBufferIndex = 0;
if (bytesToDeliver >= numOutputBytes)
{
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, numOutputBytes);
currentOutputIndex += numOutputBytes;
bytesToDeliver -= numOutputBytes;
}
else
{
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver);
_OutputBufferIndex = numOutputBytes - bytesToDeliver;
Buffer.InternalBlockCopy(_OutputBuffer, bytesToDeliver, _OutputBuffer, 0, _OutputBufferIndex);
return count;
}
}
return count;
ProcessFinalBlock:
// if so, then call TransformFinalBlock to get whatever is left
byte[] finalBytes = _Transform.TransformFinalBlock(_InputBuffer, 0, _InputBufferIndex);
// now, since _OutputBufferIndex must be 0 if we're in the while loop at this point,
// reset it to be what we just got back
_OutputBuffer = finalBytes;
_OutputBufferIndex = finalBytes.Length;
// set the fact that we've transformed the final block
_finalBlockTransformed = true;
// now, return either everything we just got or just what's asked for, whichever is smaller
if (bytesToDeliver < _OutputBufferIndex)
{
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver);
_OutputBufferIndex -= bytesToDeliver;
Buffer.InternalBlockCopy(_OutputBuffer, bytesToDeliver, _OutputBuffer, 0, _OutputBufferIndex);
return (count);
}
else
{
Buffer.InternalBlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, _OutputBufferIndex);
bytesToDeliver -= _OutputBufferIndex;
_OutputBufferIndex = 0;
return (count - bytesToDeliver);
}
}
finally { sem.Release(); }
}
public override void Write(byte[] buffer, int offset, int count) {
if (!CanWrite)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// write <= count bytes to the output stream, transforming as we go.
// Basic idea: using bytes in the _InputBuffer first, make whole blocks,
// transform them, and write them out. Cache any remaining bytes in the _InputBuffer.
int bytesToWrite = count;
int currentInputIndex = offset;
// if we have some bytes in the _InputBuffer, we have to deal with those first,
// so let's try to make an entire block out of it
if (_InputBufferIndex > 0) {
if (count >= _InputBlockSize - _InputBufferIndex) {
// we have enough to transform at least a block, so fill the input block
Buffer.InternalBlockCopy(buffer, offset, _InputBuffer, _InputBufferIndex, _InputBlockSize - _InputBufferIndex);
currentInputIndex += (_InputBlockSize - _InputBufferIndex);
bytesToWrite -= (_InputBlockSize - _InputBufferIndex);
_InputBufferIndex = _InputBlockSize;
// Transform the block and write it out
} else {
// not enough to transform a block, so just copy the bytes into the _InputBuffer
// and return
Buffer.InternalBlockCopy(buffer, offset, _InputBuffer, _InputBufferIndex, count);
_InputBufferIndex += count;
return;
}
}
// If the OutputBuffer has anything in it, write it out
if (_OutputBufferIndex > 0) {
_stream.Write(_OutputBuffer, 0, _OutputBufferIndex);
_OutputBufferIndex = 0;
}
// At this point, either the _InputBuffer is full, empty, or we've already returned.
// If full, let's process it -- we now know the _OutputBuffer is empty
int numOutputBytes;
if (_InputBufferIndex == _InputBlockSize) {
numOutputBytes = _Transform.TransformBlock(_InputBuffer, 0, _InputBlockSize, _OutputBuffer, 0);
// write out the bytes we just got
_stream.Write(_OutputBuffer, 0, numOutputBytes);
// reset the _InputBuffer
_InputBufferIndex = 0;
}
while (bytesToWrite > 0) {
if (bytesToWrite >= _InputBlockSize) {
// We have at least an entire block's worth to transform
// If the transform will handle multiple blocks at once, do that
if (_Transform.CanTransformMultipleBlocks) {
int numWholeBlocks = bytesToWrite / _InputBlockSize;
int numWholeBlocksInBytes = numWholeBlocks * _InputBlockSize;
byte[] _tempOutputBuffer = new byte[numWholeBlocks * _OutputBlockSize];
numOutputBytes = _Transform.TransformBlock(buffer, currentInputIndex, numWholeBlocksInBytes, _tempOutputBuffer, 0);
_stream.Write(_tempOutputBuffer, 0, numOutputBytes);
currentInputIndex += numWholeBlocksInBytes;
bytesToWrite -= numWholeBlocksInBytes;
} else {
// do it the slow way
numOutputBytes = _Transform.TransformBlock(buffer, currentInputIndex, _InputBlockSize, _OutputBuffer, 0);
_stream.Write(_OutputBuffer, 0, numOutputBytes);
currentInputIndex += _InputBlockSize;
bytesToWrite -= _InputBlockSize;
}
} else {
// In this case, we don't have an entire block's worth left, so store it up in the
// input buffer, which by now must be empty.
Buffer.InternalBlockCopy(buffer, currentInputIndex, _InputBuffer, 0, bytesToWrite);
_InputBufferIndex += bytesToWrite;
return;
}
}
return;
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (!CanWrite)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() or BeginWrite() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write/BeginWrite) when we are not sure.
if (this.GetType() != typeof(CryptoStream))
return base.WriteAsync(buffer, offset, count, cancellationToken);
// Fast path check for cancellation already requested
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation(cancellationToken);
return WriteAsyncInternal(buffer, offset, count, cancellationToken);
}
private async Task WriteAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// Same conditions validated with exceptions in ReadAsync
Contract.Requires(CanWrite);
Contract.Requires(offset >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer.Length - offset >= count);
await default(HopToThreadPoolAwaitable); // computationally-intensive operation follows, so force execution to run asynchronously
var sem = base.EnsureAsyncActiveSemaphoreInitialized();
await sem.WaitAsync().ConfigureAwait(false);
try
{
// The following logic is identical to that in Write, except calling async
// methods instead of synchronous on the underlying stream.
// write <= count bytes to the output stream, transforming as we go.
// Basic idea: using bytes in the _InputBuffer first, make whole blocks,
// transform them, and write them out. Cache any remaining bytes in the _InputBuffer.
int bytesToWrite = count;
int currentInputIndex = offset;
// if we have some bytes in the _InputBuffer, we have to deal with those first,
// so let's try to make an entire block out of it
if (_InputBufferIndex > 0)
{
if (count >= _InputBlockSize - _InputBufferIndex)
{
// we have enough to transform at least a block, so fill the input block
Buffer.InternalBlockCopy(buffer, offset, _InputBuffer, _InputBufferIndex, _InputBlockSize - _InputBufferIndex);
currentInputIndex += (_InputBlockSize - _InputBufferIndex);
bytesToWrite -= (_InputBlockSize - _InputBufferIndex);
_InputBufferIndex = _InputBlockSize;
// Transform the block and write it out
}
else
{
// not enough to transform a block, so just copy the bytes into the _InputBuffer
// and return
Buffer.InternalBlockCopy(buffer, offset, _InputBuffer, _InputBufferIndex, count);
_InputBufferIndex += count;
return;
}
}
// If the OutputBuffer has anything in it, write it out
if (_OutputBufferIndex > 0)
{
await _stream.WriteAsync(_OutputBuffer, 0, _OutputBufferIndex, cancellationToken).ConfigureAwait(false);
_OutputBufferIndex = 0;
}
// At this point, either the _InputBuffer is full, empty, or we've already returned.
// If full, let's process it -- we now know the _OutputBuffer is empty
int numOutputBytes;
if (_InputBufferIndex == _InputBlockSize)
{
numOutputBytes = _Transform.TransformBlock(_InputBuffer, 0, _InputBlockSize, _OutputBuffer, 0);
// write out the bytes we just got
await _stream.WriteAsync(_OutputBuffer, 0, numOutputBytes, cancellationToken).ConfigureAwait(false);
// reset the _InputBuffer
_InputBufferIndex = 0;
}
while (bytesToWrite > 0)
{
if (bytesToWrite >= _InputBlockSize)
{
// We have at least an entire block's worth to transform
// If the transform will handle multiple blocks at once, do that
if (_Transform.CanTransformMultipleBlocks)
{
int numWholeBlocks = bytesToWrite / _InputBlockSize;
int numWholeBlocksInBytes = numWholeBlocks * _InputBlockSize;
byte[] _tempOutputBuffer = new byte[numWholeBlocks * _OutputBlockSize];
numOutputBytes = _Transform.TransformBlock(buffer, currentInputIndex, numWholeBlocksInBytes, _tempOutputBuffer, 0);
await _stream.WriteAsync(_tempOutputBuffer, 0, numOutputBytes, cancellationToken).ConfigureAwait(false);
currentInputIndex += numWholeBlocksInBytes;
bytesToWrite -= numWholeBlocksInBytes;
}
else
{
// do it the slow way
numOutputBytes = _Transform.TransformBlock(buffer, currentInputIndex, _InputBlockSize, _OutputBuffer, 0);
await _stream.WriteAsync(_OutputBuffer, 0, numOutputBytes, cancellationToken).ConfigureAwait(false);
currentInputIndex += _InputBlockSize;
bytesToWrite -= _InputBlockSize;
}
}
else
{
// In this case, we don't have an entire block's worth left, so store it up in the
// input buffer, which by now must be empty.
Buffer.InternalBlockCopy(buffer, currentInputIndex, _InputBuffer, 0, bytesToWrite);
_InputBufferIndex += bytesToWrite;
return;
}
}
return;
}
finally { sem.Release(); }
}
public void Clear() {
Close();
}
protected override void Dispose(bool disposing) {
try {
if (disposing) {
if (!_finalBlockTransformed) {
FlushFinalBlock();
}
_stream.Close();
}
}
finally {
try {
// Ensure we don't try to transform the final block again if we get disposed twice
// since it's null after this
_finalBlockTransformed = true;
// we need to clear all the internal buffers
if (_InputBuffer != null)
Array.Clear(_InputBuffer, 0, _InputBuffer.Length);
if (_OutputBuffer != null)
Array.Clear(_OutputBuffer, 0, _OutputBuffer.Length);
_InputBuffer = null;
_OutputBuffer = null;
_canRead = false;
_canWrite = false;
}
finally {
base.Dispose(disposing);
}
}
}
// Private methods
private void InitializeBuffer() {
if (_Transform != null) {
_InputBlockSize = _Transform.InputBlockSize;
_InputBuffer = new byte[_InputBlockSize];
_OutputBlockSize = _Transform.OutputBlockSize;
_OutputBuffer = new byte[_OutputBlockSize];
}
}
}
}
| |
#region Foreign-License
/*
Implements the built-in "interp" Tcl command.
Copyright (c) 2000 Christian Krone.
Copyright (c) 2012 Sky Morey
See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#endregion
using System;
using System.Collections;
namespace Tcl.Lang
{
/// <summary> This class implements the slave interpreter commands, which are created
/// in response to the built-in "interp create" command in Tcl.
///
/// It is also used by the "interp" command to record and find information
/// about slave interpreters. Maps from a command name in the master to
/// information about a slave interpreter, e.g. what aliases are defined
/// in it.
/// </summary>
class InterpSlaveCmd : ICommandWithDispose, IAssocData
{
private static readonly string[] options = new string[] { "alias", "aliases", "eval", "expose", "hide", "hidden", "issafe", "invokehidden", "marktrusted" };
private const int OPT_ALIAS = 0;
private const int OPT_ALIASES = 1;
private const int OPT_EVAL = 2;
private const int OPT_EXPOSE = 3;
private const int OPT_HIDE = 4;
private const int OPT_HIDDEN = 5;
private const int OPT_ISSAFE = 6;
private const int OPT_INVOKEHIDDEN = 7;
private const int OPT_MARKTRUSTED = 8;
private static readonly string[] hiddenOptions = new string[] { "-global", "--" };
private const int OPT_HIDDEN_GLOBAL = 0;
private const int OPT_HIDDEN_LAST = 1;
// Master interpreter for this slave.
internal Interp masterInterp;
// Hash entry in masters slave table for this slave interpreter.
// Used to find this record, and used when deleting the slave interpreter
// to delete it from the master's table.
internal string path;
// The slave interpreter.
internal Interp slaveInterp;
// Interpreter object command.
internal WrappedCommand interpCmd;
public TCL.CompletionCode CmdProc( Interp interp, TclObject[] objv )
{
if ( objv.Length < 2 )
{
throw new TclNumArgsException( interp, 1, objv, "cmd ?arg ...?" );
}
int cmd = TclIndex.Get( interp, objv[1], options, "option", 0 );
switch ( cmd )
{
case OPT_ALIAS:
if ( objv.Length == 3 )
{
InterpAliasCmd.describe( interp, slaveInterp, objv[2] );
return TCL.CompletionCode.RETURN;
}
if ( "".Equals( objv[3].ToString() ) )
{
if ( objv.Length == 4 )
{
InterpAliasCmd.delete( interp, slaveInterp, objv[2] );
return TCL.CompletionCode.RETURN;
}
}
else
{
InterpAliasCmd.create( interp, slaveInterp, interp, objv[2], objv[3], 4, objv );
return TCL.CompletionCode.RETURN;
}
throw new TclNumArgsException( interp, 2, objv, "aliasName ?targetName? ?args..?" );
case OPT_ALIASES:
InterpAliasCmd.list( interp, slaveInterp );
break;
case OPT_EVAL:
if ( objv.Length < 3 )
{
throw new TclNumArgsException( interp, 2, objv, "arg ?arg ...?" );
}
eval( interp, slaveInterp, 2, objv );
break;
case OPT_EXPOSE:
if ( objv.Length < 3 || objv.Length > 4 )
{
throw new TclNumArgsException( interp, 2, objv, "hiddenCmdName ?cmdName?" );
}
expose( interp, slaveInterp, 2, objv );
break;
case OPT_HIDE:
if ( objv.Length < 3 || objv.Length > 4 )
{
throw new TclNumArgsException( interp, 2, objv, "cmdName ?hiddenCmdName?" );
}
hide( interp, slaveInterp, 2, objv );
break;
case OPT_HIDDEN:
if ( objv.Length != 2 )
{
throw new TclNumArgsException( interp, 2, objv, null );
}
InterpSlaveCmd.hidden( interp, slaveInterp );
break;
case OPT_ISSAFE:
interp.SetResult( slaveInterp._isSafe );
break;
case OPT_INVOKEHIDDEN:
bool global = false;
int i;
for ( i = 2; i < objv.Length; i++ )
{
if ( objv[i].ToString()[0] != '-' )
{
break;
}
int index = TclIndex.Get( interp, objv[i], hiddenOptions, "option", 0 );
if ( index == OPT_HIDDEN_GLOBAL )
{
global = true;
}
else
{
i++;
break;
}
}
if ( objv.Length - i < 1 )
{
throw new TclNumArgsException( interp, 2, objv, "?-global? ?--? cmd ?arg ..?" );
}
InterpSlaveCmd.invokeHidden( interp, slaveInterp, global, i, objv );
break;
case OPT_MARKTRUSTED:
if ( objv.Length != 2 )
{
throw new TclNumArgsException( interp, 2, objv, null );
}
markTrusted( interp, slaveInterp );
break;
}
return TCL.CompletionCode.RETURN;
}
/// <summary>----------------------------------------------------------------------
///
/// disposeCmd --
///
/// Invoked when an object command for a slave interpreter is deleted;
/// cleans up all state associated with the slave interpreter and destroys
/// the slave interpreter.
///
/// Results:
/// None.
///
/// Side effects:
/// Cleans up all state associated with the slave interpreter and
/// destroys the slave interpreter.
///
/// ----------------------------------------------------------------------
/// </summary>
public void Dispose()
{
// Unlink the slave from its master interpreter.
SupportClass.HashtableRemove( masterInterp._slaveTable, path );
// Set to null so that when the InterpInfo is cleaned up in the slave
// it does not try to delete the command causing all sorts of grief.
// See SlaveRecordDeleteProc().
interpCmd = null;
if ( slaveInterp != null )
{
slaveInterp.Dispose();
}
}
public void Dispose( Interp interp )
// Current interpreter.
{
// There shouldn't be any commands left.
if ( !( interp._slaveTable.Count == 0 ) )
{
System.Console.Error.WriteLine( "InterpInfoDeleteProc: still exist commands" );
}
interp._slaveTable = null;
// Tell any interps that have aliases to this interp that they should
// delete those aliases. If the other interp was already dead, it
// would have removed the target record already.
// TODO ATK
foreach ( WrappedCommand slaveCmd in new ArrayList( interp._targetTable.Keys ) )
{
Interp slaveInterp = (Interp)interp._targetTable[slaveCmd];
slaveInterp.DeleteCommandFromToken( slaveCmd );
}
interp._targetTable = null;
if ( interp._interpChanTable != null )
{
foreach ( Channel channel in new ArrayList( interp._interpChanTable.Values ) )
{
TclIO.unregisterChannel( interp, channel );
}
}
if ( interp._slave.interpCmd != null )
{
// Tcl_DeleteInterp() was called on this interpreter, rather
// "interp delete" or the equivalent deletion of the command in the
// master. First ensure that the cleanup callback doesn't try to
// delete the interp again.
interp._slave.slaveInterp = null;
interp._slave.masterInterp.DeleteCommandFromToken( interp._slave.interpCmd );
}
// There shouldn't be any aliases left.
if ( !( interp._aliasTable.Count == 0 ) )
{
System.Console.Error.WriteLine( "InterpInfoDeleteProc: still exist aliases" );
}
interp._aliasTable = null;
}
internal static Interp create( Interp interp, TclObject path, bool safe )
{
Interp masterInterp;
string pathString;
TclObject[] objv = TclList.getElements( interp, path );
if ( objv.Length < 2 )
{
masterInterp = interp;
pathString = path.ToString();
}
else
{
TclObject obj = TclList.NewInstance();
TclList.insert( interp, obj, 0, objv, 0, objv.Length - 2 );
masterInterp = InterpCmd.getInterp( interp, obj );
pathString = objv[objv.Length - 1].ToString();
}
if ( !safe )
{
safe = masterInterp._isSafe;
}
if ( masterInterp._slaveTable.ContainsKey( pathString ) )
{
throw new TclException( interp, "interpreter named \"" + pathString + "\" already exists, cannot create" );
}
Interp slaveInterp = new Interp();
InterpSlaveCmd slave = new InterpSlaveCmd();
slaveInterp._slave = slave;
slaveInterp.SetAssocData( "InterpSlaveCmd", slave );
slave.masterInterp = masterInterp;
slave.path = pathString;
slave.slaveInterp = slaveInterp;
masterInterp.CreateCommand( pathString, slaveInterp._slave );
slaveInterp._slave.interpCmd = NamespaceCmd.findCommand( masterInterp, pathString, null, 0 );
SupportClass.PutElement( masterInterp._slaveTable, pathString, slaveInterp._slave );
slaveInterp.SetVar( "tcl_interactive", "0", TCL.VarFlag.GLOBAL_ONLY );
// Inherit the recursion limit.
slaveInterp._maxNestingDepth = masterInterp._maxNestingDepth;
if ( safe )
{
try
{
makeSafe( slaveInterp );
}
catch ( TclException e )
{
SupportClass.WriteStackTrace( e, Console.Error );
}
}
else
{
//Tcl_Init(slaveInterp);
}
return slaveInterp;
}
internal static void eval( Interp interp, Interp slaveInterp, int objIx, TclObject[] objv )
{
TCL.CompletionCode result;
slaveInterp.preserve();
slaveInterp.allowExceptions();
try
{
if ( objIx + 1 == objv.Length )
{
slaveInterp.Eval( objv[objIx], 0 );
}
else
{
TclObject obj = TclList.NewInstance();
for ( int ix = objIx; ix < objv.Length; ix++ )
{
TclList.Append( interp, obj, objv[ix] );
}
obj.Preserve();
slaveInterp.Eval( obj, 0 );
obj.Release();
}
result = slaveInterp._returnCode;
}
catch ( TclException e )
{
result = e.GetCompletionCode();
}
slaveInterp.release();
interp.transferResult( slaveInterp, result );
}
internal static void expose( Interp interp, Interp slaveInterp, int objIx, TclObject[] objv )
{
if ( interp._isSafe )
{
throw new TclException( interp, "permission denied: " + "safe interpreter cannot expose commands" );
}
int nameIdx = objv.Length - objIx == 1 ? objIx : objIx + 1;
try
{
slaveInterp.exposeCommand( objv[objIx].ToString(), objv[nameIdx].ToString() );
}
catch ( TclException e )
{
interp.transferResult( slaveInterp, e.GetCompletionCode() );
throw;
}
}
internal static void hide( Interp interp, Interp slaveInterp, int objIx, TclObject[] objv )
{
if ( interp._isSafe )
{
throw new TclException( interp, "permission denied: " + "safe interpreter cannot hide commands" );
}
int nameIdx = objv.Length - objIx == 1 ? objIx : objIx + 1;
try
{
slaveInterp.hideCommand( objv[objIx].ToString(), objv[nameIdx].ToString() );
}
catch ( TclException e )
{
interp.transferResult( slaveInterp, e.GetCompletionCode() );
throw;
}
}
internal static void hidden( Interp interp, Interp slaveInterp )
{
if ( slaveInterp._hiddenCmdTable == null )
{
return;
}
TclObject result = TclList.NewInstance();
interp.SetResult( result );
IEnumerator hiddenCmds = slaveInterp._hiddenCmdTable.Keys.GetEnumerator();
while ( hiddenCmds.MoveNext() )
{
string cmdName = (string)hiddenCmds.Current;
TclList.Append( interp, result, TclString.NewInstance( cmdName ) );
}
}
internal static void invokeHidden( Interp interp, Interp slaveInterp, bool global, int objIx, TclObject[] objv )
{
TCL.CompletionCode result;
if ( interp._isSafe )
{
throw new TclException( interp, "not allowed to " + "invoke hidden commands from safe interpreter" );
}
slaveInterp.preserve();
slaveInterp.allowExceptions();
TclObject[] localObjv = new TclObject[objv.Length - objIx];
for ( int i = 0; i < objv.Length - objIx; i++ )
{
localObjv[i] = objv[i + objIx];
}
try
{
if ( global )
{
slaveInterp.invokeGlobal( localObjv, Interp.INVOKE_HIDDEN );
}
else
{
slaveInterp.invoke( localObjv, Interp.INVOKE_HIDDEN );
}
result = slaveInterp._returnCode;
}
catch ( TclException e )
{
result = e.GetCompletionCode();
}
slaveInterp.release();
interp.transferResult( slaveInterp, result );
}
internal static void markTrusted( Interp interp, Interp slaveInterp )
{
if ( interp._isSafe )
{
throw new TclException( interp, "permission denied: " + "safe interpreter cannot mark trusted" );
}
slaveInterp._isSafe = false;
}
private static void makeSafe( Interp interp )
{
Channel chan; // Channel to remove from safe interpreter.
interp.hideUnsafeCommands();
interp._isSafe = true;
// Unsetting variables : (which should not have been set
// in the first place, but...)
// No env array in a safe slave.
try
{
interp.UnsetVar( "env", TCL.VarFlag.GLOBAL_ONLY );
}
catch ( TclException e )
{
}
// Remove unsafe parts of tcl_platform
try
{
interp.UnsetVar( "tcl_platform", "os", TCL.VarFlag.GLOBAL_ONLY );
}
catch ( TclException e )
{
}
try
{
interp.UnsetVar( "tcl_platform", "osVersion", TCL.VarFlag.GLOBAL_ONLY );
}
catch ( TclException e )
{
}
try
{
interp.UnsetVar( "tcl_platform", "machine", TCL.VarFlag.GLOBAL_ONLY );
}
catch ( TclException e )
{
}
try
{
interp.UnsetVar( "tcl_platform", "user", TCL.VarFlag.GLOBAL_ONLY );
}
catch ( TclException e )
{
}
// Unset path informations variables
// (the only one remaining is [info nameofexecutable])
try
{
interp.UnsetVar( "tclDefaultLibrary", TCL.VarFlag.GLOBAL_ONLY );
}
catch ( TclException e )
{
}
try
{
interp.UnsetVar( "tcl_library", TCL.VarFlag.GLOBAL_ONLY );
}
catch ( TclException e )
{
}
try
{
interp.UnsetVar( "tcl_pkgPath", TCL.VarFlag.GLOBAL_ONLY );
}
catch ( TclException e )
{
}
// Remove the standard channels from the interpreter; safe interpreters
// do not ordinarily have access to stdin, stdout and stderr.
//
// NOTE: These channels are not added to the interpreter by the
// Tcl_CreateInterp call, but may be added later, by another I/O
// operation. We want to ensure that the interpreter does not have
// these channels even if it is being made safe after being used for
// some time..
chan = TclIO.GetStdChannel( StdChannel.STDIN );
if ( chan != null )
{
TclIO.unregisterChannel( interp, chan );
}
chan = TclIO.GetStdChannel( StdChannel.STDOUT );
if ( chan != null )
{
TclIO.unregisterChannel( interp, chan );
}
chan = TclIO.GetStdChannel( StdChannel.STDERR );
if ( chan != null )
{
TclIO.unregisterChannel( interp, chan );
}
}
} // end InterpSlaveCmd
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.OCSPConfigurationBinding", Namespace="urn:iControl")]
public partial class ManagementOCSPConfiguration : iControlInterface {
public ManagementOCSPConfiguration() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_responder
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
public void add_responder(
string [] config_names,
string [] [] responders
) {
this.Invoke("add_responder", new object [] {
config_names,
responders});
}
public System.IAsyncResult Beginadd_responder(string [] config_names,string [] [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_responder", new object[] {
config_names,
responders}, callback, asyncState);
}
public void Endadd_responder(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
public void create(
string [] config_names,
string [] [] responders
) {
this.Invoke("create", new object [] {
config_names,
responders});
}
public System.IAsyncResult Begincreate(string [] config_names,string [] [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
config_names,
responders}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_configurations
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
public void delete_all_configurations(
) {
this.Invoke("delete_all_configurations", new object [0]);
}
public System.IAsyncResult Begindelete_all_configurations(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_configurations", new object[0], callback, asyncState);
}
public void Enddelete_all_configurations(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_configuration
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
public void delete_configuration(
string [] config_names
) {
this.Invoke("delete_configuration", new object [] {
config_names});
}
public System.IAsyncResult Begindelete_configuration(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_configuration", new object[] {
config_names}, callback, asyncState);
}
public void Enddelete_configuration(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] config_names
) {
object [] results = this.Invoke("get_description", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_responder
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_responder(
string [] config_names
) {
object [] results = this.Invoke("get_responder", new object [] {
config_names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_responder(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_responder", new object[] {
config_names}, callback, asyncState);
}
public string [] [] Endget_responder(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_responders
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
public void remove_all_responders(
string [] config_names
) {
this.Invoke("remove_all_responders", new object [] {
config_names});
}
public System.IAsyncResult Beginremove_all_responders(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_responders", new object[] {
config_names}, callback, asyncState);
}
public void Endremove_all_responders(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_responder
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
public void remove_responder(
string [] config_names,
string [] [] responders
) {
this.Invoke("remove_responder", new object [] {
config_names,
responders});
}
public System.IAsyncResult Beginremove_responder(string [] config_names,string [] [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_responder", new object[] {
config_names,
responders}, callback, asyncState);
}
public void Endremove_responder(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPConfiguration",
RequestNamespace="urn:iControl:Management/OCSPConfiguration", ResponseNamespace="urn:iControl:Management/OCSPConfiguration")]
public void set_description(
string [] config_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
config_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] config_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
config_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
//
// ComboBoxBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Gtk;
#if XWT_GTK3
using TreeModel = Gtk.ITreeModel;
#endif
namespace Xwt.GtkBackend
{
public class ComboBoxBackend: WidgetBackend, IComboBoxBackend, ICellRendererTarget
{
public ComboBoxBackend ()
{
}
public override void Initialize ()
{
//NeedsEventBox = false; // TODO: needs fix: no events with or without event box
Widget = (Gtk.ComboBox) CreateWidget ();
if (Widget.Cells.Length == 0) {
var cr = new Gtk.CellRendererText ();
Widget.PackStart (cr, false);
Widget.AddAttribute (cr, "text", 0);
}
Widget.Show ();
Widget.RowSeparatorFunc = IsRowSeparator;
}
protected virtual Gtk.Widget CreateWidget ()
{
return new Gtk.ComboBox ();
}
protected new Gtk.ComboBox Widget {
get { return (Gtk.ComboBox)base.Widget; }
set { base.Widget = value; }
}
protected new IComboBoxEventSink EventSink {
get { return (IComboBoxEventSink)base.EventSink; }
}
bool IsRowSeparator (TreeModel model, Gtk.TreeIter iter)
{
Gtk.TreePath path = model.GetPath (iter);
bool res = false;
ApplicationContext.InvokeUserCode (delegate {
res = EventSink.RowIsSeparator (path.Indices[0]);
});
return res;
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is ComboBoxEvent) {
if ((ComboBoxEvent)eventId == ComboBoxEvent.SelectionChanged)
Widget.Changed += HandleChanged;
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is ComboBoxEvent) {
if ((ComboBoxEvent)eventId == ComboBoxEvent.SelectionChanged)
Widget.Changed -= HandleChanged;
}
}
void HandleChanged (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (EventSink.OnSelectionChanged);
}
#region IComboBoxBackend implementation
public void SetViews (CellViewCollection views)
{
Widget.Clear ();
foreach (var v in views)
CellUtil.CreateCellRenderer (ApplicationContext, Frontend, this, null, v);
}
public void SetSource (IListDataSource source, IBackend sourceBackend)
{
ListStoreBackend b = sourceBackend as ListStoreBackend;
if (b == null) {
CustomListModel model = new CustomListModel (source, Widget);
Widget.Model = model.Store;
} else
Widget.Model = b.Store;
}
public int SelectedRow {
get {
return Widget.Active;
}
set {
Widget.Active = value;
}
}
#endregion
#region ICellRendererTarget implementation
public void PackStart (object target, Gtk.CellRenderer cr, bool expand)
{
Widget.PackStart (cr, expand);
}
public void PackEnd (object target, Gtk.CellRenderer cr, bool expand)
{
Widget.PackEnd (cr, expand);
}
public void AddAttribute (object target, Gtk.CellRenderer cr, string field, int column)
{
Widget.AddAttribute (cr, field, column);
}
public void SetCellDataFunc (object target, Gtk.CellRenderer cr, Gtk.CellLayoutDataFunc dataFunc)
{
Widget.SetCellDataFunc (cr, dataFunc);
}
Rectangle ICellRendererTarget.GetCellBounds (object target, Gtk.CellRenderer cr, Gtk.TreeIter iter)
{
return new Rectangle ();
}
Rectangle ICellRendererTarget.GetCellBackgroundBounds (object target, Gtk.CellRenderer cr, Gtk.TreeIter iter)
{
return new Rectangle ();
}
public virtual void SetCurrentEventRow (string path)
{
}
Gtk.Widget ICellRendererTarget.EventRootWidget {
get { return Widget; }
}
TreeModel ICellRendererTarget.Model {
get { return Widget.Model; }
}
Gtk.TreeIter ICellRendererTarget.PressedIter { get; set; }
CellViewBackend ICellRendererTarget.PressedCell { get; set; }
public bool GetCellPosition (Gtk.CellRenderer r, int ex, int ey, out int cx, out int cy, out Gtk.TreeIter it)
{
cx = cy = 0;
it = Gtk.TreeIter.Zero;
return false;
}
public void QueueDraw (object target, Gtk.TreeIter iter)
{
}
public void QueueResize (object target, Gtk.TreeIter iter)
{
}
bool disposed;
protected override void Dispose(bool disposing)
{
if (disposing && !disposed)
Widget.RowSeparatorFunc = null;
disposed = true;
base.Dispose(disposing);
}
#endregion
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
#nullable disable
using System;
using System.Collections;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using Scriban.Runtime;
using Scriban.Syntax;
namespace Scriban.Functions
{
/// <summary>
/// String functions available through the builtin object 'string`.
/// </summary>
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
class StringFunctions : ScriptObject
{
[ThreadStatic] private static StringBuilder _tlsBuilder;
private static StringBuilder GetTempStringBuilder()
{
var builder = _tlsBuilder;
if (builder == null) builder = _tlsBuilder = new StringBuilder(1024);
return builder;
}
private static void ReleaseBuilder(StringBuilder builder) => builder.Length = 0;
/// <summary>
/// Escapes a string with escape characters.
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The two strings concatenated</returns>
/// <remarks>
/// ```scriban-html
/// {{ "Hel\tlo\n\"W\\orld" | string.escape }}
/// ```
/// ```html
/// Hel\tlo\n\"W\\orld
/// ```
/// </remarks>
public static string Escape(string text)
{
if (text == null) return text;
StringBuilder builder = null;
for (int i = 0; i < text.Length; i++)
{
var c = text[i];
if (c < 32 || c == '"' || c == '\\')
{
string appendText;
switch (c)
{
case '"':
appendText = "\\\"";
break;
case '\\':
appendText = "\\\\";
break;
case '\a':
appendText = "\\a";
break;
case '\b':
appendText = "\\b";
break;
case '\t':
appendText = "\\t";
break;
case '\r':
appendText = "\\r";
break;
case '\v':
appendText = "\\v";
break;
case '\f':
appendText = "\\f";
break;
case '\n':
appendText = "\\n";
break;
default:
appendText = $"\\x{(int)c:x2}";
break;
}
if (builder == null)
{
builder = new StringBuilder(text.Length + 10);
if (i > 0) builder.Append(text, 0, i);
}
builder.Append(appendText);
}
else if (builder != null)
{
// TODO: could be more optimized by adding range
builder.Append(c);
}
}
return builder != null ? builder.ToString() : text;
}
/// <summary>
/// Concatenates two strings
/// </summary>
/// <param name="text">The input string</param>
/// <param name="with">The text to append</param>
/// <returns>The two strings concatenated</returns>
/// <remarks>
/// ```scriban-html
/// {{ "Hello" | string.append " World" }}
/// ```
/// ```html
/// Hello World
/// ```
/// </remarks>
public static string Append(string text, string with)
{
return (text ?? string.Empty) + (with ?? string.Empty);
}
/// <summary>
/// Converts the first character of the passed string to a upper case character.
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The capitalized input string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "test" | string.capitalize }}
/// ```
/// ```html
/// Test
/// ```
/// </remarks>
public static string Capitalize(string text)
{
if (string.IsNullOrEmpty(text) || char.IsUpper(text[0]))
{
return text ?? string.Empty;
}
var builder = GetTempStringBuilder();
builder.Append(char.ToUpper(text[0]));
if (text.Length > 1)
{
builder.Append(text, 1, text.Length - 1);
}
var result = builder.ToString();
ReleaseBuilder(builder);
return result;
}
/// <summary>
/// Converts the first character of each word in the passed string to a upper case character.
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The capitalized input string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "This is easy" | string.capitalizewords }}
/// ```
/// ```html
/// This Is Easy
/// ```
/// </remarks>
public static string Capitalizewords(string text)
{
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
var builder = GetTempStringBuilder();
var previousSpace = true;
for (int i = 0; i < text.Length; i++)
{
var c = text[i];
if (char.IsWhiteSpace(c))
{
previousSpace = true;
}
else if (previousSpace && char.IsLetter(c))
{
// TODO: Handle culture
c = char.ToUpper(c);
previousSpace = false;
}
builder.Append(c);
}
var result = builder.ToString();
ReleaseBuilder(builder);
return result;
}
/// <summary>
/// Returns a boolean indicating whether the input string contains the specified string `value`.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="value">The string to look for</param>
/// <returns><c>true</c> if `text` contains the string `value`</returns>
/// <remarks>
/// ```scriban-html
/// {{ "This is easy" | string.contains "easy" }}
/// ```
/// ```html
/// true
/// ```
/// </remarks>
public static bool Contains(string text, string value)
{
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(value))
{
return false;
}
return text.Contains(value);
}
/// <summary>
/// Returns a boolean indicating whether the input string is an empty string.
/// </summary>
/// <param name="text">The input string</param>
/// <returns><c>true</c> if `text` is an empty string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "" | string.empty }}
/// ```
/// ```html
/// true
/// ```
/// </remarks>
public static bool Empty(string text)
{
return string.IsNullOrEmpty(text);
}
/// <summary>
/// Returns a boolean indicating whether the input string is empty or contains only whitespace characters.
/// </summary>
/// <param name="text">The input string</param>
/// <returns><c>true</c> if `text` is empty string or contains only whitespace characters</returns>
/// <remarks>
/// ```scriban-html
/// {{ "" | string.whitespace }}
/// ```
/// ```html
/// true
/// ```
/// </remarks>
public static bool Whitespace(string text)
{
return string.IsNullOrWhiteSpace(text);
}
/// <summary>
/// Converts the string to lower case.
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The input string lower case</returns>
/// <remarks>
/// ```scriban-html
/// {{ "TeSt" | string.downcase }}
/// ```
/// ```html
/// test
/// ```
/// </remarks>
public static string Downcase(string text)
{
return text?.ToLowerInvariant();
}
/// <summary>
/// Returns a boolean indicating whether the input string ends with the specified string `value`.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="value">The string to look for</param>
/// <returns><c>true</c> if `text` ends with the specified string `value`</returns>
/// <remarks>
/// ```scriban-html
/// {{ "This is easy" | string.ends_with "easy" }}
/// ```
/// ```html
/// true
/// ```
/// </remarks>
public static bool EndsWith(string text, string value)
{
if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(text))
{
return false;
}
return text.EndsWith(value);
}
/// <summary>
/// Returns a url handle from the input string.
/// </summary>
/// <param name="text">The input string</param>
/// <returns>A url handle</returns>
/// <remarks>
/// ```scriban-html
/// {{ '100% M & Ms!!!' | string.handleize }}
/// ```
/// ```html
/// 100-m-ms
/// ```
/// </remarks>
public static string Handleize(string text)
{
var builder = GetTempStringBuilder();
char lastChar = (char) 0;
for (int i = 0; i < text.Length; i++)
{
var c = text[i];
if (char.IsLetterOrDigit(c))
{
lastChar = c;
builder.Append(char.ToLowerInvariant(c));
}
else if (lastChar != '-')
{
builder.Append('-');
lastChar = '-';
}
}
if (builder.Length > 0 && builder[builder.Length - 1] == '-')
{
builder.Length--;
}
var result = builder.ToString();
ReleaseBuilder(builder);
return result;
}
/// <summary>
/// Return a string literal enclosed with double quotes of the input string.
/// </summary>
/// <param name="text">The string to return a literal from.</param>
/// <returns>The literal of a string.</returns>
/// <remarks>
/// If the input string has non printable characters or they need contain a double quote, they will be escaped.
/// ```scriban-html
/// {{ 'Hello\n"World"' | string.literal }}
/// ```
/// ```html
/// "Hello\n\"World\""
/// ```
/// </remarks>
public static string Literal(string text)
{
return text == null ? null : $"\"{Escape(text)}\"";
}
/// <summary>
/// Removes any whitespace characters on the **left** side of the input string.
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The input string without any left whitespace characters</returns>
/// <remarks>
/// ```scriban-html
/// {{ ' too many spaces' | string.lstrip }}
/// ```
/// > Highlight to see the empty spaces to the right of the string
/// ```html
/// too many spaces
/// ```
/// </remarks>
public static string LStrip(string text)
{
return text?.TrimStart();
}
/// <summary>
/// Outputs the singular or plural version of a string based on the value of a number.
/// </summary>
/// <param name="number">The number to check</param>
/// <param name="singular">The singular string to return if number is == 1</param>
/// <param name="plural">The plural string to return if number is != 1</param>
/// <returns>The singular or plural string based on number</returns>
/// <remarks>
/// ```scriban-html
/// {{ products.size }} {{products.size | string.pluralize 'product' 'products' }}
/// ```
/// ```html
/// 7 products
/// ```
/// </remarks>
public static string Pluralize(int number, string singular, string plural)
{
return number == 1 ? singular : plural;
}
/// <summary>
/// Concatenates two strings by placing the `by` string in from of the `text` string
/// </summary>
/// <param name="text">The input string</param>
/// <param name="by">The string to prepend to `text`</param>
/// <returns>The two strings concatenated</returns>
/// <remarks>
/// ```scriban-html
/// {{ "World" | string.prepend "Hello " }}
/// ```
/// ```html
/// Hello World
/// ```
/// </remarks>
public static string Prepend(string text, string by)
{
return (by ?? string.Empty) + (text ?? string.Empty);
}
/// <summary>
/// Removes all occurrences of a substring from a string.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="remove">The substring to remove from the `text` string</param>
/// <returns>The input string with the all occurence of a substring removed</returns>
/// <remarks>
/// ```scriban-html
/// {{ "Hello, world. Goodbye, world." | string.remove "world" }}
/// ```
/// ```html
/// Hello, . Goodbye, .
/// ```
/// </remarks>
public static string Remove(string text, string remove)
{
if (string.IsNullOrEmpty(remove) || string.IsNullOrEmpty(text))
{
return text;
}
return text.Replace(remove, string.Empty);
}
/// <summary>
/// Removes the first occurrence of a substring from a string.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="remove">The first occurence of substring to remove from the `text` string</param>
/// <returns>The input string with the first occurence of a substring removed</returns>
/// <remarks>
/// ```scriban-html
/// {{ "Hello, world. Goodbye, world." | string.remove_first "world" }}
/// ```
/// ```html
/// Hello, . Goodbye, world.
/// ```
/// </remarks>
public static string RemoveFirst(string text, string remove)
{
return ReplaceFirst(text, remove, string.Empty);
}
/// <summary>
/// Replaces all occurrences of a string with a substring.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="match">The substring to find in the `text` string</param>
/// <param name="replace">The substring used to replace the string matched by `match` in the input `text`</param>
/// <returns>The input string replaced</returns>
/// <remarks>
/// ```scriban-html
/// {{ "Hello, world. Goodbye, world." | string.replace "world" "buddy" }}
/// ```
/// ```html
/// Hello, buddy. Goodbye, buddy.
/// ```
/// </remarks>
public static string Replace(string text, string match, string replace)
{
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
match = match ?? string.Empty;
replace = replace ?? string.Empty;
return text.Replace(match, replace);
}
/// <summary>
/// Replaces the first occurrence of a string with a substring.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="match">The substring to find in the `text` string</param>
/// <param name="replace">The substring used to replace the string matched by `match` in the input `text`</param>
/// <returns>The input string replaced</returns>
/// <remarks>
/// ```scriban-html
/// {{ "Hello, world. Goodbye, world." | string.replace_first "world" "buddy" }}
/// ```
/// ```html
/// Hello, buddy. Goodbye, world.
/// ```
/// </remarks>
public static string ReplaceFirst(string text, string match, string replace)
{
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
if (string.IsNullOrEmpty(match))
{
return text;
}
replace = replace ?? string.Empty;
var indexOfMatch = text.IndexOf(match, StringComparison.OrdinalIgnoreCase);
if (indexOfMatch < 0)
{
return text;
}
var builder = GetTempStringBuilder();
builder.Append(text.Substring(0, indexOfMatch));
builder.Append(replace);
builder.Append(text.Substring(indexOfMatch + match.Length));
var result = builder.ToString();
ReleaseBuilder(builder);
return result;
}
/// <summary>
/// Removes any whitespace characters on the **right** side of the input string.
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The input string without any left whitespace characters</returns>
/// <remarks>
/// ```scriban-html
/// {{ ' too many spaces ' | string.rstrip }}
/// ```
/// > Highlight to see the empty spaces to the right of the string
/// ```html
/// too many spaces
/// ```
/// </remarks>
public static string RStrip(string text)
{
return text?.TrimEnd();
}
/// <summary>
/// Returns the number of characters from the input string
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The length of the input string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "test" | string.size }}
/// ```
/// ```html
/// 4
/// ```
/// </remarks>
public static int Size(string text)
{
return string.IsNullOrEmpty(text) ? 0 : text.Length;
}
/// <summary>
/// The slice returns a substring, starting at the specified index. An optional second parameter can be passed to specify the length of the substring.
/// If no second parameter is given, a substring with the remaining characters will be returned.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="start">The starting index character where the slice should start from the input `text` string</param>
/// <param name="length">The number of character. Default is 0, meaning that the remaining of the string will be returned.</param>
/// <returns>The input string sliced</returns>
/// <remarks>
/// ```scriban-html
/// {{ "hello" | string.slice 0 }}
/// {{ "hello" | string.slice 1 }}
/// {{ "hello" | string.slice 1 3 }}
/// {{ "hello" | string.slice 1 length:3 }}
/// ```
/// ```html
/// hello
/// ello
/// ell
/// ell
/// ```
/// </remarks>
public static string Slice(string text, int start, int? length = null)
{
if (string.IsNullOrEmpty(text) || start >= text.Length)
{
return string.Empty;
}
if (start < 0)
{
start = start + text.Length;
}
if (!length.HasValue)
{
length = text.Length;
}
if (start < 0)
{
if (start + length <= 0)
{
return string.Empty;
}
length = length + start;
start = 0;
}
if (start + length > text.Length)
{
length = text.Length - start;
}
return text.Substring(start, length.Value);
}
/// <summary>
/// The slice returns a substring, starting at the specified index. An optional second parameter can be passed to specify the length of the substring.
/// If no second parameter is given, a substring with the first character will be returned.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="start">The starting index character where the slice should start from the input `text` string</param>
/// <param name="length">The number of character. Default is 1, meaning that only the first character at `start` position will be returned.</param>
/// <returns>The input string sliced</returns>
/// <remarks>
/// ```scriban-html
/// {{ "hello" | string.slice1 0 }}
/// {{ "hello" | string.slice1 1 }}
/// {{ "hello" | string.slice1 1 3 }}
/// {{ "hello" | string.slice1 1 length: 3 }}
/// ```
/// ```html
/// h
/// e
/// ell
/// ell
/// ```
/// </remarks>
public static string Slice1(string text, int start, int length = 1)
{
if (string.IsNullOrEmpty(text) || start > text.Length || length <= 0)
{
return string.Empty;
}
if (start < 0)
{
start = start + text.Length;
}
if (start < 0)
{
length = length + start;
start = 0;
}
if (start + length > text.Length)
{
length = text.Length - start;
}
return text.Substring(start, length);
}
/// <summary>
/// The `split` function takes on a substring as a parameter.
/// The substring is used as a delimiter to divide a string into an array. You can output different parts of an array using `array` functions.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="match">The string used to split the input `text` string</param>
/// <returns>An enumeration of the substrings</returns>
/// <remarks>
/// ```scriban-html
/// {{ for word in "Hi, how are you today?" | string.split ' ' ~}}
/// {{ word }}
/// {{ end ~}}
/// ```
/// ```html
/// Hi,
/// how
/// are
/// you
/// today?
/// ```
/// </remarks>
public static IEnumerable Split(string text, string match)
{
if (string.IsNullOrEmpty(text))
{
return new ScriptRange(Enumerable.Empty<string>());
}
return new ScriptRange(text.Split(new[] {match}, StringSplitOptions.RemoveEmptyEntries));
}
/// <summary>
/// Returns a boolean indicating whether the input string starts with the specified string `value`.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="value">The string to look for</param>
/// <returns><c>true</c> if `text` starts with the specified string `value`</returns>
/// <remarks>
/// ```scriban-html
/// {{ "This is easy" | string.starts_with "This" }}
/// ```
/// ```html
/// true
/// ```
/// </remarks>
public static bool StartsWith(string text, string value)
{
if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(text))
{
return false;
}
return text.StartsWith(value);
}
/// <summary>
/// Removes any whitespace characters on the **left** and **right** side of the input string.
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The input string without any left and right whitespace characters</returns>
/// <remarks>
/// ```scriban-html
/// {{ ' too many spaces ' | string.strip }}
/// ```
/// > Highlight to see the empty spaces to the right of the string
/// ```html
/// too many spaces
/// ```
/// </remarks>
public static string Strip(string text)
{
return text?.Trim();
}
/// <summary>
/// Removes any line breaks/newlines from a string.
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The input string without any breaks/newlines characters</returns>
/// <remarks>
/// ```scriban-html
/// {{ "This is a string.\r\n With \nanother \rstring" | string.strip_newlines }}
/// ```
/// ```html
/// This is a string. With another string
/// ```
/// </remarks>
public static string StripNewlines(string text)
{
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
return Regex.Replace(text, @"\r\n|\r|\n", string.Empty);
}
/// <summary>
/// Converts a string to an integer
/// </summary>
/// <param name="context">The template context</param>
/// <param name="text">The input string</param>
/// <returns>A 32 bit integer or null if conversion failed</returns>
/// <remarks>
/// ```scriban-html
/// {{ "123" | string.to_int + 1 }}
/// ```
/// ```html
/// 124
/// ```
/// </remarks>
public static object ToInt(TemplateContext context, string text)
{
return int.TryParse(text, NumberStyles.Integer, context.CurrentCulture, out int result) ? (object) result : null;
}
/// <summary>
/// Converts a string to a long 64 bit integer
/// </summary>
/// <param name="context">The template context</param>
/// <param name="text">The input string</param>
/// <returns>A 64 bit integer or null if conversion failed</returns>
/// <remarks>
/// ```scriban-html
/// {{ "123678912345678" | string.to_long + 1 }}
/// ```
/// ```html
/// 123678912345679
/// ```
/// </remarks>
public static object ToLong(TemplateContext context, string text)
{
return long.TryParse(text, NumberStyles.Integer, context.CurrentCulture, out long result) ? (object)result : null;
}
/// <summary>
/// Converts a string to a float
/// </summary>
/// <param name="context">The template context</param>
/// <param name="text">The input string</param>
/// <returns>A 32 bit float or null if conversion failed</returns>
/// <remarks>
/// ```scriban-html
/// {{ "123.4" | string.to_float + 1 }}
/// ```
/// ```html
/// 124.4
/// ```
/// </remarks>
public static object ToFloat(TemplateContext context, string text)
{
return float.TryParse(text, NumberStyles.Float | NumberStyles.AllowThousands, context.CurrentCulture, out float result) ? (object)result : null;
}
/// <summary>
/// Converts a string to a double
/// </summary>
/// <param name="context">The template context</param>
/// <param name="text">The input string</param>
/// <returns>A 64 bit float or null if conversion failed</returns>
/// <remarks>
/// ```scriban-html
/// {{ "123.4" | string.to_double + 1 }}
/// ```
/// ```html
/// 124.4
/// ```
/// </remarks>
public static object ToDouble(TemplateContext context, string text)
{
return double.TryParse(text, NumberStyles.Float | NumberStyles.AllowThousands, context.CurrentCulture, out double result) ? (object)result : null;
}
/// <summary>
/// Truncates a string down to the number of characters passed as the first parameter.
/// An ellipsis (...) is appended to the truncated string and is included in the character count
/// </summary>
/// <param name="text">The input string</param>
/// <param name="length">The maximum length of the output string, including the length of the `ellipsis`</param>
/// <param name="ellipsis">The ellipsis to append to the end of the truncated string</param>
/// <returns>The truncated input string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "The cat came back the very next day" | string.truncate 13 }}
/// ```
/// ```html
/// The cat ca...
/// ```
/// </remarks>
public static string Truncate(string text, int length, string ellipsis = null)
{
ellipsis = ellipsis ?? "...";
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
int lMinusTruncate = length - ellipsis.Length;
if (text.Length > length)
{
var builder = GetTempStringBuilder();
builder.Append(text, 0, lMinusTruncate < 0 ? 0 : lMinusTruncate);
builder.Append(ellipsis);
text = builder.ToString();
ReleaseBuilder(builder);
}
return text;
}
/// <summary>
/// Truncates a string down to the number of words passed as the first parameter.
/// An ellipsis (...) is appended to the truncated string.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="count">The number of words to keep from the input `text` string before appending the `ellipsis`</param>
/// <param name="ellipsis">The ellipsis to append to the end of the truncated string</param>
/// <returns>The truncated input string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "The cat came back the very next day" | string.truncatewords 4 }}
/// ```
/// ```html
/// The cat came back...
/// ```
/// </remarks>
public static string Truncatewords(string text, int count, string ellipsis = null)
{
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
var builder = GetTempStringBuilder();
bool isFirstWord = true;
foreach (var word in Regex.Split(text, @"\s+"))
{
if (count <= 0)
{
break;
}
if (!isFirstWord)
{
builder.Append(' ');
}
builder.Append(word);
isFirstWord = false;
count--;
}
builder.Append("...");
var result = builder.ToString();
ReleaseBuilder(builder);
return result;
}
/// <summary>
/// Converts the string to uppercase
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The input string upper case</returns>
/// <remarks>
/// ```scriban-html
/// {{ "test" | string.upcase }}
/// ```
/// ```html
/// TEST
/// ```
/// </remarks>
public static string Upcase(string text)
{
return text?.ToUpperInvariant();
}
/// <summary>
/// Computes the `md5` hash of the input string
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The `md5` hash of the input string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "test" | string.md5 }}
/// ```
/// ```html
/// 098f6bcd4621d373cade4e832627b4f6
/// ```
/// </remarks>
public static string Md5(string text)
{
text = text ?? string.Empty;
using (var md5 = System.Security.Cryptography.MD5.Create())
{
return Hash(md5, text);
}
}
/// <summary>
/// Computes the `sha1` hash of the input string
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The `sha1` hash of the input string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "test" | string.sha1 }}
/// ```
/// ```html
/// a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
/// ```
/// </remarks>
public static string Sha1(string text)
{
using (var sha1 = System.Security.Cryptography.SHA1.Create())
{
return Hash(sha1, text);
}
}
/// <summary>
/// Computes the `sha256` hash of the input string
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The `sha256` hash of the input string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "test" | string.sha256 }}
/// ```
/// ```html
/// 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
/// ```
/// </remarks>
public static string Sha256(string text)
{
using (var sha256 = System.Security.Cryptography.SHA256.Create())
{
return Hash(sha256, text);
}
}
/// <summary>
/// Converts a string into a SHA-1 hash using a hash message authentication code (HMAC). Pass the secret key for the message as a parameter to the function.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="secretKey">The secret key</param>
/// <returns>The `SHA-1` hash of the input string using a hash message authentication code (HMAC)</returns>
/// <remarks>
/// ```scriban-html
/// {{ "test" | string.hmac_sha1 "secret" }}
/// ```
/// ```html
/// 1aa349585ed7ecbd3b9c486a30067e395ca4b356
/// ```
/// </remarks>
public static string HmacSha1(string text, string secretKey)
{
using (var hsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(secretKey ?? string.Empty)))
{
return Hash(hsha1, text);
}
}
/// <summary>
/// Converts a string into a SHA-256 hash using a hash message authentication code (HMAC). Pass the secret key for the message as a parameter to the function.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="secretKey">The secret key</param>
/// <returns>The `SHA-256` hash of the input string using a hash message authentication code (HMAC)</returns>
/// <remarks>
/// ```scriban-html
/// {{ "test" | string.hmac_sha256 "secret" }}
/// ```
/// ```html
/// 0329a06b62cd16b33eb6792be8c60b158d89a2ee3a876fce9a881ebb488c0914
/// ```
/// </remarks>
public static string HmacSha256(string text, string secretKey)
{
using (var hsha256 = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(secretKey ?? string.Empty)))
{
return Hash(hsha256, text);
}
}
private static string Hash(System.Security.Cryptography.HashAlgorithm algo, string text)
{
text = text ?? string.Empty;
var bytes = Encoding.UTF8.GetBytes(text);
var hash = algo.ComputeHash(bytes);
var sb = GetTempStringBuilder();
for (var i = 0; i < hash.Length; i++)
{
var b = hash[i];
sb.Append(b.ToString("x2"));
}
var result = sb.ToString();
ReleaseBuilder(sb);
return result;
}
/// <summary>
/// Pads a string with leading spaces to a specified total length.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="width">The number of characters in the resulting string</param>
/// <returns>The input string padded</returns>
/// <remarks>
/// ```scriban-html
/// hello{{ "world" | string.pad_left 10 }}
/// ```
/// ```html
/// hello world
/// ```
/// </remarks>
public static string PadLeft(string text, int width)
{
return (text ?? string.Empty).PadLeft(width);
}
/// <summary>
/// Pads a string with trailing spaces to a specified total length.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="width">The number of characters in the resulting string</param>
/// <returns>The input string padded</returns>
/// <remarks>
/// ```scriban-html
/// {{ "hello" | string.pad_right 10 }}world
/// ```
/// ```html
/// hello world
/// ```
/// </remarks>
public static string PadRight(string text, int width)
{
return (text ?? string.Empty).PadRight(width);
}
/// <summary>
/// Encodes a string to its Base64 representation.
/// Its character encoded will be UTF-8.
/// </summary>
/// <param name="text">The string to encode</param>
/// <returns>The encoded string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "hello" | string.base64_encode }}
/// ```
/// ```html
/// aGVsbG8=
/// ```
/// </remarks>
public static string Base64Encode(string text)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(text ?? string.Empty));
}
/// <summary>
/// Decodes a Base64-encoded string to a byte array.
/// The encoding of the bytes is assumed to be UTF-8.
/// </summary>
/// <param name="text">The string to decode</param>
/// <returns>The decoded string</returns>
/// <remarks>
/// ```scriban-html
/// {{ "aGVsbG8=" | string.base64_decode }}
/// ```
/// ```html
/// hello
/// ```
/// </remarks>
public static string Base64Decode(string text)
{
var decoded = Convert.FromBase64String(text ?? string.Empty);
return Encoding.UTF8.GetString(decoded);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection.Internal;
using System.Text;
using Xunit;
namespace System.Reflection.Metadata.Tests
{
public class BlobReaderTests
{
[Fact]
public unsafe void PublicBlobReaderCtorValidatesArgs()
{
byte* bufferPtrForLambda;
byte[] buffer = new byte[4] { 0, 1, 0, 2 };
fixed (byte* bufferPtr = buffer)
{
bufferPtrForLambda = bufferPtr;
Assert.Throws<ArgumentOutOfRangeException>(() => new BlobReader(bufferPtrForLambda, -1));
}
Assert.Throws<ArgumentNullException>(() => new BlobReader(null, 1));
Assert.Equal(0, new BlobReader(null, 0).Length); // this is valid
Assert.Throws<BadImageFormatException>(() => new BlobReader(null, 0).ReadByte()); // but can't read anything non-empty from it...
Assert.Same(String.Empty, new BlobReader(null, 0).ReadUtf8NullTerminated()); // can read empty string.
}
[Fact]
public unsafe void ReadFromMemoryReader()
{
byte[] buffer = new byte[4] { 0, 1, 0, 2 };
fixed (byte* bufferPtr = buffer)
{
var reader = new BlobReader(new MemoryBlock(bufferPtr, buffer.Length));
Assert.False(reader.SeekOffset(-1));
Assert.False(reader.SeekOffset(Int32.MaxValue));
Assert.False(reader.SeekOffset(Int32.MinValue));
Assert.False(reader.SeekOffset(buffer.Length));
Assert.True(reader.SeekOffset(buffer.Length - 1));
Assert.True(reader.SeekOffset(0));
Assert.Equal(0, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadUInt64());
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(1));
Assert.Equal(1, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadDouble());
Assert.Equal(1, reader.Offset);
Assert.True(reader.SeekOffset(2));
Assert.Equal(2, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadUInt32());
Assert.Equal((ushort)0x0200, reader.ReadUInt16());
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(2));
Assert.Equal(2, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadSingle());
Assert.Equal(2, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Equal(9.404242E-38F, reader.ReadSingle());
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(3));
Assert.Equal(3, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadUInt16());
Assert.Equal((byte)0x02, reader.ReadByte());
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Equal("\u0000\u0001\u0000\u0002", reader.ReadUTF8(4));
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadUTF8(5));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadUTF8(-1));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Equal("\u0100\u0200", reader.ReadUTF16(4));
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(5));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(-1));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(6));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Equal(buffer, reader.ReadBytes(4));
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Same(String.Empty, reader.ReadUtf8NullTerminated());
Assert.Equal(1, reader.Offset);
Assert.True(reader.SeekOffset(1));
Assert.Equal("\u0001", reader.ReadUtf8NullTerminated());
Assert.Equal(3, reader.Offset);
Assert.True(reader.SeekOffset(3));
Assert.Equal("\u0002", reader.ReadUtf8NullTerminated());
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Same(String.Empty, reader.ReadUtf8NullTerminated());
Assert.Equal(1, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadBytes(5));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadBytes(Int32.MinValue));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.GetMemoryBlockAt(-1, 1));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.GetMemoryBlockAt(1, -1));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Equal(3, reader.GetMemoryBlockAt(1, 3).Length);
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(3));
reader.ReadByte();
Assert.Equal(4, reader.Offset);
Assert.Equal(4, reader.Offset);
Assert.Equal(0, reader.ReadBytes(0).Length);
Assert.Equal(4, reader.Offset);
int value;
Assert.False(reader.TryReadCompressedInteger(out value));
Assert.Equal(BlobReader.InvalidCompressedInteger, value);
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadCompressedInteger());
Assert.Equal(4, reader.Offset);
Assert.Equal(SerializationTypeCode.Invalid, reader.ReadSerializationTypeCode());
Assert.Equal(4, reader.Offset);
Assert.Equal(SignatureTypeCode.Invalid, reader.ReadSignatureTypeCode());
Assert.Equal(4, reader.Offset);
Assert.Equal(default(EntityHandle), reader.ReadTypeHandle());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadBoolean());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadByte());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadSByte());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadUInt32());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadInt32());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadUInt64());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadInt64());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadSingle());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadDouble());
Assert.Equal(4, reader.Offset);
}
byte[] buffer2 = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 };
fixed (byte* bufferPtr2 = buffer2)
{
var reader = new BlobReader(new MemoryBlock(bufferPtr2, buffer2.Length));
Assert.Equal(reader.Offset, 0);
Assert.Equal(0x0807060504030201UL, reader.ReadUInt64());
Assert.Equal(reader.Offset, 8);
reader.Reset();
Assert.Equal(reader.Offset, 0);
Assert.Equal(0x0807060504030201L, reader.ReadInt64());
reader.Reset();
Assert.Equal(reader.Offset, 0);
Assert.Equal(BitConverter.ToDouble(buffer2, 0), reader.ReadDouble());
}
}
[Fact]
public unsafe void ValidatePeekReferenceSize()
{
byte[] buffer = new byte[8] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
fixed (byte* bufferPtr = buffer)
{
var block = new MemoryBlock(bufferPtr, buffer.Length);
// small ref size always fits in 16 bits
Assert.Equal(0xFFFF, block.PeekReference(0, smallRefSize: true));
Assert.Equal(0xFFFF, block.PeekReference(4, smallRefSize: true));
Assert.Equal(0xFFFFU, block.PeekTaggedReference(0, smallRefSize: true));
Assert.Equal(0xFFFFU, block.PeekTaggedReference(4, smallRefSize: true));
Assert.Equal(0x01FFU, block.PeekTaggedReference(6, smallRefSize: true));
// large ref size throws on > RIDMask when tagged variant is not used.
Assert.Throws<BadImageFormatException>(() => block.PeekReference(0, smallRefSize: false));
Assert.Throws<BadImageFormatException>(() => block.PeekReference(4, smallRefSize: false));
// large ref size does not throw when Tagged variant is used.
Assert.Equal(0xFFFFFFFFU, block.PeekTaggedReference(0, smallRefSize: false));
Assert.Equal(0x01FFFFFFU, block.PeekTaggedReference(4, smallRefSize: false));
// bounds check applies in all cases
Assert.Throws<BadImageFormatException>(() => block.PeekReference(7, smallRefSize: true));
Assert.Throws<BadImageFormatException>(() => block.PeekReference(5, smallRefSize: false));
}
}
[Fact]
public unsafe void ReadFromMemoryBlock()
{
byte[] buffer = new byte[4] { 0, 1, 0, 2 };
fixed (byte* bufferPtr = buffer)
{
var block = new MemoryBlock(bufferPtr, buffer.Length);
Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(Int32.MaxValue));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(-1));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(Int32.MinValue));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(4));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(1));
Assert.Equal(0x02000100U, block.PeekUInt32(0));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(Int32.MaxValue));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(-1));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(Int32.MinValue));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(4));
Assert.Equal(0x0200, block.PeekUInt16(2));
int bytesRead;
MetadataStringDecoder stringDecoder = MetadataStringDecoder.DefaultUTF8;
Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MaxValue, null, stringDecoder, out bytesRead));
Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(-1, null, stringDecoder, out bytesRead));
Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MinValue, null, stringDecoder, out bytesRead));
Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(5, null, stringDecoder, out bytesRead));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 1));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(1, -1));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(0, -1));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 0));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-Int32.MaxValue, Int32.MaxValue));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, -Int32.MaxValue));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, Int32.MaxValue));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(block.Length, -1));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, block.Length));
Assert.Equal("\u0001", block.PeekUtf8NullTerminated(1, null, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 2);
Assert.Equal("\u0002", block.PeekUtf8NullTerminated(3, null, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 1);
Assert.Equal("", block.PeekUtf8NullTerminated(4, null, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 0);
byte[] helloPrefix = Encoding.UTF8.GetBytes("Hello");
Assert.Equal("Hello\u0001", block.PeekUtf8NullTerminated(1, helloPrefix, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 2);
Assert.Equal("Hello\u0002", block.PeekUtf8NullTerminated(3, helloPrefix, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 1);
Assert.Equal("Hello", block.PeekUtf8NullTerminated(4, helloPrefix, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 0);
}
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kodestruct.Common.CalculationLogger.Interfaces;
using Kodestruct.Common.Section.Interfaces;
using Kodestruct.Concrete.ACI;
using Kodestruct.Common.Mathematics;
namespace Kodestruct.Concrete.ACI318_14
{
public partial class ConcreteSectionCompression : ConcreteCompressionSectionBase
{
public ConcreteSectionCompression(IConcreteSectionWithLongitudinalRebar Section,
ConfinementReinforcementType ConfinementReinforcementType,
ICalcLog log, bool IsPrestressed =false )
: base(Section.Section, Section.LongitudinalBars, log)
{
this.ConfinementReinforcementType = ConfinementReinforcementType;
switch (ConfinementReinforcementType)
{
case ConfinementReinforcementType.Spiral:
this.CompressionMemberType = IsPrestressed == false ? CompressionMemberType.NonPrestressedWithSpirals : CompressionMemberType.PrestressedWithSpirals;
break;
case ConfinementReinforcementType.Ties:
this.CompressionMemberType = IsPrestressed == false ? CompressionMemberType.NonPrestressedWithTies : CompressionMemberType.PrestressedWithTies;
break;
case ConfinementReinforcementType.NoReinforcement:
throw new Exception("Invalid type of ConfinementReinforcementType variable. Specify either ties or spirals. Alternatively use nodes for plain concrete design");
break;
this.CompressionMemberType = IsPrestressed == false ? CompressionMemberType.NonPrestressedWithTies : CompressionMemberType.PrestressedWithTies;
break;
}
}
public ConcreteSectionCompression(IConcreteSection Section,
List<RebarPoint> LongitudinalBars, CompressionMemberType CompressionMemberType, ICalcLog log)
: base(Section, LongitudinalBars, log)
{
this.CompressionMemberType = CompressionMemberType;
switch (CompressionMemberType)
{
case CompressionMemberType.NonPrestressedWithTies:
ConfinementReinforcementType = ACI.ConfinementReinforcementType.Ties;
break;
case CompressionMemberType.NonPrestressedWithSpirals:
ConfinementReinforcementType = ConfinementReinforcementType.Spiral;
break;
case CompressionMemberType.PrestressedWithTies:
ConfinementReinforcementType = ConfinementReinforcementType.Ties;
break;
case CompressionMemberType.PrestressedWithSpirals:
ConfinementReinforcementType = ConfinementReinforcementType.Spiral;
break;
default:
ConfinementReinforcementType = ACI.ConfinementReinforcementType.Ties;
break;
}
}
public ConcreteSectionCompression(ConcreteSectionFlexure FlexuralSection, CompressionMemberType CompressionMemberType, ICalcLog log)
: base(FlexuralSection.Section, FlexuralSection.LongitudinalBars, log)
{
this.CompressionMemberType = CompressionMemberType;
switch (CompressionMemberType)
{
case CompressionMemberType.NonPrestressedWithTies:
ConfinementReinforcementType = ACI.ConfinementReinforcementType.Ties;
break;
case CompressionMemberType.NonPrestressedWithSpirals:
ConfinementReinforcementType = ConfinementReinforcementType.Spiral;
break;
case CompressionMemberType.PrestressedWithTies:
ConfinementReinforcementType = ConfinementReinforcementType.Ties;
break;
case CompressionMemberType.PrestressedWithSpirals:
ConfinementReinforcementType = ConfinementReinforcementType.Spiral;
break;
default:
ConfinementReinforcementType = ACI.ConfinementReinforcementType.Ties;
break;
}
}
private ConfinementReinforcementType _ConfinementReinforcementType;
public ConfinementReinforcementType ConfinementReinforcementType
{
get { return _ConfinementReinforcementType;}
set { _ConfinementReinforcementType = value;}
}
private CompressionMemberType compressionMemberType;
public CompressionMemberType CompressionMemberType
{
get { return compressionMemberType; }
set { compressionMemberType = value; }
}
public ConcreteCompressionStrengthResult GetDesignMomentWithCompressionStrength( double phiP_n,
FlexuralCompressionFiberPosition FlexuralCompressionFiberPosition,
bool CapAxialForceAtMaximum = true)
{
this.phiP_n = phiP_n; //store value for iteration
this.FlexuralCompressionFiberPosition = FlexuralCompressionFiberPosition;
double P_o = GetMaximumForce();
StrengthReductionFactorFactory f = new StrengthReductionFactorFactory();
double phiAxial = f.Get_phiFlexureAndAxial(FlexuralFailureModeClassification.CompressionControlled, ConfinementReinforcementType, 0, 0);
double phiP_nMax = phiAxial * P_o;
if (phiP_n > phiP_nMax)
{
if (CapAxialForceAtMaximum == false)
{
throw new Exception("Axial forces exceeds maximum axial force.");
}
else
{
phiP_n = phiP_n;
}
}
//Estimate resistance factor to adjust from phiP_n to P_n
double phiMin = 0.65;
double phiMax = 0.9;
double ConvergenceTolerance = 0.0001;
double targetPhiFactorDifference = 0.0;
//Find P_n by guessing a phi-factor and calculating the result
double phiIterated = RootFinding.Brent(new FunctionOfOneVariable(phiFactorDifferenceCalculation), phiMax, phiMin, ConvergenceTolerance, targetPhiFactorDifference);
double P_nActual = phiP_n / phiIterated;
//Calculate final results using the estimated value of phi
IStrainCompatibilityAnalysisResult nominalResult = this.GetNominalMomentResult(P_nActual, FlexuralCompressionFiberPosition);
ConcreteCompressionStrengthResult result = new ConcreteCompressionStrengthResult(nominalResult, FlexuralCompressionFiberPosition, this.Section.Material.beta1);
FlexuralFailureModeClassification failureMode = f.GetFlexuralFailureMode(result.epsilon_t, result.epsilon_ty);
double phiFinal = f.Get_phiFlexureAndAxial(failureMode, ConfinementReinforcementType, result.epsilon_t, result.epsilon_ty);
double phiM_n = phiFinal * nominalResult.Moment;
result.phiM_n = phiM_n;
result.FlexuralFailureModeClassification = failureMode;
return result;
}
double phiP_n; //stored value for iteration
FlexuralCompressionFiberPosition FlexuralCompressionFiberPosition; //stored value for iteration
private double phiFactorDifferenceCalculation(double phi)
{
double P_nIter = phiP_n / phi;
IStrainCompatibilityAnalysisResult nominalResult = this.GetNominalMomentResult(P_nIter, FlexuralCompressionFiberPosition);
ConcreteCompressionStrengthResult result = new ConcreteCompressionStrengthResult(nominalResult, FlexuralCompressionFiberPosition, this.Section.Material.beta1);
StrengthReductionFactorFactory f = new StrengthReductionFactorFactory();
FlexuralFailureModeClassification failureMode = f.GetFlexuralFailureMode(result.epsilon_t, result.epsilon_ty);
double phiActual = f.Get_phiFlexureAndAxial(failureMode, ConfinementReinforcementType, result.epsilon_t, result.epsilon_ty);
return phi - phiActual;
}
//Table 22.4.2.1
public double GetMaximumForce()
{
double C;
switch (CompressionMemberType)
{
case CompressionMemberType.NonPrestressedWithTies:
C = 0.8;
break;
case CompressionMemberType.NonPrestressedWithSpirals:
C = 0.85;
break;
case CompressionMemberType.PrestressedWithTies:
C = 0.8;
break;
case CompressionMemberType.PrestressedWithSpirals:
C = 0.85;
break;
//case CompressionMemberType.Composite:
// C = 0.85;
// break;
default:
C = 0.8;
break;
}
double P_o = GetP_o();
return C * P_o;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime {
/// <summary>
/// Mutable set class
/// </summary>
[PythonType("set"), DebuggerDisplay("set, {Count} items", TargetTypeName = "set"), DebuggerTypeProxy(typeof(CollectionDebugProxy))]
public class SetCollection : IEnumerable, IEnumerable<object>, ICollection, IStructuralEquatable, ICodeFormattable
#if CLR2
, IValueEquality
#endif
{
internal SetStorage _items;
#region Set Construction
public void __init__() {
clear();
}
public void __init__([NotNull]SetCollection set) {
_items = set._items.Clone();
}
public void __init__([NotNull]FrozenSetCollection set) {
_items = set._items.Clone();
}
public void __init__(object set) {
SetStorage items;
if (SetStorage.GetItems(set, out items)) {
_items = items.Clone();
} else {
_items = items;
}
}
public static object __new__(CodeContext/*!*/ context, PythonType cls) {
if (cls == TypeCache.Set) {
return new SetCollection();
}
return cls.CreateInstance(context);
}
public static object __new__(CodeContext/*!*/ context, PythonType cls, object arg) {
return __new__(context, cls);
}
public static object __new__(CodeContext/*!*/ context, PythonType cls, params object[] args\u00F8) {
return __new__(context, cls);
}
public static object __new__(CodeContext/*!*/ context, PythonType cls, [ParamDictionary]IDictionary<object, object> kwArgs, params object[] args\u00F8) {
return __new__(context, cls);
}
public SetCollection() {
_items = new SetStorage();
}
internal SetCollection(SetStorage items) {
_items = items;
}
private SetCollection Empty {
get {
if (this.GetType() == typeof(SetCollection)) {
return new SetCollection();
}
return Make(DynamicHelpers.GetPythonType(this), new SetStorage());
}
}
internal SetCollection(object[] items) {
_items = new SetStorage(items.Length);
foreach (var o in items) {
_items.AddNoLock(o);
}
}
private SetCollection Make(SetStorage items) {
if (this.GetType() == typeof(SetCollection)) {
return new SetCollection(items);
}
return Make(DynamicHelpers.GetPythonType(this), items);
}
private static SetCollection Make(PythonType/*!*/ cls, SetStorage items) {
if (cls == TypeCache.Set) {
return new SetCollection(items);
}
SetCollection res = PythonCalls.Call(cls) as SetCollection;
Debug.Assert(res != null);
if (items.Count > 0) {
res._items = items;
}
return res;
}
internal static SetCollection Make(PythonType/*!*/ cls, object set) {
SetStorage items;
if (SetStorage.GetItems(set, out items)) {
items = items.Clone();
}
return Make(cls, items);
}
public SetCollection copy() {
return Make(_items.Clone());
}
#endregion
#region Protocol Methods
public int __len__() {
return Count;
}
public bool __contains__(object item) {
if (!SetStorage.GetHashableSetIfSet(ref item)) {
// make sure we have a hashable item
return _items.ContainsAlwaysHash(item);
}
return _items.Contains(item);
}
public PythonTuple __reduce__() {
var type = GetType() != typeof(SetCollection) ? DynamicHelpers.GetPythonType(this) : TypeCache.Set;
return SetStorage.Reduce(_items, type);
}
#endregion
#region IValueEquality Members
#if CLR2
int IValueEquality.GetValueHashCode() {
throw PythonOps.TypeError("set objects are unhashable");
}
bool IValueEquality.ValueEquals(object o) {
return __eq__(o);
}
#endif
#endregion
#region IStructuralEquatable Members
public const object __hash__ = null;
int IStructuralEquatable.GetHashCode(IEqualityComparer/*!*/ comparer) {
if (CompareUtil.Check(this)) {
return 0;
}
int res;
CompareUtil.Push(this);
try {
res = ((IStructuralEquatable)new FrozenSetCollection(_items)).GetHashCode(comparer);
} finally {
CompareUtil.Pop(this);
}
return res;
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer/*!*/ comparer) {
SetStorage items;
return SetStorage.GetItemsIfSet(other, out items) &&
SetStorage.Equals(_items, items, comparer);
}
// default conversion of protocol methods only allows our specific type for equality,
// but sets can do __eq__ / __ne__ against any type. This is why we define a separate
// __eq__ / __ne__ here.
public bool __eq__(object other) {
SetStorage items;
return SetStorage.GetItemsIfSet(other, out items) &&
_items.Count == items.Count &&
_items.IsSubset(items);
}
public bool __ne__(object other) {
SetStorage items;
return !SetStorage.GetItemsIfSet(other, out items) ||
_items.Count != items.Count ||
!_items.IsSubset(items);
}
#endregion
#region Mutating Members
public void add(object item) {
_items.Add(item);
}
public void clear() {
_items.Clear();
}
public void discard(object item) {
SetStorage.GetHashableSetIfSet(ref item);
_items.Remove(item);
}
public object pop() {
object res;
if (_items.Pop(out res)) {
return res;
}
throw PythonOps.KeyError("pop from an empty set");
}
public void remove(object item) {
bool res;
object hashableItem = item;
if (SetStorage.GetHashableSetIfSet(ref hashableItem)) {
res = _items.Remove(hashableItem);
} else {
res = _items.RemoveAlwaysHash(hashableItem);
}
if (!res) {
throw PythonOps.KeyError(item);
}
}
public void update(SetCollection set) {
if (object.ReferenceEquals(set, this)) {
return;
}
lock (_items) {
_items.UnionUpdate(set._items);
}
}
public void update(FrozenSetCollection set) {
lock (_items) {
_items.UnionUpdate(set._items);
}
}
/// <summary>
/// Appends an IEnumerable to an existing set
/// </summary>
public void update(object set) {
if (object.ReferenceEquals(set, this)) {
return;
}
SetStorage items = SetStorage.GetItems(set);
lock (_items) {
_items.UnionUpdate(items);
}
}
public void update([NotNull]params object[]/*!*/ sets) {
Debug.Assert(sets != null);
if (sets.Length == 0) {
return;
}
lock (_items) {
foreach (object set in sets) {
if (object.ReferenceEquals(set, this)) {
continue;
}
_items.UnionUpdate(SetStorage.GetItems(set));
}
}
}
public void intersection_update(SetCollection set) {
if (object.ReferenceEquals(set, this)) {
return;
}
lock (_items) {
_items.IntersectionUpdate(set._items);
}
}
public void intersection_update(FrozenSetCollection set) {
lock (_items) {
_items.IntersectionUpdate(set._items);
}
}
public void intersection_update(object set) {
if (object.ReferenceEquals(set, this)) {
return;
}
SetStorage items = SetStorage.GetItems(set);
lock (_items) {
_items.IntersectionUpdate(items);
}
}
public void intersection_update([NotNull]params object[]/*!*/ sets) {
Debug.Assert(sets != null);
if (sets.Length == 0) {
return;
}
lock (_items) {
foreach (object set in sets) {
if (object.ReferenceEquals(set, this)) {
continue;
}
_items.IntersectionUpdate(SetStorage.GetItems(set));
}
}
}
public void difference_update(SetCollection set) {
if (object.ReferenceEquals(set, this)) {
_items.Clear();
return;
}
lock (_items) {
_items.DifferenceUpdate(set._items);
}
}
public void difference_update(FrozenSetCollection set) {
lock (_items) {
_items.DifferenceUpdate(set._items);
}
}
public void difference_update(object set) {
if (object.ReferenceEquals(set, this)) {
_items.Clear();
return;
}
SetStorage items = SetStorage.GetItems(set);
lock (_items) {
_items.DifferenceUpdate(items);
}
}
public void difference_update([NotNull]params object[]/*!*/ sets) {
Debug.Assert(sets != null);
if (sets.Length == 0) {
return;
}
lock (_items) {
foreach (object set in sets) {
if (object.ReferenceEquals(set, this)) {
_items.ClearNoLock();
return;
}
_items.DifferenceUpdate(SetStorage.GetItems(set));
}
}
}
public void symmetric_difference_update(SetCollection set) {
if (object.ReferenceEquals(set, this)) {
_items.Clear();
return;
}
lock (_items) {
_items.SymmetricDifferenceUpdate(set._items);
}
}
public void symmetric_difference_update(FrozenSetCollection set) {
lock (_items) {
_items.SymmetricDifferenceUpdate(set._items);
}
}
public void symmetric_difference_update(object set) {
if (object.ReferenceEquals(set, this)) {
_items.Clear();
return;
}
SetStorage items = SetStorage.GetItems(set);
lock (_items) {
_items.SymmetricDifferenceUpdate(items);
}
}
#endregion
#region Generated NonOperator Operations (SetCollection)
// *** BEGIN GENERATED CODE ***
// generated by function: _gen_setops from: generate_set.py
public bool isdisjoint(SetCollection set) {
return _items.IsDisjoint(set._items);
}
public bool isdisjoint(FrozenSetCollection set) {
return _items.IsDisjoint(set._items);
}
public bool isdisjoint(object set) {
return _items.IsDisjoint(SetStorage.GetItems(set));
}
public bool issubset(SetCollection set) {
return _items.IsSubset(set._items);
}
public bool issubset(FrozenSetCollection set) {
return _items.IsSubset(set._items);
}
public bool issubset(object set) {
return _items.IsSubset(SetStorage.GetItems(set));
}
public bool issuperset(SetCollection set) {
return set._items.IsSubset(_items);
}
public bool issuperset(FrozenSetCollection set) {
return set._items.IsSubset(_items);
}
public bool issuperset(object set) {
return SetStorage.GetItems(set).IsSubset(_items);
}
public SetCollection union() {
return copy();
}
public SetCollection union(SetCollection set) {
return Make(SetStorage.Union(_items, set._items));
}
public SetCollection union(FrozenSetCollection set) {
return Make(SetStorage.Union(_items, set._items));
}
public SetCollection union(object set) {
SetStorage items;
if (SetStorage.GetItems(set, out items)) {
items = SetStorage.Union(_items, items);
} else {
items.UnionUpdate(_items);
}
return Make(items);
}
public SetCollection union([NotNull]params object[]/*!*/ sets) {
Debug.Assert(sets != null);
SetStorage res = _items.Clone();
foreach (object set in sets) {
res.UnionUpdate(SetStorage.GetItems(set));
}
return Make(res);
}
public SetCollection intersection() {
return copy();
}
public SetCollection intersection(SetCollection set) {
return Make(SetStorage.Intersection(_items, set._items));
}
public SetCollection intersection(FrozenSetCollection set) {
return Make(SetStorage.Intersection(_items, set._items));
}
public SetCollection intersection(object set) {
SetStorage items;
if (SetStorage.GetItems(set, out items)) {
items = SetStorage.Intersection(_items, items);
} else {
items.IntersectionUpdate(_items);
}
return Make(items);
}
public SetCollection intersection([NotNull]params object[]/*!*/ sets) {
Debug.Assert(sets != null);
if (sets.Length == 0) {
return copy();
}
SetStorage res = _items;
foreach (object set in sets) {
SetStorage items, x = res, y;
if (SetStorage.GetItems(set, out items)) {
y = items;
SetStorage.SortBySize(ref x, ref y);
if (object.ReferenceEquals(x, items) || object.ReferenceEquals(x, _items)) {
x = x.Clone();
}
} else {
y = items;
SetStorage.SortBySize(ref x, ref y);
if (object.ReferenceEquals(x, _items)) {
x = x.Clone();
}
}
x.IntersectionUpdate(y);
res = x;
}
Debug.Assert(!object.ReferenceEquals(res, _items));
return Make(res);
}
public SetCollection difference() {
return copy();
}
public SetCollection difference(SetCollection set) {
if (object.ReferenceEquals(set, this)) {
return Empty;
}
return Make(
SetStorage.Difference(_items, set._items)
);
}
public SetCollection difference(FrozenSetCollection set) {
return Make(
SetStorage.Difference(_items, set._items)
);
}
public SetCollection difference(object set) {
return Make(
SetStorage.Difference(_items, SetStorage.GetItems(set))
);
}
public SetCollection difference([NotNull]params object[]/*!*/ sets) {
Debug.Assert(sets != null);
if (sets.Length == 0) {
return copy();
}
SetStorage res = _items;
foreach (object set in sets) {
if (object.ReferenceEquals(set, this)) {
return Empty;
}
SetStorage items = SetStorage.GetItems(set);
if (object.ReferenceEquals(res, _items)) {
res = SetStorage.Difference(_items, items);
} else {
res.DifferenceUpdate(items);
}
}
Debug.Assert(!object.ReferenceEquals(res, _items));
return Make(res);
}
public SetCollection symmetric_difference(SetCollection set) {
if (object.ReferenceEquals(set, this)) {
return Empty;
}
return Make(SetStorage.SymmetricDifference(_items, set._items));
}
public SetCollection symmetric_difference(FrozenSetCollection set) {
return Make(SetStorage.SymmetricDifference(_items, set._items));
}
public SetCollection symmetric_difference(object set) {
SetStorage items;
if (SetStorage.GetItems(set, out items)) {
items = SetStorage.SymmetricDifference(_items, items);
} else {
items.SymmetricDifferenceUpdate(_items);
}
return Make(items);
}
// *** END GENERATED CODE ***
#endregion
#region Generated Mutating Operators
// *** BEGIN GENERATED CODE ***
// generated by function: gen_mutating_ops from: generate_set.py
[SpecialName]
public SetCollection InPlaceBitwiseOr(SetCollection set) {
update(set);
return this;
}
[SpecialName]
public SetCollection InPlaceBitwiseOr(FrozenSetCollection set) {
update(set);
return this;
}
[SpecialName]
public SetCollection InPlaceBitwiseOr(object set) {
if (set is FrozenSetCollection || set is SetCollection) {
update(set);
return this;
}
throw PythonOps.TypeError(
"unsupported operand type(s) for |=: '{0}' and '{1}'",
PythonTypeOps.GetName(this), PythonTypeOps.GetName(set)
);
}
[SpecialName]
public SetCollection InPlaceBitwiseAnd(SetCollection set) {
intersection_update(set);
return this;
}
[SpecialName]
public SetCollection InPlaceBitwiseAnd(FrozenSetCollection set) {
intersection_update(set);
return this;
}
[SpecialName]
public SetCollection InPlaceBitwiseAnd(object set) {
if (set is FrozenSetCollection || set is SetCollection) {
intersection_update(set);
return this;
}
throw PythonOps.TypeError(
"unsupported operand type(s) for &=: '{0}' and '{1}'",
PythonTypeOps.GetName(this), PythonTypeOps.GetName(set)
);
}
[SpecialName]
public SetCollection InPlaceExclusiveOr(SetCollection set) {
symmetric_difference_update(set);
return this;
}
[SpecialName]
public SetCollection InPlaceExclusiveOr(FrozenSetCollection set) {
symmetric_difference_update(set);
return this;
}
[SpecialName]
public SetCollection InPlaceExclusiveOr(object set) {
if (set is FrozenSetCollection || set is SetCollection) {
symmetric_difference_update(set);
return this;
}
throw PythonOps.TypeError(
"unsupported operand type(s) for ^=: '{0}' and '{1}'",
PythonTypeOps.GetName(this), PythonTypeOps.GetName(set)
);
}
[SpecialName]
public SetCollection InPlaceSubtract(SetCollection set) {
difference_update(set);
return this;
}
[SpecialName]
public SetCollection InPlaceSubtract(FrozenSetCollection set) {
difference_update(set);
return this;
}
[SpecialName]
public SetCollection InPlaceSubtract(object set) {
if (set is FrozenSetCollection || set is SetCollection) {
difference_update(set);
return this;
}
throw PythonOps.TypeError(
"unsupported operand type(s) for -=: '{0}' and '{1}'",
PythonTypeOps.GetName(this), PythonTypeOps.GetName(set)
);
}
// *** END GENERATED CODE ***
#endregion
#region Generated Operators (SetCollection)
// *** BEGIN GENERATED CODE ***
// generated by function: _gen_ops from: generate_set.py
public static SetCollection operator |(SetCollection x, SetCollection y) {
return x.union(y);
}
public static SetCollection operator &(SetCollection x, SetCollection y) {
return x.intersection(y);
}
public static SetCollection operator ^(SetCollection x, SetCollection y) {
return x.symmetric_difference(y);
}
public static SetCollection operator -(SetCollection x, SetCollection y) {
return x.difference(y);
}
public static SetCollection operator |(SetCollection x, FrozenSetCollection y) {
return x.union(y);
}
public static SetCollection operator &(SetCollection x, FrozenSetCollection y) {
return x.intersection(y);
}
public static SetCollection operator ^(SetCollection x, FrozenSetCollection y) {
return x.symmetric_difference(y);
}
public static SetCollection operator -(SetCollection x, FrozenSetCollection y) {
return x.difference(y);
}
// *** END GENERATED CODE ***
#endregion
#region Generated Interface Implementations (SetCollection)
// *** BEGIN GENERATED CODE ***
// generated by function: _gen_interfaces from: generate_set.py
#region IRichComparable
public static bool operator >(SetCollection self, object other) {
SetStorage items;
if (SetStorage.GetItemsIfSet(other, out items)) {
return items.IsStrictSubset(self._items);
}
throw PythonOps.TypeError("can only compare to a set");
}
public static bool operator <(SetCollection self, object other) {
SetStorage items;
if (SetStorage.GetItemsIfSet(other, out items)) {
return self._items.IsStrictSubset(items);
}
throw PythonOps.TypeError("can only compare to a set");
}
public static bool operator >=(SetCollection self, object other) {
SetStorage items;
if (SetStorage.GetItemsIfSet(other, out items)) {
return items.IsSubset(self._items);
}
throw PythonOps.TypeError("can only compare to a set");
}
public static bool operator <=(SetCollection self, object other) {
SetStorage items;
if (SetStorage.GetItemsIfSet(other, out items)) {
return self._items.IsSubset(items);
}
throw PythonOps.TypeError("can only compare to a set");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic") ,System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "o")]
[SpecialName]
public int Compare(object o) {
throw PythonOps.TypeError("cannot compare sets using cmp()");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic") ,System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "o")]
public int __cmp__(object o) {
throw PythonOps.TypeError("cannot compare sets using cmp()");
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
return new SetIterator(_items, true);
}
#endregion
#region IEnumerable<object> Members
IEnumerator<object> IEnumerable<object>.GetEnumerator() {
return new SetIterator(_items, true);
}
#endregion
#region ICodeFormattable Members
public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
return SetStorage.SetToString(context, this, _items);
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index) {
int i = 0;
foreach (object o in this) {
array.SetValue(o, index + i++);
}
}
public int Count {
[PythonHidden]
get { return _items.Count; }
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return this; }
}
#endregion
// *** END GENERATED CODE ***
#endregion
}
/// <summary>
/// Immutable set class
/// </summary>
[PythonType("frozenset"), DebuggerDisplay("frozenset, {Count} items", TargetTypeName = "frozenset"), DebuggerTypeProxy(typeof(CollectionDebugProxy))]
public class FrozenSetCollection : IEnumerable, IEnumerable<object>, ICollection, IStructuralEquatable, ICodeFormattable
#if CLR2
, IValueEquality
#endif
{
internal SetStorage _items;
private HashCache _hashCache;
private static readonly FrozenSetCollection _empty = new FrozenSetCollection();
#region Set Construction
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "o")]
public void __init__(params object[] o) {
// nop
}
public static FrozenSetCollection __new__(CodeContext/*!*/ context, object cls) {
if (cls == TypeCache.FrozenSet) {
return _empty;
} else {
object res = ((PythonType)cls).CreateInstance(context);
FrozenSetCollection fs = res as FrozenSetCollection;
if (fs == null) {
throw PythonOps.TypeError("{0} is not a subclass of frozenset", res);
}
return fs;
}
}
public static FrozenSetCollection __new__(CodeContext/*!*/ context, object cls, object set) {
if (cls == TypeCache.FrozenSet) {
return Make(TypeCache.FrozenSet, set);
} else {
object res = ((PythonType)cls).CreateInstance(context, set);
FrozenSetCollection fs = res as FrozenSetCollection;
if (fs == null) {
throw PythonOps.TypeError("{0} is not a subclass of frozenset", res);
}
return fs;
}
}
public FrozenSetCollection() : this(new SetStorage()) { }
internal FrozenSetCollection(SetStorage set) {
_items = set;
}
protected internal FrozenSetCollection(object set) : this(SetStorage.GetFrozenItems(set)) { }
private FrozenSetCollection Empty {
get {
if (this.GetType() == typeof(FrozenSetCollection)) {
return _empty;
}
return Make(DynamicHelpers.GetPythonType(this), new SetStorage());
}
}
private FrozenSetCollection Make(SetStorage items) {
if (items.Count == 0) {
return Empty;
}
if (this.GetType() == typeof(FrozenSetCollection)) {
return new FrozenSetCollection(items);
}
return Make(DynamicHelpers.GetPythonType(this), items);
}
private static FrozenSetCollection Make(PythonType/*!*/ cls, SetStorage items) {
if (cls == TypeCache.FrozenSet) {
if (items.Count == 0) {
return _empty;
}
return new FrozenSetCollection(items);
}
FrozenSetCollection res = PythonCalls.Call(cls) as FrozenSetCollection;
Debug.Assert(res != null);
if (items.Count > 0) {
res._items = items;
}
return res;
}
internal static FrozenSetCollection Make(PythonType/*!*/ cls, object set) {
FrozenSetCollection fs = set as FrozenSetCollection;
if (fs != null && cls == TypeCache.FrozenSet) {
// constructing frozen set from frozen set, we return the original
return fs;
}
return Make(cls, SetStorage.GetFrozenItems(set));
}
public FrozenSetCollection copy() {
// Python behavior: If we're a non-derived frozen set, set return the original
// frozen set. If we're derived from a frozen set, we make a new set of this type
// which contains the same elements.
if (this.GetType() == typeof(FrozenSetCollection)) {
return this;
}
// subclass
return Make(DynamicHelpers.GetPythonType(this), _items);
}
#endregion
#region Protocol Methods
public int __len__() {
return Count;
}
public bool __contains__(object item) {
if (!SetStorage.GetHashableSetIfSet(ref item)) {
// make sure we have a hashable item
return _items.ContainsAlwaysHash(item);
}
return _items.Contains(item);
}
public PythonTuple __reduce__() {
var type = GetType() != typeof(FrozenSetCollection) ? DynamicHelpers.GetPythonType(this) : TypeCache.FrozenSet;
return SetStorage.Reduce(_items, type);
}
#endregion
#region IValueEquality Members
#if CLR2
int IValueEquality.GetValueHashCode() {
return CalculateHashCode(DefaultContext.DefaultPythonContext.EqualityComparerNonGeneric);
}
bool IValueEquality.ValueEquals(object o) {
return __eq__(o);
}
#endif
#endregion
#region IStructuralEquatable Members
private sealed class HashCache {
internal readonly int HashCode;
internal readonly IEqualityComparer Comparer;
internal HashCache(int hashCode, IEqualityComparer comparer) {
HashCode = hashCode;
Comparer = comparer;
}
}
private int CalculateHashCode(IEqualityComparer/*!*/ comparer) {
Assert.NotNull(comparer);
HashCache curHashCache = _hashCache;
if (curHashCache != null && object.ReferenceEquals(comparer, curHashCache.Comparer)) {
return curHashCache.HashCode;
}
int hash = SetStorage.GetHashCode(_items, comparer);
_hashCache = new HashCache(hash, comparer);
return hash;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer/*!*/ comparer) {
return CalculateHashCode(comparer);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
SetStorage items;
return SetStorage.GetItemsIfSet(other, out items) &&
SetStorage.Equals(_items, items, comparer);
}
// default conversion of protocol methods only allows our specific type for equality,
// but sets can do __eq__ / __ne__ against any type. This is why we define a separate
// __eq__ / __ne__ here.
public bool __eq__(object other) {
SetStorage items;
return SetStorage.GetItemsIfSet(other, out items) &&
_items.Count == items.Count &&
_items.IsSubset(items);
}
public bool __ne__(object other) {
SetStorage items;
return !SetStorage.GetItemsIfSet(other, out items) ||
_items.Count != items.Count ||
!_items.IsSubset(items);
}
#endregion
#region Generated NonOperator Operations (FrozenSetCollection)
// *** BEGIN GENERATED CODE ***
// generated by function: _gen_setops from: generate_set.py
public bool isdisjoint(FrozenSetCollection set) {
return _items.IsDisjoint(set._items);
}
public bool isdisjoint(SetCollection set) {
return _items.IsDisjoint(set._items);
}
public bool isdisjoint(object set) {
return _items.IsDisjoint(SetStorage.GetItems(set));
}
public bool issubset(FrozenSetCollection set) {
return _items.IsSubset(set._items);
}
public bool issubset(SetCollection set) {
return _items.IsSubset(set._items);
}
public bool issubset(object set) {
return _items.IsSubset(SetStorage.GetItems(set));
}
public bool issuperset(FrozenSetCollection set) {
return set._items.IsSubset(_items);
}
public bool issuperset(SetCollection set) {
return set._items.IsSubset(_items);
}
public bool issuperset(object set) {
return SetStorage.GetItems(set).IsSubset(_items);
}
public FrozenSetCollection union() {
return Make(_items);
}
public FrozenSetCollection union(FrozenSetCollection set) {
return Make(SetStorage.Union(_items, set._items));
}
public FrozenSetCollection union(SetCollection set) {
return Make(SetStorage.Union(_items, set._items));
}
public FrozenSetCollection union(object set) {
SetStorage items;
if (SetStorage.GetItems(set, out items)) {
items = SetStorage.Union(_items, items);
} else {
items.UnionUpdate(_items);
}
return Make(items);
}
public FrozenSetCollection union([NotNull]params object[]/*!*/ sets) {
Debug.Assert(sets != null);
SetStorage res = _items.Clone();
foreach (object set in sets) {
res.UnionUpdate(SetStorage.GetItems(set));
}
return Make(res);
}
public FrozenSetCollection intersection() {
return Make(_items);
}
public FrozenSetCollection intersection(FrozenSetCollection set) {
return Make(SetStorage.Intersection(_items, set._items));
}
public FrozenSetCollection intersection(SetCollection set) {
return Make(SetStorage.Intersection(_items, set._items));
}
public FrozenSetCollection intersection(object set) {
SetStorage items;
if (SetStorage.GetItems(set, out items)) {
items = SetStorage.Intersection(_items, items);
} else {
items.IntersectionUpdate(_items);
}
return Make(items);
}
public FrozenSetCollection intersection([NotNull]params object[]/*!*/ sets) {
Debug.Assert(sets != null);
if (sets.Length == 0) {
return Make(_items);
}
SetStorage res = _items;
foreach (object set in sets) {
SetStorage items, x = res, y;
if (SetStorage.GetItems(set, out items)) {
y = items;
SetStorage.SortBySize(ref x, ref y);
if (object.ReferenceEquals(x, items) || object.ReferenceEquals(x, _items)) {
x = x.Clone();
}
} else {
y = items;
SetStorage.SortBySize(ref x, ref y);
if (object.ReferenceEquals(x, _items)) {
x = x.Clone();
}
}
x.IntersectionUpdate(y);
res = x;
}
Debug.Assert(!object.ReferenceEquals(res, _items));
return Make(res);
}
public FrozenSetCollection difference() {
return Make(_items);
}
public FrozenSetCollection difference(FrozenSetCollection set) {
if (object.ReferenceEquals(set, this)) {
return Empty;
}
return Make(
SetStorage.Difference(_items, set._items)
);
}
public FrozenSetCollection difference(SetCollection set) {
return Make(
SetStorage.Difference(_items, set._items)
);
}
public FrozenSetCollection difference(object set) {
return Make(
SetStorage.Difference(_items, SetStorage.GetItems(set))
);
}
public FrozenSetCollection difference([NotNull]params object[]/*!*/ sets) {
Debug.Assert(sets != null);
if (sets.Length == 0) {
return Make(_items);
}
SetStorage res = _items;
foreach (object set in sets) {
if (object.ReferenceEquals(set, this)) {
return Empty;
}
SetStorage items = SetStorage.GetItems(set);
if (object.ReferenceEquals(res, _items)) {
res = SetStorage.Difference(_items, items);
} else {
res.DifferenceUpdate(items);
}
}
Debug.Assert(!object.ReferenceEquals(res, _items));
return Make(res);
}
public FrozenSetCollection symmetric_difference(FrozenSetCollection set) {
if (object.ReferenceEquals(set, this)) {
return Empty;
}
return Make(SetStorage.SymmetricDifference(_items, set._items));
}
public FrozenSetCollection symmetric_difference(SetCollection set) {
return Make(SetStorage.SymmetricDifference(_items, set._items));
}
public FrozenSetCollection symmetric_difference(object set) {
SetStorage items;
if (SetStorage.GetItems(set, out items)) {
items = SetStorage.SymmetricDifference(_items, items);
} else {
items.SymmetricDifferenceUpdate(_items);
}
return Make(items);
}
// *** END GENERATED CODE ***
#endregion
#region Generated Operators (FrozenSetCollection)
// *** BEGIN GENERATED CODE ***
// generated by function: _gen_ops from: generate_set.py
public static FrozenSetCollection operator |(FrozenSetCollection x, FrozenSetCollection y) {
return x.union(y);
}
public static FrozenSetCollection operator &(FrozenSetCollection x, FrozenSetCollection y) {
return x.intersection(y);
}
public static FrozenSetCollection operator ^(FrozenSetCollection x, FrozenSetCollection y) {
return x.symmetric_difference(y);
}
public static FrozenSetCollection operator -(FrozenSetCollection x, FrozenSetCollection y) {
return x.difference(y);
}
public static FrozenSetCollection operator |(FrozenSetCollection x, SetCollection y) {
return x.union(y);
}
public static FrozenSetCollection operator &(FrozenSetCollection x, SetCollection y) {
return x.intersection(y);
}
public static FrozenSetCollection operator ^(FrozenSetCollection x, SetCollection y) {
return x.symmetric_difference(y);
}
public static FrozenSetCollection operator -(FrozenSetCollection x, SetCollection y) {
return x.difference(y);
}
// *** END GENERATED CODE ***
#endregion
#region Generated Interface Implementations (FrozenSetCollection)
// *** BEGIN GENERATED CODE ***
// generated by function: _gen_interfaces from: generate_set.py
#region IRichComparable
public static bool operator >(FrozenSetCollection self, object other) {
SetStorage items;
if (SetStorage.GetItemsIfSet(other, out items)) {
return items.IsStrictSubset(self._items);
}
throw PythonOps.TypeError("can only compare to a set");
}
public static bool operator <(FrozenSetCollection self, object other) {
SetStorage items;
if (SetStorage.GetItemsIfSet(other, out items)) {
return self._items.IsStrictSubset(items);
}
throw PythonOps.TypeError("can only compare to a set");
}
public static bool operator >=(FrozenSetCollection self, object other) {
SetStorage items;
if (SetStorage.GetItemsIfSet(other, out items)) {
return items.IsSubset(self._items);
}
throw PythonOps.TypeError("can only compare to a set");
}
public static bool operator <=(FrozenSetCollection self, object other) {
SetStorage items;
if (SetStorage.GetItemsIfSet(other, out items)) {
return self._items.IsSubset(items);
}
throw PythonOps.TypeError("can only compare to a set");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic") ,System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "o")]
[SpecialName]
public int Compare(object o) {
throw PythonOps.TypeError("cannot compare sets using cmp()");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic") ,System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "o")]
public int __cmp__(object o) {
throw PythonOps.TypeError("cannot compare sets using cmp()");
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
return new SetIterator(_items, false);
}
#endregion
#region IEnumerable<object> Members
IEnumerator<object> IEnumerable<object>.GetEnumerator() {
return new SetIterator(_items, false);
}
#endregion
#region ICodeFormattable Members
public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
return SetStorage.SetToString(context, this, _items);
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index) {
int i = 0;
foreach (object o in this) {
array.SetValue(o, index + i++);
}
}
public int Count {
[PythonHidden]
get { return _items.Count; }
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return this; }
}
#endregion
// *** END GENERATED CODE ***
#endregion
}
/// <summary>
/// Iterator over sets
/// </summary>
[PythonType("setiterator")]
public sealed class SetIterator : IEnumerable, IEnumerable<object>, IEnumerator, IEnumerator<object> {
private readonly SetStorage _items;
private readonly int _version;
private readonly int _maxIndex;
private int _index = -2;
internal SetIterator(SetStorage items, bool mutable) {
_items = items;
if (mutable) {
lock (items) {
_version = items.Version;
_maxIndex = items._count > 0 ? items._buckets.Length : 0;
}
} else {
_version = items.Version;
_maxIndex = items._count > 0 ? items._buckets.Length : 0;
}
}
#region IDisposable Members
[PythonHidden]
public void Dispose() { }
#endregion
#region IEnumerator Members
public object Current {
[PythonHidden]
get {
if (_index < 0) {
return null;
}
object res = _items._buckets[_index].Item;
if (_items.Version != _version) {
throw PythonOps.RuntimeError("set changed during iteration");
}
return res;
}
}
[PythonHidden]
public bool MoveNext() {
if (_index == _maxIndex) {
return false;
}
_index++;
if (_index < 0) {
if (_items._hasNull) {
return true;
} else {
_index++;
}
}
if (_maxIndex > 0) {
SetStorage.Bucket[] buckets = _items._buckets;
for (; _index < buckets.Length; _index++) {
object item = buckets[_index].Item;
if (item != null && item != SetStorage.Removed) {
return true;
}
}
}
return false;
}
[PythonHidden]
public void Reset() {
_index = -2;
}
#endregion
#region IEnumerable Members
[PythonHidden]
public IEnumerator GetEnumerator() {
return this;
}
#endregion
#region IEnumerable<object> Members
IEnumerator<object> IEnumerable<object>.GetEnumerator() {
return this;
}
#endregion
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A long-running asynchronous task
/// First published in XenServer 4.0.
/// </summary>
public partial class Task : XenObject<Task>
{
#region Constructors
public Task()
{
}
public Task(string uuid,
string name_label,
string name_description,
List<task_allowed_operations> allowed_operations,
Dictionary<string, task_allowed_operations> current_operations,
DateTime created,
DateTime finished,
task_status_type status,
XenRef<Host> resident_on,
double progress,
string type,
string result,
string[] error_info,
Dictionary<string, string> other_config,
XenRef<Task> subtask_of,
List<XenRef<Task>> subtasks,
string backtrace)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.created = created;
this.finished = finished;
this.status = status;
this.resident_on = resident_on;
this.progress = progress;
this.type = type;
this.result = result;
this.error_info = error_info;
this.other_config = other_config;
this.subtask_of = subtask_of;
this.subtasks = subtasks;
this.backtrace = backtrace;
}
/// <summary>
/// Creates a new Task from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Task(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Task from a Proxy_Task.
/// </summary>
/// <param name="proxy"></param>
public Task(Proxy_Task proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Task.
/// </summary>
public override void UpdateFrom(Task update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
created = update.created;
finished = update.finished;
status = update.status;
resident_on = update.resident_on;
progress = update.progress;
type = update.type;
result = update.result;
error_info = update.error_info;
other_config = update.other_config;
subtask_of = update.subtask_of;
subtasks = update.subtasks;
backtrace = update.backtrace;
}
internal void UpdateFrom(Proxy_Task proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<task_allowed_operations>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_task_allowed_operations(proxy.current_operations);
created = proxy.created;
finished = proxy.finished;
status = proxy.status == null ? (task_status_type) 0 : (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), (string)proxy.status);
resident_on = proxy.resident_on == null ? null : XenRef<Host>.Create(proxy.resident_on);
progress = Convert.ToDouble(proxy.progress);
type = proxy.type == null ? null : proxy.type;
result = proxy.result == null ? null : proxy.result;
error_info = proxy.error_info == null ? new string[] {} : (string [])proxy.error_info;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
subtask_of = proxy.subtask_of == null ? null : XenRef<Task>.Create(proxy.subtask_of);
subtasks = proxy.subtasks == null ? null : XenRef<Task>.Create(proxy.subtasks);
backtrace = proxy.backtrace == null ? null : proxy.backtrace;
}
public Proxy_Task ToProxy()
{
Proxy_Task result_ = new Proxy_Task();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.allowed_operations = allowed_operations == null ? new string[] {} : Helper.ObjectListToStringArray(allowed_operations);
result_.current_operations = Maps.convert_to_proxy_string_task_allowed_operations(current_operations);
result_.created = created;
result_.finished = finished;
result_.status = task_status_type_helper.ToString(status);
result_.resident_on = resident_on ?? "";
result_.progress = progress;
result_.type = type ?? "";
result_.result = result ?? "";
result_.error_info = error_info;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.subtask_of = subtask_of ?? "";
result_.subtasks = subtasks == null ? new string[] {} : Helper.RefListToStringArray(subtasks);
result_.backtrace = backtrace ?? "";
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Task
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("allowed_operations"))
allowed_operations = Helper.StringArrayToEnumList<task_allowed_operations>(Marshalling.ParseStringArray(table, "allowed_operations"));
if (table.ContainsKey("current_operations"))
current_operations = Maps.convert_from_proxy_string_task_allowed_operations(Marshalling.ParseHashTable(table, "current_operations"));
if (table.ContainsKey("created"))
created = Marshalling.ParseDateTime(table, "created");
if (table.ContainsKey("finished"))
finished = Marshalling.ParseDateTime(table, "finished");
if (table.ContainsKey("status"))
status = (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), Marshalling.ParseString(table, "status"));
if (table.ContainsKey("resident_on"))
resident_on = Marshalling.ParseRef<Host>(table, "resident_on");
if (table.ContainsKey("progress"))
progress = Marshalling.ParseDouble(table, "progress");
if (table.ContainsKey("type"))
type = Marshalling.ParseString(table, "type");
if (table.ContainsKey("result"))
result = Marshalling.ParseString(table, "result");
if (table.ContainsKey("error_info"))
error_info = Marshalling.ParseStringArray(table, "error_info");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("subtask_of"))
subtask_of = Marshalling.ParseRef<Task>(table, "subtask_of");
if (table.ContainsKey("subtasks"))
subtasks = Marshalling.ParseSetRef<Task>(table, "subtasks");
if (table.ContainsKey("backtrace"))
backtrace = Marshalling.ParseString(table, "backtrace");
}
public bool DeepEquals(Task other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._created, other._created) &&
Helper.AreEqual2(this._finished, other._finished) &&
Helper.AreEqual2(this._status, other._status) &&
Helper.AreEqual2(this._resident_on, other._resident_on) &&
Helper.AreEqual2(this._progress, other._progress) &&
Helper.AreEqual2(this._type, other._type) &&
Helper.AreEqual2(this._result, other._result) &&
Helper.AreEqual2(this._error_info, other._error_info) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._subtask_of, other._subtask_of) &&
Helper.AreEqual2(this._subtasks, other._subtasks) &&
Helper.AreEqual2(this._backtrace, other._backtrace);
}
internal static List<Task> ProxyArrayToObjectList(Proxy_Task[] input)
{
var result = new List<Task>();
foreach (var item in input)
result.Add(new Task(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Task server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Task.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static Task get_record(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_record(session.opaque_ref, _task);
else
return new Task(session.XmlRpcProxy.task_get_record(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get a reference to the task instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Task> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Task>.Create(session.XmlRpcProxy.task_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the task instances with the given label.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Task>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Task>.Create(session.XmlRpcProxy.task_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_uuid(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_uuid(session.opaque_ref, _task);
else
return session.XmlRpcProxy.task_get_uuid(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_name_label(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_name_label(session.opaque_ref, _task);
else
return session.XmlRpcProxy.task_get_name_label(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_name_description(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_name_description(session.opaque_ref, _task);
else
return session.XmlRpcProxy.task_get_name_description(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static List<task_allowed_operations> get_allowed_operations(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_allowed_operations(session.opaque_ref, _task);
else
return Helper.StringArrayToEnumList<task_allowed_operations>(session.XmlRpcProxy.task_get_allowed_operations(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the current_operations field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static Dictionary<string, task_allowed_operations> get_current_operations(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_current_operations(session.opaque_ref, _task);
else
return Maps.convert_from_proxy_string_task_allowed_operations(session.XmlRpcProxy.task_get_current_operations(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the created field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static DateTime get_created(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_created(session.opaque_ref, _task);
else
return session.XmlRpcProxy.task_get_created(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the finished field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static DateTime get_finished(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_finished(session.opaque_ref, _task);
else
return session.XmlRpcProxy.task_get_finished(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the status field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static task_status_type get_status(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_status(session.opaque_ref, _task);
else
return (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), (string)session.XmlRpcProxy.task_get_status(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the resident_on field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static XenRef<Host> get_resident_on(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_resident_on(session.opaque_ref, _task);
else
return XenRef<Host>.Create(session.XmlRpcProxy.task_get_resident_on(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the progress field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static double get_progress(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_progress(session.opaque_ref, _task);
else
return Convert.ToDouble(session.XmlRpcProxy.task_get_progress(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the type field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_type(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_type(session.opaque_ref, _task);
else
return session.XmlRpcProxy.task_get_type(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the result field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_result(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_result(session.opaque_ref, _task);
else
return session.XmlRpcProxy.task_get_result(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the error_info field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string[] get_error_info(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_error_info(session.opaque_ref, _task);
else
return (string [])session.XmlRpcProxy.task_get_error_info(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given task.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static Dictionary<string, string> get_other_config(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_other_config(session.opaque_ref, _task);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.task_get_other_config(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the subtask_of field of the given task.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static XenRef<Task> get_subtask_of(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_subtask_of(session.opaque_ref, _task);
else
return XenRef<Task>.Create(session.XmlRpcProxy.task_get_subtask_of(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the subtasks field of the given task.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static List<XenRef<Task>> get_subtasks(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_subtasks(session.opaque_ref, _task);
else
return XenRef<Task>.Create(session.XmlRpcProxy.task_get_subtasks(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the backtrace field of the given task.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_backtrace(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_backtrace(session.opaque_ref, _task);
else
return session.XmlRpcProxy.task_get_backtrace(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given task.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _task, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_set_other_config(session.opaque_ref, _task, _other_config);
else
session.XmlRpcProxy.task_set_other_config(session.opaque_ref, _task ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given task.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _task, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_add_to_other_config(session.opaque_ref, _task, _key, _value);
else
session.XmlRpcProxy.task_add_to_other_config(session.opaque_ref, _task ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given task. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _task, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_remove_from_other_config(session.opaque_ref, _task, _key);
else
session.XmlRpcProxy.task_remove_from_other_config(session.opaque_ref, _task ?? "", _key ?? "").parse();
}
/// <summary>
/// Create a new task object which must be manually destroyed.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">short label for the new task</param>
/// <param name="_description">longer description for the new task</param>
public static XenRef<Task> create(Session session, string _label, string _description)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_create(session.opaque_ref, _label, _description);
else
return XenRef<Task>.Create(session.XmlRpcProxy.task_create(session.opaque_ref, _label ?? "", _description ?? "").parse());
}
/// <summary>
/// Destroy the task object
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static void destroy(Session session, string _task)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_destroy(session.opaque_ref, _task);
else
session.XmlRpcProxy.task_destroy(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Request that a task be cancelled. Note that a task may fail to be cancelled and may complete or fail normally and note that, even when a task does cancel, it might take an arbitrary amount of time.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static void cancel(Session session, string _task)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_cancel(session.opaque_ref, _task);
else
session.XmlRpcProxy.task_cancel(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Request that a task be cancelled. Note that a task may fail to be cancelled and may complete or fail normally and note that, even when a task does cancel, it might take an arbitrary amount of time.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static XenRef<Task> async_cancel(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_task_cancel(session.opaque_ref, _task);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_task_cancel(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Set the task status
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
/// <param name="_value">task status value to be set</param>
public static void set_status(Session session, string _task, task_status_type _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_set_status(session.opaque_ref, _task, _value);
else
session.XmlRpcProxy.task_set_status(session.opaque_ref, _task ?? "", task_status_type_helper.ToString(_value)).parse();
}
/// <summary>
/// Return a list of all the tasks known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Task>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_all(session.opaque_ref);
else
return XenRef<Task>.Create(session.XmlRpcProxy.task_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the task Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Task>, Task> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_all_records(session.opaque_ref);
else
return XenRef<Task>.Create<Proxy_Task>(session.XmlRpcProxy.task_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<task_allowed_operations> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<task_allowed_operations> _allowed_operations = new List<task_allowed_operations>() {};
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, task_allowed_operations> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, task_allowed_operations> _current_operations = new Dictionary<string, task_allowed_operations>() {};
/// <summary>
/// Time task was created
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime created
{
get { return _created; }
set
{
if (!Helper.AreEqual(value, _created))
{
_created = value;
NotifyPropertyChanged("created");
}
}
}
private DateTime _created;
/// <summary>
/// Time task finished (i.e. succeeded or failed). If task-status is pending, then the value of this field has no meaning
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime finished
{
get { return _finished; }
set
{
if (!Helper.AreEqual(value, _finished))
{
_finished = value;
NotifyPropertyChanged("finished");
}
}
}
private DateTime _finished;
/// <summary>
/// current status of the task
/// </summary>
[JsonConverter(typeof(task_status_typeConverter))]
public virtual task_status_type status
{
get { return _status; }
set
{
if (!Helper.AreEqual(value, _status))
{
_status = value;
NotifyPropertyChanged("status");
}
}
}
private task_status_type _status;
/// <summary>
/// the host on which the task is running
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> resident_on
{
get { return _resident_on; }
set
{
if (!Helper.AreEqual(value, _resident_on))
{
_resident_on = value;
NotifyPropertyChanged("resident_on");
}
}
}
private XenRef<Host> _resident_on = new XenRef<Host>(Helper.NullOpaqueRef);
/// <summary>
/// This field contains the estimated fraction of the task which is complete. This field should not be used to determine whether the task is complete - for this the status field of the task should be used.
/// </summary>
public virtual double progress
{
get { return _progress; }
set
{
if (!Helper.AreEqual(value, _progress))
{
_progress = value;
NotifyPropertyChanged("progress");
}
}
}
private double _progress;
/// <summary>
/// if the task has completed successfully, this field contains the type of the encoded result (i.e. name of the class whose reference is in the result field). Undefined otherwise.
/// </summary>
public virtual string type
{
get { return _type; }
set
{
if (!Helper.AreEqual(value, _type))
{
_type = value;
NotifyPropertyChanged("type");
}
}
}
private string _type = "";
/// <summary>
/// if the task has completed successfully, this field contains the result value (either Void or an object reference). Undefined otherwise.
/// </summary>
public virtual string result
{
get { return _result; }
set
{
if (!Helper.AreEqual(value, _result))
{
_result = value;
NotifyPropertyChanged("result");
}
}
}
private string _result = "";
/// <summary>
/// if the task has failed, this field contains the set of associated error strings. Undefined otherwise.
/// </summary>
public virtual string[] error_info
{
get { return _error_info; }
set
{
if (!Helper.AreEqual(value, _error_info))
{
_error_info = value;
NotifyPropertyChanged("error_info");
}
}
}
private string[] _error_info = {};
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// Ref pointing to the task this is a substask of.
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(XenRefConverter<Task>))]
public virtual XenRef<Task> subtask_of
{
get { return _subtask_of; }
set
{
if (!Helper.AreEqual(value, _subtask_of))
{
_subtask_of = value;
NotifyPropertyChanged("subtask_of");
}
}
}
private XenRef<Task> _subtask_of = new XenRef<Task>(Helper.NullOpaqueRef);
/// <summary>
/// List pointing to all the substasks.
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Task>))]
public virtual List<XenRef<Task>> subtasks
{
get { return _subtasks; }
set
{
if (!Helper.AreEqual(value, _subtasks))
{
_subtasks = value;
NotifyPropertyChanged("subtasks");
}
}
}
private List<XenRef<Task>> _subtasks = new List<XenRef<Task>>() {};
/// <summary>
/// Function call trace for debugging.
/// First published in XenServer 7.0.
/// </summary>
public virtual string backtrace
{
get { return _backtrace; }
set
{
if (!Helper.AreEqual(value, _backtrace))
{
_backtrace = value;
NotifyPropertyChanged("backtrace");
}
}
}
private string _backtrace = "()";
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Runtime;
namespace Orleans.Streams
{
internal class PersistentStreamPullingAgent : SystemTarget, IPersistentStreamPullingAgent
{
private static readonly IBackoffProvider DeliveryBackoffProvider = new ExponentialBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1));
private static readonly IBackoffProvider ReadLoopBackoff = new ExponentialBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(1));
private static readonly IStreamFilterPredicateWrapper DefaultStreamFilter =new DefaultStreamFilterPredicateWrapper();
private const int StreamInactivityCheckFrequency = 10;
private readonly string streamProviderName;
private readonly IStreamPubSub pubSub;
private readonly Dictionary<StreamId, StreamConsumerCollection> pubSubCache;
private readonly SafeRandom safeRandom;
private readonly PersistentStreamProviderConfig config;
private readonly Logger logger;
private readonly CounterStatistic numReadMessagesCounter;
private readonly CounterStatistic numSentMessagesCounter;
private int numMessages;
private IQueueAdapter queueAdapter;
private IQueueCache queueCache;
private IQueueAdapterReceiver receiver;
private IStreamFailureHandler streamFailureHandler;
private DateTime lastTimeCleanedPubSubCache;
private IDisposable timer;
internal readonly QueueId QueueId;
private Task receiverInitTask;
private bool IsShutdown => timer == null;
private string StatisticUniquePostfix => streamProviderName + "." + QueueId;
internal PersistentStreamPullingAgent(
GrainId id,
string strProviderName,
IStreamProviderRuntime runtime,
IStreamPubSub streamPubSub,
QueueId queueId,
PersistentStreamProviderConfig config)
: base(id, runtime.ExecutingSiloAddress, true)
{
if (runtime == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null");
if (strProviderName == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: strProviderName should not be null");
QueueId = queueId;
streamProviderName = strProviderName;
pubSub = streamPubSub;
pubSubCache = new Dictionary<StreamId, StreamConsumerCollection>();
safeRandom = new SafeRandom();
this.config = config;
numMessages = 0;
logger = runtime.GetLogger(GrainId + "-" + streamProviderName);
logger.Info(ErrorCode.PersistentStreamPullingAgent_01,
"Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.",
GetType().Name, GrainId.ToDetailedString(), streamProviderName, Silo, QueueId.ToStringWithHashCode());
numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, StatisticUniquePostfix));
numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, StatisticUniquePostfix));
IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, StatisticUniquePostfix), () => pubSubCache.Count);
// TODO: move queue cache size statistics tracking into queue cache implementation once Telemetry APIs and LogStatistics have been reconciled.
//IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, statUniquePostfix), () => queueCache != null ? queueCache.Size : 0);
}
/// <summary>
/// Take responsibility for a new queues that was assigned to me via a new range.
/// We first store the new queue in our internal data structure, try to initialize it and start a pumping timer.
/// ERROR HANDLING:
/// The resposibility to handle initializatoion and shutdown failures is inside the INewQueueAdapterReceiver code.
/// The agent will call Initialize once and log an error. It will not call initiliaze again.
/// The receiver itself may attempt later to recover from this error and do initialization again.
/// The agent will assume initialization has succeeded and will subsequently start calling pumping receive.
/// Same applies to shutdown.
/// </summary>
/// <param name="qAdapter"></param>
/// <param name="queueAdapterCache"></param>
/// <param name="failureHandler"></param>
/// <returns></returns>
public Task Initialize(Immutable<IQueueAdapter> qAdapter, Immutable<IQueueAdapterCache> queueAdapterCache, Immutable<IStreamFailureHandler> failureHandler)
{
if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null");
if (failureHandler.Value == null) throw new ArgumentNullException("failureHandler", "Init: streamDeliveryFailureHandler should not be null");
return OrleansTaskExtentions.WrapInTask(() => InitializeInternal(qAdapter.Value, queueAdapterCache.Value, failureHandler.Value));
}
private void InitializeInternal(IQueueAdapter qAdapter, IQueueAdapterCache queueAdapterCache, IStreamFailureHandler failureHandler)
{
logger.Info(ErrorCode.PersistentStreamPullingAgent_02, "Init of {0} {1} on silo {2} for queue {3}.",
GetType().Name, GrainId.ToDetailedString(), Silo, QueueId.ToStringWithHashCode());
// Remove cast once we cleanup
queueAdapter = qAdapter;
streamFailureHandler = failureHandler;
lastTimeCleanedPubSubCache = DateTime.UtcNow;
try
{
receiver = queueAdapter.CreateReceiver(QueueId);
}
catch (Exception exc)
{
logger.Error(ErrorCode.PersistentStreamPullingAgent_02, "Exception while calling IQueueAdapter.CreateNewReceiver.", exc);
throw;
}
try
{
if (queueAdapterCache != null)
{
queueCache = queueAdapterCache.CreateQueueCache(QueueId);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.PersistentStreamPullingAgent_23, "Exception while calling IQueueAdapterCache.CreateQueueCache.", exc);
throw;
}
try
{
receiverInitTask = OrleansTaskExtentions.SafeExecute(() => receiver.Initialize(config.InitQueueTimeout))
.LogException(logger, ErrorCode.PersistentStreamPullingAgent_03, $"QueueAdapterReceiver {QueueId.ToStringWithHashCode()} failed to Initialize.");
receiverInitTask.Ignore();
}
catch
{
// Just ignore this exception and proceed as if Initialize has succeeded.
// We already logged individual exceptions for individual calls to Initialize. No need to log again.
}
// Setup a reader for a new receiver.
// Even if the receiver failed to initialise, treat it as OK and start pumping it. It's receiver responsibility to retry initialization.
var randomTimerOffset = safeRandom.NextTimeSpan(config.GetQueueMsgsTimerPeriod);
timer = RegisterTimer(AsyncTimerCallback, QueueId, randomTimerOffset, config.GetQueueMsgsTimerPeriod);
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_04, "Taking queue {0} under my responsibility.", QueueId.ToStringWithHashCode());
}
public async Task Shutdown()
{
// Stop pulling from queues that are not in my range anymore.
logger.Info(ErrorCode.PersistentStreamPullingAgent_05, "Shutdown of {0} responsible for queue: {1}", GetType().Name, QueueId.ToStringWithHashCode());
if (timer != null)
{
IDisposable tmp = timer;
timer = null;
Utils.SafeExecute(tmp.Dispose);
}
Task localReceiverInitTask = receiverInitTask;
if (localReceiverInitTask != null)
{
try
{
await localReceiverInitTask;
receiverInitTask = null;
}
catch (Exception)
{
receiverInitTask = null;
// squelch
}
}
try
{
var task = OrleansTaskExtentions.SafeExecute(() => receiver.Shutdown(config.InitQueueTimeout));
task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_07,
$"QueueAdapterReceiver {QueueId} failed to Shutdown.");
await task;
}
catch
{
// Just ignore this exception and proceed as if Shutdown has succeeded.
// We already logged individual exceptions for individual calls to Shutdown. No need to log again.
}
var unregisterTasks = new List<Task>();
var meAsStreamProducer = this.AsReference<IStreamProducerExtension>();
foreach (var tuple in pubSubCache)
{
tuple.Value.DisposeAll(logger);
var streamId = tuple.Key;
logger.Info(ErrorCode.PersistentStreamPullingAgent_06, "Unregister PersistentStreamPullingAgent Producer for stream {0}.", streamId);
unregisterTasks.Add(pubSub.UnregisterProducer(streamId, streamProviderName, meAsStreamProducer));
}
try
{
await Task.WhenAll(unregisterTasks);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.PersistentStreamPullingAgent_08,
"Failed to unregister myself as stream producer to some streams that used to be in my responsibility.", exc);
}
pubSubCache.Clear();
IntValueStatistic.Delete(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, StatisticUniquePostfix));
//IntValueStatistic.Delete(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, StatisticUniquePostfix));
}
public Task AddSubscriber(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
IStreamFilterPredicateWrapper filter)
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.PersistentStreamPullingAgent_09, "AddSubscriber: Stream={0} Subscriber={1}.", streamId, streamConsumer);
// cannot await here because explicit consumers trigger this call, so it could cause a deadlock.
AddSubscriber_Impl(subscriptionId, streamId, streamConsumer, null, filter)
.LogException(logger, ErrorCode.PersistentStreamPullingAgent_26,
$"Failed to add subscription for stream {streamId}.")
.Ignore();
return TaskDone.Done;
}
// Called by rendezvous when new remote subscriber subscribes to this stream.
private async Task AddSubscriber_Impl(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
StreamSequenceToken cacheToken,
IStreamFilterPredicateWrapper filter)
{
if (IsShutdown) return;
StreamConsumerCollection streamDataCollection;
if (!pubSubCache.TryGetValue(streamId, out streamDataCollection))
{
streamDataCollection = new StreamConsumerCollection(DateTime.UtcNow);
pubSubCache.Add(streamId, streamDataCollection);
}
StreamConsumerData data;
if (!streamDataCollection.TryGetConsumer(subscriptionId, out data))
data = streamDataCollection.AddConsumer(subscriptionId, streamId, streamConsumer, filter ?? DefaultStreamFilter);
if (await DoHandshakeWithConsumer(data, cacheToken))
{
if (data.State == StreamConsumerDataState.Inactive)
RunConsumerCursor(data, data.Filter).Ignore(); // Start delivering events if not actively doing so
}
}
private async Task<bool> DoHandshakeWithConsumer(
StreamConsumerData consumerData,
StreamSequenceToken cacheToken)
{
StreamHandshakeToken requestedHandshakeToken = null;
// if not cache, then we can't get cursor and there is no reason to ask consumer for token.
if (queueCache != null)
{
Exception exceptionOccured = null;
try
{
requestedHandshakeToken = await AsyncExecutorWithRetries.ExecuteWithRetries(
i => consumerData.StreamConsumer.GetSequenceToken(consumerData.SubscriptionId),
AsyncExecutorWithRetries.INFINITE_RETRIES,
(exception, i) => !(exception is ClientNotAvailableException),
config.MaxEventDeliveryTime,
DeliveryBackoffProvider);
if (requestedHandshakeToken != null)
{
consumerData.SafeDisposeCursor(logger);
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, requestedHandshakeToken.Token);
}
else
{
if (consumerData.Cursor == null) // if the consumer did not ask for a specific token and we already have a cursor, jsut keep using it.
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, cacheToken);
}
}
catch (Exception exception)
{
exceptionOccured = exception;
}
if (exceptionOccured != null)
{
bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, false, null, requestedHandshakeToken?.Token);
if (faultedSubscription) return false;
}
}
consumerData.LastToken = requestedHandshakeToken; // use what ever the consumer asked for as LastToken for next handshake (even if he asked for null).
// if we don't yet have a cursor (had errors in the handshake or data not available exc), get a cursor at the event that triggered that consumer subscription.
if (consumerData.Cursor == null && queueCache != null)
{
try
{
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, cacheToken);
}
catch (Exception)
{
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, null); // just in case last GetCacheCursor failed.
}
}
return true;
}
public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId)
{
RemoveSubscriber_Impl(subscriptionId, streamId);
return TaskDone.Done;
}
public void RemoveSubscriber_Impl(GuidId subscriptionId, StreamId streamId)
{
if (IsShutdown) return;
StreamConsumerCollection streamData;
if (!pubSubCache.TryGetValue(streamId, out streamData)) return;
// remove consumer
bool removed = streamData.RemoveConsumer(subscriptionId, logger);
if (removed && logger.IsVerbose) logger.Verbose(ErrorCode.PersistentStreamPullingAgent_10, "Removed Consumer: subscription={0}, for stream {1}.", subscriptionId, streamId);
if (streamData.Count == 0)
pubSubCache.Remove(streamId);
}
private async Task AsyncTimerCallback(object state)
{
try
{
Task localReceiverInitTask = receiverInitTask;
if (localReceiverInitTask != null)
{
await localReceiverInitTask;
receiverInitTask = null;
}
if (IsShutdown) return; // timer was already removed, last tick
int maxCacheAddCount = queueCache?.GetMaxAddCount() ?? QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG;
// loop through the queue until it is empty.
while (!IsShutdown) // timer will be set to null when we are asked to shudown.
{
// If read succeeds and there is more data, we continue reading.
// If read succeeds and there is no more data, we breack out of loop
// If read fails, we try again, with backoff policy.
// This prevents spamming backend queue which may be encountering transient errors.
// We retry until the operation succeeds or we are shutdown.
bool moreData = await AsyncExecutorWithRetries.ExecuteWithRetries(
i => ReadFromQueue((QueueId)state, receiver, maxCacheAddCount),
AsyncExecutorWithRetries.INFINITE_RETRIES,
(e, i) => !IsShutdown,
TimeSpan.MaxValue,
ReadLoopBackoff);
if (!moreData)
return;
}
}
catch (Exception exc)
{
receiverInitTask = null;
logger.Error(ErrorCode.PersistentStreamPullingAgent_12, "Exception while PersistentStreamPullingAgentGrain.AsyncTimerCallback", exc);
}
}
/// <summary>
/// Read from queue.
/// Returns true, if data was read, false if it was not
/// </summary>
/// <param name="myQueueId"></param>
/// <param name="rcvr"></param>
/// <param name="maxCacheAddCount"></param>
/// <returns></returns>
private async Task<bool> ReadFromQueue(QueueId myQueueId, IQueueAdapterReceiver rcvr, int maxCacheAddCount)
{
try
{
var now = DateTime.UtcNow;
// Try to cleanup the pubsub cache at the cadence of 10 times in the configurable StreamInactivityPeriod.
if ((now - lastTimeCleanedPubSubCache) >= config.StreamInactivityPeriod.Divide(StreamInactivityCheckFrequency))
{
lastTimeCleanedPubSubCache = now;
CleanupPubSubCache(now);
}
if (queueCache != null)
{
IList<IBatchContainer> purgedItems;
if (queueCache.TryPurgeFromCache(out purgedItems))
{
try
{
await rcvr.MessagesDeliveredAsync(purgedItems);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.PersistentStreamPullingAgent_27,
$"Exception calling MessagesDeliveredAsync on queue {myQueueId}. Ignoring.", exc);
}
}
}
if (queueCache != null && queueCache.IsUnderPressure())
{
// Under back pressure. Exit the loop. Will attempt again in the next timer callback.
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_24, "Stream cache is under pressure. Backing off.");
return false;
}
// Retrive one multiBatch from the queue. Every multiBatch has an IEnumerable of IBatchContainers, each IBatchContainer may have multiple events.
IList<IBatchContainer> multiBatch = await rcvr.GetQueueMessagesAsync(maxCacheAddCount);
if (multiBatch == null || multiBatch.Count == 0) return false; // queue is empty. Exit the loop. Will attempt again in the next timer callback.
queueCache?.AddToCache(multiBatch);
numMessages += multiBatch.Count;
numReadMessagesCounter.IncrementBy(multiBatch.Count);
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.PersistentStreamPullingAgent_11, "Got {0} messages from queue {1}. So far {2} msgs from this queue.",
multiBatch.Count, myQueueId.ToStringWithHashCode(), numMessages);
foreach (var group in
multiBatch
.Where(m => m != null)
.GroupBy(container => new Tuple<Guid, string>(container.StreamGuid, container.StreamNamespace)))
{
var streamId = StreamId.GetStreamId(group.Key.Item1, queueAdapter.Name, group.Key.Item2);
StreamConsumerCollection streamData;
if (pubSubCache.TryGetValue(streamId, out streamData))
{
streamData.RefreshActivity(now);
StartInactiveCursors(streamData); // if this is an existing stream, start any inactive cursors
}
else
{
RegisterStream(streamId, group.First().SequenceToken, now).Ignore(); // if this is a new stream register as producer of stream in pub sub system
}
}
return true;
}
catch (Exception exc)
{
logger.Error(ErrorCode.PersistentStreamPullingAgent_28, "Exception while reading from queue.", exc);
throw;
}
}
private void CleanupPubSubCache(DateTime now)
{
if (pubSubCache.Count == 0) return;
var toRemove = pubSubCache.Where(pair => pair.Value.IsInactive(now, config.StreamInactivityPeriod))
.ToList();
toRemove.ForEach(tuple =>
{
pubSubCache.Remove(tuple.Key);
tuple.Value.DisposeAll(logger);
});
}
private async Task RegisterStream(StreamId streamId, StreamSequenceToken firstToken, DateTime now)
{
var streamData = new StreamConsumerCollection(now);
pubSubCache.Add(streamId, streamData);
// Create a fake cursor to point into a cache.
// That way we will not purge the event from the cache, until we talk to pub sub.
// This will help ensure the "casual consistency" between pre-existing subscripton (of a potentially new already subscribed consumer)
// and later production.
var pinCursor = queueCache.GetCacheCursor(streamId, firstToken);
try
{
await RegisterAsStreamProducer(streamId, firstToken);
}finally
{
// Cleanup the fake pinning cursor.
pinCursor.Dispose();
}
}
private void StartInactiveCursors(StreamConsumerCollection streamData)
{
foreach (StreamConsumerData consumerData in streamData.AllConsumers())
{
if (consumerData.State == StreamConsumerDataState.Inactive)
{
// wake up inactive consumers
RunConsumerCursor(consumerData, consumerData.Filter).Ignore();
}
else
{
consumerData.Cursor?.Refresh();
}
}
}
private async Task RunConsumerCursor(StreamConsumerData consumerData, IStreamFilterPredicateWrapper filterWrapper)
{
try
{
// double check in case of interleaving
if (consumerData.State == StreamConsumerDataState.Active ||
consumerData.Cursor == null) return;
consumerData.State = StreamConsumerDataState.Active;
while (consumerData.Cursor != null)
{
IBatchContainer batch = null;
Exception exceptionOccured = null;
try
{
Exception ignore;
if (!consumerData.Cursor.MoveNext())
{
break;
}
batch = consumerData.Cursor.GetCurrent(out ignore);
}
catch (Exception exc)
{
exceptionOccured = exc;
consumerData.SafeDisposeCursor(logger);
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, null);
}
// Apply filtering to this batch, if applicable
if (filterWrapper != null && batch != null)
{
try
{
// Apply batch filter to this input batch, to see whether we should deliver it to this consumer.
if (!batch.ShouldDeliver(
consumerData.StreamId,
filterWrapper.FilterData,
filterWrapper.ShouldReceive)) continue; // Skip this batch -- nothing to do
}
catch (Exception exc)
{
var message =
$"Ignoring exception while trying to evaluate subscription filter function {filterWrapper} on stream {consumerData.StreamId} in PersistentStreamPullingAgentGrain.RunConsumerCursor";
logger.Warn((int) ErrorCode.PersistentStreamPullingAgent_13, message, exc);
}
}
try
{
numSentMessagesCounter.Increment();
if (batch != null)
{
StreamHandshakeToken newToken = await AsyncExecutorWithRetries.ExecuteWithRetries(
i => DeliverBatchToConsumer(consumerData, batch),
AsyncExecutorWithRetries.INFINITE_RETRIES,
(exception, i) => !(exception is ClientNotAvailableException),
config.MaxEventDeliveryTime,
DeliveryBackoffProvider);
if (newToken != null)
{
consumerData.LastToken = newToken;
IQueueCacheCursor newCursor = queueCache.GetCacheCursor(consumerData.StreamId, newToken.Token);
consumerData.SafeDisposeCursor(logger);
consumerData.Cursor = newCursor;
}
}
}
catch (Exception exc)
{
consumerData.Cursor?.RecordDeliveryFailure();
var message =
$"Exception while trying to deliver msgs to stream {consumerData.StreamId} in PersistentStreamPullingAgentGrain.RunConsumerCursor";
logger.Error(ErrorCode.PersistentStreamPullingAgent_14, message, exc);
exceptionOccured = exc is ClientNotAvailableException
? exc
: new StreamEventDeliveryFailureException(consumerData.StreamId);
}
// if we failed to deliver a batch
if (exceptionOccured != null)
{
bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, true, batch, batch?.SequenceToken);
if (faultedSubscription) return;
}
}
consumerData.State = StreamConsumerDataState.Inactive;
}
catch (Exception exc)
{
// RunConsumerCursor is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception
logger.Error(ErrorCode.PersistentStreamPullingAgent_15, "Ignored RunConsumerCursor Error", exc);
consumerData.State = StreamConsumerDataState.Inactive;
throw;
}
}
private async Task<StreamHandshakeToken> DeliverBatchToConsumer(StreamConsumerData consumerData, IBatchContainer batch)
{
StreamHandshakeToken prevToken = consumerData.LastToken;
Task<StreamHandshakeToken> batchDeliveryTask;
bool isRequestContextSet = batch.ImportRequestContext();
try
{
batchDeliveryTask = consumerData.StreamConsumer.DeliverBatch(consumerData.SubscriptionId, batch.AsImmutable(), prevToken);
}
finally
{
if (isRequestContextSet)
{
// clear RequestContext before await!
RequestContext.Clear();
}
}
StreamHandshakeToken newToken = await batchDeliveryTask;
consumerData.LastToken = StreamHandshakeToken.CreateDeliveyToken(batch.SequenceToken); // this is the currently delivered token
return newToken;
}
private static async Task DeliverErrorToConsumer(StreamConsumerData consumerData, Exception exc, IBatchContainer batch)
{
Task errorDeliveryTask;
bool isRequestContextSet = batch != null && batch.ImportRequestContext();
try
{
errorDeliveryTask = consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId, exc);
}
finally
{
if (isRequestContextSet)
{
RequestContext.Clear(); // clear RequestContext before await!
}
}
await errorDeliveryTask;
}
private async Task<bool> ErrorProtocol(StreamConsumerData consumerData, Exception exceptionOccured, bool isDeliveryError, IBatchContainer batch, StreamSequenceToken token)
{
// for loss of client, we just remove the subscription
if (exceptionOccured is ClientNotAvailableException)
{
logger.Warn(ErrorCode.Stream_ConsumerIsDead,
"Consumer {0} on stream {1} is no longer active - permanently removing Consumer.", consumerData.StreamConsumer, consumerData.StreamId);
pubSub.UnregisterConsumer(consumerData.SubscriptionId, consumerData.StreamId, consumerData.StreamId.ProviderName).Ignore();
return true;
}
// notify consumer about the error or that the data is not available.
await OrleansTaskExtentions.ExecuteAndIgnoreException(
() => DeliverErrorToConsumer(
consumerData, exceptionOccured, batch));
// record that there was a delivery failure
if (isDeliveryError)
{
await OrleansTaskExtentions.ExecuteAndIgnoreException(
() => streamFailureHandler.OnDeliveryFailure(
consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token));
}
else
{
await OrleansTaskExtentions.ExecuteAndIgnoreException(
() => streamFailureHandler.OnSubscriptionFailure(
consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token));
}
// if configured to fault on delivery failure and this is not an implicit subscription, fault and remove the subscription
if (streamFailureHandler.ShouldFaultSubsriptionOnError && !SubscriptionMarker.IsImplicitSubscription(consumerData.SubscriptionId.Guid))
{
try
{
// notify consumer of faulted subscription, if we can.
await OrleansTaskExtentions.ExecuteAndIgnoreException(
() => DeliverErrorToConsumer(
consumerData, new FaultedSubscriptionException(consumerData.SubscriptionId, consumerData.StreamId), batch));
// mark subscription as faulted.
await pubSub.FaultSubscription(consumerData.StreamId, consumerData.SubscriptionId);
}
finally
{
// remove subscription
RemoveSubscriber_Impl(consumerData.SubscriptionId, consumerData.StreamId);
}
return true;
}
return false;
}
private async Task RegisterAsStreamProducer(StreamId streamId, StreamSequenceToken streamStartToken)
{
try
{
if (pubSub == null) throw new NullReferenceException("Found pubSub reference not set up correctly in RetreaveNewStream");
IStreamProducerExtension meAsStreamProducer = this.AsReference<IStreamProducerExtension>();
ISet<PubSubSubscriptionState> streamData = await pubSub.RegisterProducer(streamId, streamProviderName, meAsStreamProducer);
if (logger.IsVerbose) logger.Verbose(ErrorCode.PersistentStreamPullingAgent_16, "Got back {0} Subscribers for stream {1}.", streamData.Count, streamId);
var addSubscriptionTasks = new List<Task>(streamData.Count);
foreach (PubSubSubscriptionState item in streamData)
{
addSubscriptionTasks.Add(AddSubscriber_Impl(item.SubscriptionId, item.Stream, item.Consumer, streamStartToken, item.Filter));
}
await Task.WhenAll(addSubscriptionTasks);
}
catch (Exception exc)
{
// RegisterAsStreamProducer is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception
logger.Error(ErrorCode.PersistentStreamPullingAgent_17, "Ignored RegisterAsStreamProducer Error", exc);
throw;
}
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.Config.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.Config.Api.Tests
{
public class CustomFieldTests
{
public static CustomFieldController Fixture()
{
CustomFieldController controller = new CustomFieldController(new CustomFieldRepository());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.Config.Entities.CustomField customField = Fixture().Get(0);
Assert.NotNull(customField);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.Config.Entities.CustomField customField = Fixture().GetFirst();
Assert.NotNull(customField);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.Config.Entities.CustomField customField = Fixture().GetPrevious(0);
Assert.NotNull(customField);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.Config.Entities.CustomField customField = Fixture().GetNext(0);
Assert.NotNull(customField);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.Config.Entities.CustomField customField = Fixture().GetLast();
Assert.NotNull(customField);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.Config.Entities.CustomField> customFields = Fixture().Get(new long[] { });
Assert.NotNull(customFields);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(0, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(0);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace SIL.WritingSystems
{
/// <summary>
/// This class forms the bases for managing collections of WritingSystemDefinitions. WritingSystemDefinitions
/// can be registered and then retrieved and deleted by ID. The preferred use when editting a WritingSystemDefinition stored
/// in the WritingSystemRepository is to Get the WritingSystemDefinition in question and then to clone it via the
/// Clone method on WritingSystemDefinition. This allows
/// changes made to a WritingSystemDefinition to be registered back with the WritingSystemRepository via the Set method,
/// or to be discarded by simply discarding the object.
/// Internally the WritingSystemRepository uses the WritingSystemDefinition's StoreId property to establish the identity of
/// a WritingSystemDefinition. This allows the user to change the IETF language tag components and thereby the ID of a
/// WritingSystemDefinition and the WritingSystemRepository to update itself and the underlying store correctly.
/// </summary>
public abstract class WritingSystemRepositoryBase<T> : IWritingSystemRepository<T> where T : WritingSystemDefinition
{
private readonly Dictionary<string, T> _writingSystems;
private readonly Dictionary<string, string> _idChangeMap;
private IWritingSystemFactory<T> _writingSystemFactory;
public event EventHandler<WritingSystemIdChangedEventArgs> WritingSystemIdChanged;
public event EventHandler<WritingSystemDeletedEventArgs> WritingSystemDeleted;
public event EventHandler<WritingSystemConflatedEventArgs> WritingSystemConflated;
/// <summary>
/// </summary>
protected WritingSystemRepositoryBase()
{
_writingSystems = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
_idChangeMap = new Dictionary<string, string>();
}
/// <summary>
/// Gets the changed IDs mapping.
/// </summary>
protected IDictionary<string, string> ChangedIds
{
get { return _idChangeMap; }
}
protected IDictionary<string, T> WritingSystems
{
get { return _writingSystems; }
}
public virtual void Conflate(string wsToConflate, string wsToConflateWith)
{
T ws = _writingSystems[wsToConflate];
RemoveDefinition(ws);
if (WritingSystemConflated != null)
WritingSystemConflated(this, new WritingSystemConflatedEventArgs(wsToConflate, wsToConflateWith));
}
/// <summary>
/// Remove the specified WritingSystemDefinition.
/// </summary>
/// <param name="id">the StoreId of the WritingSystemDefinition</param>
/// <remarks>
/// Note that ws.StoreId may differ from ws.Id. The former is the key into the
/// dictionary, but the latter is what gets persisted to disk (and shown to the
/// user).
/// </remarks>
public virtual void Remove(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (!_writingSystems.ContainsKey(id))
throw new ArgumentOutOfRangeException("id");
T ws = _writingSystems[id];
RemoveDefinition(ws);
if (WritingSystemDeleted != null)
WritingSystemDeleted(this, new WritingSystemDeletedEventArgs(id));
//TODO: Could call the shared store to advise that one has been removed.
//TODO: This may be useful if writing systems were reference counted.
}
public virtual IEnumerable<T> AllWritingSystems
{
get { return _writingSystems.Values; }
}
protected virtual void RemoveDefinition(T ws)
{
_writingSystems.Remove(ws.Id);
}
public abstract string WritingSystemIdHasChangedTo(string id);
public virtual bool CanSave(T ws)
{
return true;
}
public IWritingSystemFactory<T> WritingSystemFactory
{
get
{
if (_writingSystemFactory == null)
_writingSystemFactory = CreateWritingSystemFactory();
return _writingSystemFactory;
}
}
protected abstract IWritingSystemFactory<T> CreateWritingSystemFactory();
/// <summary>
/// Removes all writing systems.
/// </summary>
protected void Clear()
{
_writingSystems.Clear();
}
public abstract bool WritingSystemIdHasChanged(string id);
public virtual bool Contains(string id)
{
// identifier should not be null, but some unit tests never define StoreId
// on their temporary WritingSystemDefinition objects.
return id != null && _writingSystems.ContainsKey(id);
}
public bool CanSet(T ws)
{
if (ws == null)
{
return false;
}
if (string.IsNullOrEmpty(ws.Id))
{
return !_writingSystems.ContainsKey(ws.LanguageTag);
}
if (IsLanguageIdChanging(ws, ws.Id))
{
// we are going to be changing the Id, check if we can set with
// the new Id
return !_writingSystems.ContainsKey(ws.LanguageTag);
}
// If the _writingSystems contains a writing system with this Id it is a duplicate,
// but if the writing system is reference equal to the one in _writingSystems we are either
// updating it or in the process of creating it for the first time. So return true.
return !_writingSystems.ContainsKey(ws.Id) || _writingSystems[ws.Id].Equals(ws);
}
public virtual void Set(T ws)
{
if (ws == null)
{
throw new ArgumentNullException("ws");
}
string oldId = _writingSystems.Where(kvp => kvp.Value.Id == ws.Id).Select(kvp => kvp.Key).FirstOrDefault();
//Check if this is a new writing system with a conflicting id
if (!CanSet(ws))
throw new ArgumentException(String.Format("Unable to set writing system '{0}' because this id already exists. Please change this writing system id before setting it.", ws.LanguageTag));
// if there is no Id set, this is new, so mark it as changed
if (string.IsNullOrEmpty(ws.Id))
{
ws.ForceChanged();
ws.Id = ws.LanguageTag;
}
//??? How do we update
//??? Is it sufficient to just set it, or can we not change the reference in case someone else has it too
//??? i.e. Do we need a ws.Copy(WritingSystemDefinition)?
if (!string.IsNullOrEmpty(oldId) && _writingSystems.ContainsKey(oldId))
{
_writingSystems.Remove(oldId);
}
string newId = ws.Id;
if (IsLanguageIdChanging(ws, ws.Id))
{
newId = ws.LanguageTag;
}
_writingSystems[newId] = ws;
if (!string.IsNullOrEmpty(oldId) && IsLanguageIdChanging(ws, oldId))
{
UpdateChangedIds(oldId, ws.LanguageTag);
if (WritingSystemIdChanged != null)
WritingSystemIdChanged(this, new WritingSystemIdChangedEventArgs(oldId, ws.LanguageTag));
}
ws.Id = newId;
}
private static bool IsLanguageIdChanging(T ws, string oldId)
{
return !IetfLanguageTag.AreTagsEquivalent(oldId, ws.LanguageTag);
}
/// <summary>
/// Replace one writing system with another
/// </summary>
/// <remarks>The language tag could either change, or remain the same.</remarks>
public virtual void Replace(string languageTag, T newWs)
{
Remove(languageTag);
Set(newWs);
}
/// <summary>
/// Updates the changed IDs mapping.
/// </summary>
protected void UpdateChangedIds(string oldId, string newId)
{
if (_idChangeMap.ContainsValue(oldId))
{
// if the oldid is in the value of key/value, then we can update the cooresponding key with the newId
string keyToChange = _idChangeMap.First(pair => pair.Value == oldId).Key;
_idChangeMap[keyToChange] = newId;
}
else if (_idChangeMap.ContainsKey(oldId))
{
// if oldId is already in the dictionary, set the result to be newId
_idChangeMap[oldId] = newId;
}
}
/// <summary>
/// Loads the changed IDs mapping from the existing writing systems.
/// </summary>
protected void LoadChangedIdsFromExistingWritingSystems()
{
_idChangeMap.Clear();
foreach (var pair in _writingSystems)
_idChangeMap[pair.Key] = pair.Key;
}
public virtual bool TryGet(string id, out T ws)
{
if (Contains(id))
{
ws = Get(id);
return true;
}
ws = null;
return false;
}
public string GetNewIdWhenSet(T ws)
{
if (ws == null)
{
throw new ArgumentNullException("ws");
}
return String.IsNullOrEmpty(ws.Id) ? ws.LanguageTag : ws.Id;
}
public virtual T Get(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (!_writingSystems.ContainsKey(id))
throw new ArgumentOutOfRangeException("id", String.Format("Writing system id '{0}' does not exist.", id));
return _writingSystems[id];
}
public virtual int Count
{
get
{
return _writingSystems.Count;
}
}
public virtual void Save()
{
}
void IWritingSystemRepository.Set(WritingSystemDefinition ws)
{
Set((T) ws);
}
bool IWritingSystemRepository.CanSet(WritingSystemDefinition ws)
{
return CanSet((T) ws);
}
WritingSystemDefinition IWritingSystemRepository.Get(string id)
{
return Get(id);
}
bool IWritingSystemRepository.TryGet(string id, out WritingSystemDefinition ws)
{
T result;
if (TryGet(id, out result))
{
ws = result;
return true;
}
ws = null;
return false;
}
string IWritingSystemRepository.GetNewIdWhenSet(WritingSystemDefinition ws)
{
return GetNewIdWhenSet((T) ws);
}
bool IWritingSystemRepository.CanSave(WritingSystemDefinition ws)
{
return CanSave((T) ws);
}
IEnumerable<WritingSystemDefinition> IWritingSystemRepository.AllWritingSystems
{
get { return AllWritingSystems; }
}
IWritingSystemFactory IWritingSystemRepository.WritingSystemFactory
{
get { return WritingSystemFactory; }
}
/// <summary>
/// Used whenever writing a WS definition to disk. Reads contents of any existing data in the folder,
/// falling back to any data in the SLDR Cache.
/// </summary>
/// <remarks>Does not attempt to pull the writing system into the SLDR Cache.</remarks>
protected static MemoryStream GetDataToMergeWithInSave(string writingSystemFilePath)
{
MemoryStream oldData = null;
if (File.Exists(writingSystemFilePath))
{
// load old data to preserve stuff in LDML that we don't use, but don't throw up an error if it fails
try
{
oldData = new MemoryStream(File.ReadAllBytes(writingSystemFilePath), false);
}
catch
{
}
}
else
{
var source = Path.Combine(Sldr.SldrCachePath,
Path.GetFileName(writingSystemFilePath));
if (File.Exists(source))
{
oldData = new MemoryStream(File.ReadAllBytes(source), false);
}
}
return oldData;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Linq;
using System.Xml;
using System.Runtime.Serialization;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.DebugHelpers;
using Microsoft.Msagl.DebugHelpers.Persistence;
namespace Microsoft.Msagl.Drawing {
/// <summary>
/// reads a drawing graph from a stream
/// </summary>
public class GraphReader {
/// <summary>
/// the list of edges, needed to match it with GeometryGraphReader edges
/// </summary>
public IList<Edge> EdgeList = new List<Edge>();
Stream stream;
Graph graph = new Graph();
XmlReader xmlReader;
Dictionary<string, SubgraphTemplate> subgraphTable=new Dictionary<string, SubgraphTemplate>();
GeometryGraphReader geometryGraphReader;
internal GraphReader(Stream streamP) {
stream = streamP;
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreWhitespace = true;
readerSettings.IgnoreComments = true;
xmlReader = XmlReader.Create(stream, readerSettings);
}
/// <summary>
/// Reads the graph from a file
/// </summary>
/// <returns></returns>
internal Graph Read() {
System.Globalization.CultureInfo currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
try {
ReadGraph();
} finally { System.Threading.Thread.CurrentThread.CurrentCulture = currentCulture; }
return graph;
}
private void ReadGraph() {
MoveToContent();
CheckToken(Tokens.MsaglGraph);
XmlRead();
if (TokenIs(Tokens.UserData))
graph.UserData = ReadUserData();
ReadAttr();
ReadLabel(graph);
bool done = false;
do
{
switch (GetElementTag())
{
case Tokens.Nodes:
ReadNodes();
break;
case Tokens.Edges:
FleshOutSubgraphs(); //for this moment the nodes and the clusters have to be set already
ReadEdges();
break;
case Tokens.Subgraphs:
ReadSubgraphs();
break;
case Tokens.graph:
ReadGeomGraph();
break;
case Tokens.End:
done = true;
break;
default: //ignore this element
xmlReader.Skip();
break;
// XmlReader.Skip();
// ReadHeader();
// if (TokenIs(Tokens.LayoutAlgorithmSettings))
// this.Settings = ReadLayoutAlgorithmSettings(XmlReader);
// ReadNodes();
// ReadClusters();
// ReadEdges();
}
} while (!done);
}
void FleshOutSubgraphs() {
foreach (var subgraphTemlate in subgraphTable.Values) {
var subgraph = subgraphTemlate.Subgraph;
foreach (var id in subgraphTemlate.SubgraphIdList)
subgraph.AddSubgraph(subgraphTable[id].Subgraph);
foreach (var id in subgraphTemlate.NodeIdList)
subgraph.AddNode(this.graph.FindNode(id));
}
var rootSubgraphSet = new Set<Subgraph>();
foreach (var subgraph in subgraphTable.Values.Select(c => c.Subgraph))
if (subgraph.ParentSubgraph == null) {
rootSubgraphSet.Insert(subgraph);
graph.RootSubgraph.AddSubgraph(subgraph);
}
if (rootSubgraphSet.Count == 1)
graph.RootSubgraph = rootSubgraphSet.First();
else
foreach (var subgraph in rootSubgraphSet)
graph.RootSubgraph.AddSubgraph(subgraph);
}
void ReadSubgraphs() {
xmlReader.Read();
while (TokenIs(Tokens.Subgraph))
ReadSubgraph();
if (!xmlReader.IsStartElement())
ReadEndElement();
}
void ReadSubgraph() {
var listOfSubgraphs = xmlReader.GetAttribute(Tokens.listOfSubgraphs.ToString());
var subgraphTempl = new SubgraphTemplate();
if (!string.IsNullOrEmpty(listOfSubgraphs)) {
subgraphTempl.SubgraphIdList.AddRange(listOfSubgraphs.Split(' '));
}
var listOfNodes = xmlReader.GetAttribute(Tokens.listOfNodes.ToString());
if (!string.IsNullOrEmpty(listOfNodes)) {
subgraphTempl.NodeIdList.AddRange(listOfNodes.Split(' '));
}
xmlReader.Read();
var subgraph = ReadSubgraphContent();
subgraphTempl.Subgraph = subgraph;
subgraphTable[subgraph.Id] = subgraphTempl;
}
private object ReadUserData()
{
CheckToken(Tokens.UserData);
XmlRead();
string typeString = ReadStringElement(Tokens.UserDataType);
string serString = ReadStringElement(Tokens.SerializedUserData);
ReadEndElement();
Type t = Type.GetType(typeString);
DataContractSerializer dcs = new DataContractSerializer(t);
StringReader sr = new StringReader(serString);
XmlReader xr = XmlReader.Create(sr);
return dcs.ReadObject(xr,true);
}
private void ReadLabel(DrawingObject parent) {
CheckToken(Tokens.Label);
bool hasLabel = !this.xmlReader.IsEmptyElement;
if (hasLabel) {
XmlRead();
Label label = new Label {
Text = ReadStringElement(Tokens.Text),
FontName = ReadStringElement(Tokens.FontName),
FontColor = ReadColorElement(Tokens.FontColor),
FontStyle = TokenIs(Tokens.FontStyle) ? (FontStyle)ReadIntElement(Tokens.FontStyle) : FontStyle.Regular,
FontSize = ReadDoubleElement(Tokens.FontSize),
Width = ReadDoubleElement(Tokens.Width),
Height = ReadDoubleElement(Tokens.Height),
Owner = parent
};
((ILabeledObject) parent).Label = label;
ReadEndElement();
}
else {
var node = parent as Node;
if (node != null){//we still need a label!
Label label = new Label {
Text = node.Id,
Owner = parent
};
((ILabeledObject) parent).Label = label;
}
xmlReader.Skip();
}
}
void ReadGeomGraph() {
geometryGraphReader = new GeometryGraphReader();
geometryGraphReader.SetXmlReader(this.xmlReader);
GeometryGraph geomGraph = geometryGraphReader.Read();
BindTheGraphs(this.graph, geomGraph, graph.LayoutAlgorithmSettings);
}
void BindTheGraphs(Graph drawingGraph, GeometryGraph geomGraph, LayoutAlgorithmSettings settings) {
drawingGraph.GeometryGraph = geomGraph;
foreach (Node dn in drawingGraph.NodeMap.Values) {
var geomNode = dn.GeometryNode = geometryGraphReader.FindNodeById(dn.Id);
geomNode.UserData = dn;
}
foreach (var subgraph in drawingGraph.RootSubgraph.AllSubgraphsDepthFirst()) {
var geomNode = subgraph.GeometryNode = geometryGraphReader.FindClusterById(subgraph.Id);
if (geomNode != null)
geomNode.UserData = subgraph;
}
// geom edges have to appear in the same order as drawing edges
for(int i = 0;i < EdgeList.Count;i++) {
var drawingEdge = EdgeList[i];
var geomEdge = geometryGraphReader.EdgeList[i];
drawingEdge.GeometryEdge = geomEdge;
geomEdge.UserData = drawingEdge;
if(drawingEdge.Label != null) {
drawingEdge.Label.GeometryLabel = geomEdge.Label;
geomEdge.Label.UserData = drawingEdge.Label;
}
}
drawingGraph.LayoutAlgorithmSettings = settings;
}
private void ReadEdges() {
CheckToken(Tokens.Edges);
if (xmlReader.IsEmptyElement) {
XmlRead();
return;
}
XmlRead();
while (TokenIs(Tokens.Edge))
ReadEdge();
ReadEndElement();
}
private void ReadEdge() {
CheckToken(Tokens.Edge);
XmlRead();
object userData = null;
if (TokenIs(Tokens.UserData))
userData = ReadUserData();
Edge edge=graph.AddEdge(ReadStringElement(Tokens.SourceNodeID), ReadStringElement(Tokens.TargetNodeID));
edge.Attr = new EdgeAttr();
edge.UserData = userData;
ReadEdgeAttr(edge.Attr);
ReadLabel(edge);
EdgeList.Add(edge);
ReadEndElement();
}
Tokens GetElementTag()
{
Tokens token;
if (xmlReader.ReadState == ReadState.EndOfFile)
return Tokens.End;
if (Enum.TryParse(xmlReader.Name, true, out token))
return token;
throw new InvalidOperationException();
}
private void ReadEdgeAttr(EdgeAttr edgeAttr) {
CheckToken(Tokens.EdgeAttribute);
XmlRead();
ReadBaseAttr(edgeAttr);
edgeAttr.Separation = ReadIntElement(Tokens.EdgeSeparation);
edgeAttr.Weight = ReadIntElement(Tokens.Weight);
edgeAttr.ArrowheadAtSource = (ArrowStyle)Enum.Parse(typeof(ArrowStyle), ReadStringElement(Tokens.ArrowStyle), false);
edgeAttr.ArrowheadAtTarget = (ArrowStyle)Enum.Parse(typeof(ArrowStyle), ReadStringElement(Tokens.ArrowStyle), false);
edgeAttr.ArrowheadLength =(float) ReadDoubleElement(Tokens.ArrowheadLength);
ReadEndElement();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "token")]
private int ReadIntElement(Tokens token) {
CheckToken(token);
return ReadElementContentAsInt();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "token")]
private string ReadStringElement(Tokens token) {
CheckToken(token);
return ReadElementContentAsString();
}
private int ReadElementContentAsInt() {
return xmlReader.ReadElementContentAsInt();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "token")]
private bool ReadBooleanElement(Tokens token) {
CheckToken(token);
return ReadElementContentAsBoolean();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "token")]
private double ReadDoubleElement(Tokens token) {
CheckToken(token);
return ReadElementContentAsDouble();
}
private void ReadNodes() {
CheckToken(Tokens.Nodes);
XmlRead();
while (TokenIs(Tokens.Node))
ReadNode();
ReadEndElement();
}
private void ReadNode() {
CheckToken(Tokens.Node);
ReadNodeContent();
}
Subgraph ReadSubgraphContent()
{
object userData = null;
if (TokenIs(Tokens.UserData))
userData = ReadUserData();
var nodeAttr = new NodeAttr();
ReadNodeAttr(nodeAttr);
var subgraph = new Subgraph(nodeAttr.Id) {Label = null, Attr = nodeAttr, UserData = userData};
ReadLabel(subgraph);
ReadEndElement();
return subgraph;
}
void ReadNodeContent() {
XmlRead();
object userData = null;
if (TokenIs(Tokens.UserData))
userData = ReadUserData();
var nodeAttr = new NodeAttr();
ReadNodeAttr(nodeAttr);
var node = graph.AddNode(nodeAttr.Id);
node.Label = null;
node.Attr = nodeAttr;
node.UserData = userData;
ReadLabel(node);
ReadEndElement();
}
private void ReadNodeAttr(NodeAttr na) {
CheckToken(Tokens.NodeAttribute);
XmlRead();
ReadBaseAttr(na);
na.FillColor = ReadColorElement(Tokens.Fillcolor);
na.LabelMargin=ReadIntElement(Tokens.LabelMargin);
na.Padding=ReadDoubleElement(Tokens.Padding);
na.Shape = (Shape) Enum.Parse(typeof(Shape), ReadStringElement(Tokens.Shape), false);
na.XRadius=ReadDoubleElement(Tokens.XRad);
na.YRadius=ReadDoubleElement(Tokens.YRad);
ReadEndElement();
}
private void ReadBaseAttr(AttributeBase baseAttr) {
CheckToken(Tokens.BaseAttr);
XmlRead();
ReadStyles(baseAttr);
baseAttr.Color = ReadColorElement(Tokens.Color);
baseAttr.LineWidth = ReadDoubleElement(Tokens.LineWidth);
baseAttr.Id = ReadStringElement(Tokens.ID);
ReadEndElement();
}
private void ReadStyles(AttributeBase baseAttr) {
CheckToken(Tokens.Styles);
XmlRead();
bool haveStyles = false;
while (TokenIs(Tokens.Style)) {
baseAttr.AddStyle((Style)Enum.Parse(typeof(Style), ReadStringElement(Tokens.Style), false));
haveStyles = true;
}
if (haveStyles)
ReadEndElement();
}
private void ReadEndElement() {
xmlReader.ReadEndElement();
}
private string ReadElementContentAsString() {
return xmlReader.ReadElementContentAsString();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.Conditional("DEBUGGLEE")]
private void CheckToken(Tokens t) {
if (!xmlReader.IsStartElement(t.ToString())) {
throw new InvalidDataException(String.Format("expecting {0}", t));
}
}
private bool TokenIs(Tokens t) {
return xmlReader.IsStartElement(t.ToString());
}
private void ReadAttr() {
CheckToken(Tokens.GraphAttribute);
XmlRead();
ReadBaseAttr(graph.Attr);
ReadMinNodeHeight();
ReadMinNodeWidth();
ReadAspectRatio();
ReadBorder();
graph.Attr.BackgroundColor = ReadColorElement(Tokens.BackgroundColor);
graph.Attr.Margin = ReadDoubleElement(Tokens.Margin);
graph.Attr.OptimizeLabelPositions = ReadBooleanElement(Tokens.OptimizeLabelPositions);
graph.Attr.NodeSeparation = ReadDoubleElement(Tokens.NodeSeparation);
graph.Attr.LayerDirection = (LayerDirection)Enum.Parse(typeof(LayerDirection), ReadStringElement(Tokens.LayerDirection), false);
graph.Attr.LayerSeparation = ReadDoubleElement(Tokens.LayerSeparation);
ReadEndElement();
}
private void ReadBorder() {
graph.Attr.Border = ReadIntElement(Tokens.Border);
}
private void ReadMinNodeWidth() {
this.graph.Attr.MinNodeWidth = ReadDoubleElement(Tokens.MinNodeWidth);
}
private void ReadMinNodeHeight() {
this.graph.Attr.MinNodeHeight = ReadDoubleElement(Tokens.MinNodeHeight);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "token")]
Color ReadColorElement(Tokens token) {
CheckToken(token);
XmlRead();
Color c = ReadColor();
ReadEndElement();
return c;
}
Color ReadColor() {
CheckToken(Tokens.Color);
XmlRead();
Color c = new Color(ReadByte(Tokens.A), ReadByte(Tokens.R), ReadByte(Tokens.G), ReadByte(Tokens.B));
ReadEndElement();
return c;
}
private byte ReadByte(Tokens token) {
return (byte)ReadIntElement(token);
}
private void ReadAspectRatio() {
CheckToken(Tokens.AspectRatio);
graph.Attr.AspectRatio = ReadElementContentAsDouble();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Convert.ToBoolean(System.String)")]
private bool ReadElementContentAsBoolean() {
return Convert.ToBoolean(xmlReader.ReadElementContentAsString());
}
private double ReadElementContentAsDouble() {
return xmlReader.ReadElementContentAsDouble();
}
private void MoveToContent() {
xmlReader.MoveToContent();
}
private void XmlRead() {
xmlReader.Read();
}
}
}
| |
using NQuery.Binding;
using NQuery.Symbols.Aggregation;
namespace NQuery.Optimization
{
internal sealed class SubqueryExpander : BoundTreeRewriter
{
private readonly Stack<List<Subquery>> _subqueryStack = new();
private readonly Stack<BoundExpression> _passthruStack = new();
private enum SubqueryKind
{
Exists,
Subselect
}
private sealed class Subquery
{
public Subquery(SubqueryKind kind, ValueSlot valueSlot, BoundRelation relation, BoundExpression passthru)
{
Kind = kind;
ValueSlot = valueSlot;
Relation = relation;
Passthru = passthru;
}
public SubqueryKind Kind { get; }
public ValueSlot ValueSlot { get; }
public BoundRelation Relation { get; }
public BoundExpression Passthru { get; }
}
public BoundExpression CurrentPassthru
{
get { return _passthruStack.Count == 0 ? null : _passthruStack.Peek(); }
}
public override BoundRelation RewriteRelation(BoundRelation node)
{
_subqueryStack.Push(new List<Subquery>());
var result = base.RewriteRelation(node);
if (_subqueryStack.Peek().Any())
throw ExceptionBuilder.UnexpectedValue(node.Kind);
_subqueryStack.Pop();
return result;
}
protected override BoundExpression RewriteCaseExpression(BoundCaseExpression node)
{
var whenPassthru = CurrentPassthru;
var labels = node.CaseLabels;
foreach (var oldLabel in labels)
{
_passthruStack.Push(whenPassthru);
var when = RewriteExpression(oldLabel.Condition);
_passthruStack.Pop();
var thenPassthru = Expression.Or(whenPassthru, Expression.Not(when));
_passthruStack.Push(thenPassthru);
var then = RewriteExpression(oldLabel.ThenExpression);
_passthruStack.Pop();
var label = oldLabel.Update(when, then);
labels = labels.Replace(oldLabel, label);
whenPassthru = Expression.Or(whenPassthru, when);
}
_passthruStack.Push(whenPassthru);
var elseExpression = RewriteExpression(node.ElseExpression);
_passthruStack.Pop();
return node.Update(labels, elseExpression);
}
protected override BoundExpression RewriteSingleRowSubselect(BoundSingleRowSubselect node)
{
var relation = RewriteRelation(node.Relation);
var factory = node.Value.Factory;
// TODO: If the query is guaranteed to return a single, e.g. if it is a aggregated but not grouped,
// we should not emit the additional aggregation and assertion.
// 1. We need to know whether it returns more than one row.
var valueSlot = node.Value;
var anyOutput = factory.CreateTemporary(valueSlot.Type);
var countOutput = factory.CreateTemporary(typeof(int));
var anyAggregateSymbol = BuiltInAggregates.Any;
var anyAggregatable = anyAggregateSymbol.Definition.CreateAggregatable(valueSlot.Type);
var countAggregatedSymbol = BuiltInAggregates.Count;
var countAggregatable = countAggregatedSymbol.Definition.CreateAggregatable(typeof(int));
var aggregates = new[]
{
new BoundAggregatedValue(anyOutput, anyAggregateSymbol, anyAggregatable, Expression.Value(valueSlot)),
new BoundAggregatedValue(countOutput, countAggregatedSymbol, countAggregatable, Expression.Literal(0))
};
var aggregation = new BoundGroupByAndAggregationRelation(relation, Enumerable.Empty<BoundComparedValue>(), aggregates);
// 2. Now we can assert that the number of rows returned is at most one.
var condition = Expression.LessThan(Expression.Value(countOutput), Expression.Literal(1));
var message = Resources.SubqueryReturnedMoreThanRow;
var assertRelation = new BoundAssertRelation(aggregation, condition, message);
var subquery = new Subquery(SubqueryKind.Subselect, anyOutput, assertRelation, CurrentPassthru);
var subqueries = _subqueryStack.Peek();
subqueries.Add(subquery);
return Expression.Value(anyOutput);
}
protected override BoundExpression RewriteExistsSubselect(BoundExistsSubselect node)
{
var relation = RewriteRelation(node.Relation);
// TODO: This isn't ideal. In many cases, the relation will not have any output values.
// This means, we've to create a new value slot factory which in turn means that
// we have to create multiple slots with the same name. It seems we should think of
// a better way to carry the factories. Maybe we should just expose on specific
// bound nodes?
var factory = node.Relation.GetOutputValues().FirstOrDefault()?.Factory ?? new ValueSlotFactory();
var valueSlot = factory.CreateTemporary(typeof(bool));
var subquery = new Subquery(SubqueryKind.Exists, valueSlot, relation, CurrentPassthru);
var subqueries = _subqueryStack.Peek();
subqueries.Add(subquery);
return Expression.Value(valueSlot);
}
protected override BoundRelation RewriteFilterRelation(BoundFilterRelation node)
{
var input = RewriteRelation(node.Input);
var rewrittenRelation = RewriteConjunctions(input, node.Condition);
if (rewrittenRelation is not null)
{
// We might have residual subqueries that couldn't be
// converted to semi joins.
return RewriteRelation(rewrittenRelation);
}
// There were no subqueries that could be expressed as semi joins.
// However, there might still exist subqueries, so we need to visit
// the expression that will convert them to probing semi joins.
var condition = RewriteExpression(node.Condition);
var inputWithProbes = RewriteInputWithSubqueries(input);
return node.Update(inputWithProbes, condition);
}
protected override BoundRelation RewriteComputeRelation(BoundComputeRelation node)
{
var input = RewriteRelation(node.Input);
var computedValues = RewriteComputedValues(node.DefinedValues);
var inputWithProbes = RewriteInputWithSubqueries(input);
return node.Update(inputWithProbes, computedValues);
}
protected override BoundRelation RewriteJoinRelation(BoundJoinRelation node)
{
var left = RewriteRelation(node.Left);
var right = RewriteRelation(node.Right);
var rewrittenRight = RewriteConjunctions(right, node.Condition);
if (rewrittenRight is not null)
{
// We might have residual subqueries that couldn't be
// converted to semi joins.
return RewriteRelation(node.Update(node.JoinType, left, rewrittenRight, null, node.Probe, node.PassthruPredicate));
}
// There were no subqueries that could be expressed as semi joins.
// However, there might still exist subqueries, so we need to visit
// the expression that will convert them to probing semi joins.
var condition = RewriteExpression(node.Condition);
var rightWithProbes = RewriteInputWithSubqueries(right);
return node.Update(node.JoinType, left, rightWithProbes, condition, node.Probe, node.PassthruPredicate);
}
private BoundRelation RewriteInputWithSubqueries(BoundRelation input)
{
var subqueries = _subqueryStack.Peek();
var result = input;
result = subqueries.Where(s => s.Kind == SubqueryKind.Exists)
.Aggregate(result, EmitExists);
result = subqueries.Where(s => s.Kind == SubqueryKind.Subselect)
.Aggregate(result, EmitSubselect);
subqueries.Clear();
return result;
}
private static BoundJoinRelation EmitExists(BoundRelation result, Subquery existsSubquery)
{
return new BoundJoinRelation(BoundJoinType.LeftSemi, result, existsSubquery.Relation, null, existsSubquery.ValueSlot, existsSubquery.Passthru);
}
private static BoundJoinRelation EmitSubselect(BoundRelation result, Subquery subselect)
{
return new BoundJoinRelation(BoundJoinType.LeftOuter, result, subselect.Relation, null, null, subselect.Passthru);
}
private static BoundRelation RewriteConjunctions(BoundRelation input, BoundExpression condition)
{
var current = input;
var scalarPredicates = new List<BoundExpression>();
var conjunctions = Expression.SplitConjunctions(condition);
foreach (var conjunction in conjunctions)
{
if (TryGetExistsSubselect(conjunction, out var exists, out var isNegated))
{
var joinType = isNegated
? BoundJoinType.LeftAntiSemi
: BoundJoinType.LeftSemi;
current = new BoundJoinRelation(joinType, current, exists.Relation, null, null, null);
}
else if (Expression.IsDisjunction(conjunction))
{
var relation = RewriteDisjunctions(conjunction);
if (relation is not null)
current = new BoundJoinRelation(BoundJoinType.LeftSemi, current, relation, null, null, null);
else
scalarPredicates.Add(conjunction);
}
else
{
scalarPredicates.Add(conjunction);
}
}
// If we haven't done anything, simply return null to indicate to our
// caller that the condition only contained scalars.
if (current == input)
return null;
// If we have no scalar predicates left, it means the condition only
// contained EXISTs queries, so we can return the current node.
if (scalarPredicates.Count == 0)
return current;
// Otherwise we add a filter for the scalars.
var predicate = Expression.And(scalarPredicates);
return new BoundFilterRelation(current, predicate);
}
private static BoundRelation RewriteDisjunctions(BoundExpression condition)
{
var scalarPredicates = new List<BoundExpression>();
var relationalPredicates = new List<BoundRelation>();
foreach (var disjunction in Expression.SplitDisjunctions(condition))
{
if (TryGetExistsSubselect(disjunction, out var exists, out var isNegated))
{
if (!isNegated)
{
relationalPredicates.Add(exists.Relation);
}
else
{
var constantRelation = new BoundConstantRelation();
var predicate = new BoundJoinRelation(BoundJoinType.LeftAntiSemi, constantRelation, exists.Relation, null, null, null);
relationalPredicates.Add(predicate);
}
}
else if (Expression.IsConjunction(disjunction))
{
var constantRelation = new BoundConstantRelation();
var output = RewriteConjunctions(constantRelation, disjunction);
if (output is null)
{
scalarPredicates.Add(disjunction);
}
else
{
var predicate = new BoundJoinRelation(BoundJoinType.LeftSemi, constantRelation, output, null, null, null);
relationalPredicates.Add(predicate);
}
}
else
{
scalarPredicates.Add(disjunction);
}
}
if (relationalPredicates.Count == 0)
return null;
if (scalarPredicates.Count > 0)
{
var constantRelation = new BoundConstantRelation();
var predicate = Expression.Or(scalarPredicates);
var filter = new BoundFilterRelation(constantRelation, predicate);
relationalPredicates.Insert(0, filter);
}
return new BoundConcatenationRelation(relationalPredicates, Enumerable.Empty<BoundUnifiedValue>());
}
private static bool TryGetExistsSubselect(BoundExpression expression, out BoundExistsSubselect existsSubselect, out bool isNegated)
{
if (expression is BoundUnaryExpression negation && negation.Result.Selected.Signature.Kind == UnaryOperatorKind.LogicalNot)
{
if (!TryGetExistsSubselect(negation.Expression, out existsSubselect, out isNegated))
return false;
isNegated = !isNegated;
return true;
}
isNegated = false;
existsSubselect = expression as BoundExistsSubselect;
return existsSubselect is not null;
}
}
}
| |
// 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.
namespace Fixtures.AcceptanceTestsUrlMultiCollectionFormat
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Queries operations.
/// </summary>
public partial class Queries : IServiceOperations<AutoRestUrlMutliCollectionFormatTestService>, IQueries
{
/// <summary>
/// Initializes a new instance of the Queries class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Queries(AutoRestUrlMutliCollectionFormatTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestUrlMutliCollectionFormatTestService
/// </summary>
public AutoRestUrlMutliCollectionFormatTestService Client { get; private set; }
/// <summary>
/// Get a null array of string using the multi-array format
/// </summary>
/// <param name='arrayQuery'>
/// a null array of string using the multi-array format
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> ArrayStringMultiNullWithHttpMessagesAsync(IList<string> arrayQuery = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("arrayQuery", arrayQuery);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ArrayStringMultiNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "queries/array/multi/string/null").ToString();
List<string> _queryParameters = new List<string>();
if (arrayQuery != null)
{
if (arrayQuery.Count == 0)
{
_queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(string.Empty)));
}
else
{
foreach (var _item in arrayQuery)
{
_queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(_item ?? string.Empty)));
}
}
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get an empty array [] of string using the multi-array format
/// </summary>
/// <param name='arrayQuery'>
/// an empty array [] of string using the multi-array format
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> ArrayStringMultiEmptyWithHttpMessagesAsync(IList<string> arrayQuery = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("arrayQuery", arrayQuery);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ArrayStringMultiEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "queries/array/multi/string/empty").ToString();
List<string> _queryParameters = new List<string>();
if (arrayQuery != null)
{
if (arrayQuery.Count == 0)
{
_queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(string.Empty)));
}
else
{
foreach (var _item in arrayQuery)
{
_queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(_item ?? string.Empty)));
}
}
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' ,
/// null, ''] using the mult-array format
/// </summary>
/// <param name='arrayQuery'>
/// an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' ,
/// null, ''] using the mult-array format
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> ArrayStringMultiValidWithHttpMessagesAsync(IList<string> arrayQuery = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("arrayQuery", arrayQuery);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ArrayStringMultiValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "queries/array/multi/string/valid").ToString();
List<string> _queryParameters = new List<string>();
if (arrayQuery != null)
{
if (arrayQuery.Count == 0)
{
_queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(string.Empty)));
}
else
{
foreach (var _item in arrayQuery)
{
_queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(_item ?? string.Empty)));
}
}
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.Services;
using WebsitePanel.EnterpriseServer.Code.SharePoint;
using WebsitePanel.Providers.SharePoint;
using Microsoft.Web.Services3;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Summary description for esHostedSharePointServers
/// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/enterpriseserver")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
[ToolboxItem(false)]
public class esHostedSharePointServers : WebService
{
/// <summary>
/// Gets site collections in raw form.
/// </summary>
/// <param name="packageId">Package to which desired site collections belong.</param>
/// <param name="organizationId">Organization to which desired site collections belong.</param>
/// <param name="filterColumn">Filter column name.</param>
/// <param name="filterValue">Filter value.</param>
/// <param name="sortColumn">Sort column name.</param>
/// <param name="startRow">Row index to start from.</param>
/// <param name="maximumRows">Maximum number of rows to retrieve.</param>
/// <returns>Site collections in raw format.</returns>
[WebMethod]
public SharePointSiteCollectionListPaged GetSiteCollectionsPaged(int packageId, int organizationId,
string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows)
{
return HostedSharePointServerController.GetSiteCollectionsPaged(packageId, organizationId, filterColumn, filterValue,
sortColumn, startRow, maximumRows);
}
/// <summary>
/// Gets list of supported languages by this installation of SharePoint.
/// </summary>
/// <returns>List of supported languages</returns>
[WebMethod]
public int[] GetSupportedLanguages(int packageId)
{
return HostedSharePointServerController.GetSupportedLanguages(packageId);
}
/// <summary>
/// Gets list of SharePoint site collections that belong to the package.
/// </summary>
/// <param name="packageId">Package that owns site collections.</param>
/// <param name="recursive">A value which shows whether nested spaces must be searched as well.</param>
/// <returns>List of found site collections.</returns>
[WebMethod]
public List<SharePointSiteCollection> GetSiteCollections(int packageId, bool recursive)
{
return HostedSharePointServerController.GetSiteCollections(packageId, recursive);
}
[WebMethod]
public int SetStorageSettings(int itemId, int maxStorage, int warningStorage, bool applyToSiteCollections)
{
return HostedSharePointServerController.SetStorageSettings(itemId, maxStorage, warningStorage, applyToSiteCollections );
}
/// <summary>
/// Gets SharePoint site collection with given id.
/// </summary>
/// <param name="itemId">Site collection id within metabase.</param>
/// <returns>Site collection.</returns>
[WebMethod]
public SharePointSiteCollection GetSiteCollection(int itemId)
{
return HostedSharePointServerController.GetSiteCollection(itemId);
}
/// <summary>
/// Gets SharePoint site collection from package under organization with given domain.
/// </summary>
/// <param name="packageId">Package id.</param>
/// <param name="organizationId">Organization id.</param>
/// <param name="domain">Domain name.</param>
/// <returns>SharePoint site collection or null.</returns>
[WebMethod]
public SharePointSiteCollection GetSiteCollectionByDomain(int organizationId, string domain)
{
DomainInfo domainInfo = ServerController.GetDomain(domain);
SharePointSiteCollectionListPaged existentSiteCollections = this.GetSiteCollectionsPaged(domainInfo.PackageId, organizationId, "ItemName", String.Format("%{0}", domain), String.Empty, 0, Int32.MaxValue);
foreach (SharePointSiteCollection existentSiteCollection in existentSiteCollections.SiteCollections)
{
Uri existentSiteCollectionUri = new Uri(existentSiteCollection.Name);
if (existentSiteCollection.Name == String.Format("{0}://{1}", existentSiteCollectionUri.Scheme, domain))
{
return existentSiteCollection;
}
}
return null;
}
/// <summary>
/// Adds SharePoint site collection.
/// </summary>
/// <param name="item">Site collection description.</param>
/// <returns>Created site collection id within metabase.</returns>
[WebMethod]
public int AddSiteCollection(SharePointSiteCollection item)
{
return HostedSharePointServerController.AddSiteCollection(item);
}
/// <summary>
/// Deletes SharePoint site collection with given id.
/// </summary>
/// <param name="itemId">Site collection id within metabase.</param>
/// <returns>?</returns>
[WebMethod]
public int DeleteSiteCollection(int itemId)
{
return HostedSharePointServerController.DeleteSiteCollection(itemId);
}
/// <summary>
/// Deletes SharePoint site collections which belong to organization.
/// </summary>
/// <param name="organizationId">Site collection id within metabase.</param>
/// <returns>?</returns>
[WebMethod]
public int DeleteSiteCollections(int organizationId)
{
HostedSharePointServerController.DeleteSiteCollections(organizationId);
return 0;
}
/// <summary>
/// Backups SharePoint site collection.
/// </summary>
/// <param name="itemId">Site collection id within metabase.</param>
/// <param name="fileName">Backed up site collection file name.</param>
/// <param name="zipBackup">A value which shows whether back up must be archived.</param>
/// <param name="download">A value which shows whether created back up must be downloaded.</param>
/// <param name="folderName">Local folder to store downloaded backup.</param>
/// <returns>Created backup file name. </returns>
[WebMethod]
public string BackupSiteCollection(int itemId, string fileName, bool zipBackup, bool download, string folderName)
{
return HostedSharePointServerController.BackupSiteCollection(itemId, fileName, zipBackup, download, folderName);
}
/// <summary>
/// Restores SharePoint site collection.
/// </summary>
/// <param name="itemId">Site collection id within metabase.</param>
/// <param name="uploadedFile"></param>
/// <param name="packageFile"></param>
/// <returns></returns>
[WebMethod]
public int RestoreSiteCollection(int itemId, string uploadedFile, string packageFile)
{
return HostedSharePointServerController.RestoreSiteCollection(itemId, uploadedFile, packageFile);
}
/// <summary>
/// Gets binary data chunk of specified size from specified offset.
/// </summary>
/// <param name="itemId">Item id to obtain realted service id.</param>
/// <param name="path">Path to file to get bunary data chunk from.</param>
/// <param name="offset">Offset from which to start data reading.</param>
/// <param name="length">Binary data chunk length.</param>
/// <returns>Binary data chunk read from file.</returns>
[WebMethod]
public byte[] GetBackupBinaryChunk(int itemId, string path, int offset, int length)
{
return HostedSharePointServerController.GetBackupBinaryChunk(itemId, path, offset, length);
}
/// <summary>
/// Appends supplied binary data chunk to file.
/// </summary>
/// <param name="itemId">Item id to obtain realted service id.</param>
/// <param name="fileName">Non existent file name to append to.</param>
/// <param name="path">Full path to existent file to append to.</param>
/// <param name="chunk">Binary data chunk to append to.</param>
/// <returns>Path to file that was appended with chunk.</returns>
[WebMethod]
public string AppendBackupBinaryChunk(int itemId, string fileName, string path, byte[] chunk)
{
return HostedSharePointServerController.AppendBackupBinaryChunk(itemId, fileName, path, chunk);
}
[WebMethod]
public SharePointSiteDiskSpace[] CalculateSharePointSitesDiskSpace(int itemId, out int errorCode)
{
return HostedSharePointServerController.CalculateSharePointSitesDiskSpace(itemId, out errorCode);
}
[WebMethod]
public void UpdateQuota(int itemId, int siteCollectionId, int maxSize, int warningSize)
{
HostedSharePointServerController.UpdateQuota(itemId, siteCollectionId, maxSize, warningSize);
}
}
}
| |
///////////////////////////////////////////////////////////////////////////
// Description: Data Access class for the table 'RS_JenisPenjamin'
// Generated by LLBLGen v1.21.2003.712 Final on: Thursday, October 11, 2007, 2:03:11 AM
// Because the Base Class already implements IDispose, this class doesn't.
///////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace SIMRS.DataAccess
{
/// <summary>
/// Purpose: Data Access class for the table 'RS_JenisPenjamin'.
/// </summary>
public class RS_JenisPenjamin : DBInteractionBase
{
#region Class Member Declarations
private SqlBoolean _published;
private SqlDateTime _createdDate, _modifiedDate;
private SqlInt32 _createdBy, _modifiedBy, _ordering, _id;
private SqlString _kode, _nama, _keterangan;
#endregion
/// <summary>
/// Purpose: Class constructor.
/// </summary>
public RS_JenisPenjamin()
{
// Nothing for now.
}
/// <summary>
/// Purpose: IsExist method. This method will check Exsisting data from database.
/// </summary>
/// <returns></returns>
public bool IsExist()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPenjamin_IsExist]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@IsExist", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
int IsExist = int.Parse(cmdToExecute.Parameters["@IsExist"].Value.ToString());
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPenjamin_IsExist' reported the ErrorCode: " + _errorCode);
}
return IsExist == 1;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPenjamin::IsExist::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Insert method. This method will insert one new row into the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Insert()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPenjamin_Insert]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPenjamin_Insert' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPenjamin::Insert::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Update method. This method will Update one existing row in the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Update()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPenjamin_Update]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPenjamin_Update' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPenjamin::Update::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Delete()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPenjamin_Delete]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPenjamin_Delete' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPenjamin::Delete::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy</LI>
/// <LI>ModifiedDate</LI>
/// </UL>
/// Will fill all properties corresponding with a field in the table with the value of the row selected.
/// </remarks>
public override DataTable SelectOne()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPenjamin_SelectOne]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_JenisPenjamin");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPenjamin_SelectOne' reported the ErrorCode: " + _errorCode);
}
if (toReturn.Rows.Count > 0)
{
_id = (Int32)toReturn.Rows[0]["Id"];
_kode = (string)toReturn.Rows[0]["Kode"];
_nama = (string)toReturn.Rows[0]["Nama"];
_keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"];
_published = (bool)toReturn.Rows[0]["Published"];
_ordering = (Int32)toReturn.Rows[0]["Ordering"];
_createdBy = (Int32)toReturn.Rows[0]["CreatedBy"];
_createdDate = (DateTime)toReturn.Rows[0]["CreatedDate"];
_modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"];
_modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"];
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPenjamin::SelectOne::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: SelectAll method. This method will Select all rows from the table.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override DataTable SelectAll()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPenjamin_SelectAll]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_JenisPenjamin");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPenjamin_SelectAll' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPenjamin::SelectAll::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: GetList method. This method will Select all rows from the table where is active.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public DataTable GetList()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPenjamin_GetList]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_JenisPenjamin");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPenjamin_GetList' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPenjamin::GetList::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
#region Class Property Declarations
public SqlInt32 Id
{
get
{
return _id;
}
set
{
SqlInt32 idTmp = (SqlInt32)value;
if (idTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Id", "Id can't be NULL");
}
_id = value;
}
}
public SqlString Kode
{
get
{
return _kode;
}
set
{
SqlString kodeTmp = (SqlString)value;
if (kodeTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Kode", "Kode can't be NULL");
}
_kode = value;
}
}
public SqlString Nama
{
get
{
return _nama;
}
set
{
SqlString namaTmp = (SqlString)value;
if (namaTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Nama", "Nama can't be NULL");
}
_nama = value;
}
}
public SqlString Keterangan
{
get
{
return _keterangan;
}
set
{
_keterangan = value;
}
}
public SqlBoolean Published
{
get
{
return _published;
}
set
{
_published = value;
}
}
public SqlInt32 Ordering
{
get
{
return _ordering;
}
set
{
SqlInt32 orderingTmp = (SqlInt32)value;
if (orderingTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Ordering", "Ordering can't be NULL");
}
_ordering = value;
}
}
public SqlInt32 CreatedBy
{
get
{
return _createdBy;
}
set
{
SqlInt32 createdByTmp = (SqlInt32)value;
if (createdByTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedBy", "CreatedBy can't be NULL");
}
_createdBy = value;
}
}
public SqlDateTime CreatedDate
{
get
{
return _createdDate;
}
set
{
SqlDateTime createdDateTmp = (SqlDateTime)value;
if (createdDateTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedDate", "CreatedDate can't be NULL");
}
_createdDate = value;
}
}
public SqlInt32 ModifiedBy
{
get
{
return _modifiedBy;
}
set
{
_modifiedBy = value;
}
}
public SqlDateTime ModifiedDate
{
get
{
return _modifiedDate;
}
set
{
_modifiedDate = value;
}
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Referensi_KelompokPemeriksaan_List : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsListRefKelompokPemeriksaan";
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["KelompokPemeriksaanManagement"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
else
{
btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddKelompokPemeriksaan");
}
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
UpdateDataView(true);
}
}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
SIMRS.DataAccess.RS_KelompokPemeriksaan myObj = new SIMRS.DataAccess.RS_KelompokPemeriksaan();
DataTable myData = myObj.SelectAll2();
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("Add.aspx?CurrentPage=" + CurrentPage);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Nama")
dv.RowFilter = " Nama LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Kode")
dv.RowFilter = " Kode LIKE '%" + txtSearch.Text + "%'";
else
dv.RowFilter = "";
BindData(dv);
}
#endregion
#region .Update Link Item Butom
public string GetLinkButton(string Id, string Nama, string CurrentPage)
{
string szResult = "";
if (Session["KelompokPemeriksaanManagement"] != null)
{
szResult += "<a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
return szResult;
}
#endregion
}
| |
/**
* @brief Same throttleing mechanism as the baseline global_round_robin scheme. However
* this controller puts high apps into a cluster with different mechanims.
**/
//#define DEBUG_NETUTIL
//#define EXTRA_DEBUG
using System;
using System.Collections.Generic;
namespace ICSimulator
{
public class Controller_Global_round_robin_netutil: Controller_Global_round_robin
{
public static double lastNetUtil;
public static int total_cluster;
public Controller_Global_round_robin_netutil()
{
isThrottling = false;
Console.WriteLine("init: Global_RR");
for (int i = 0; i < Config.N; i++)
{
MPKI[i]=0.0;
num_ins_last_epoch[i]=0;
m_isThrottled[i]=false;
L1misses[i]=0;
lastNetUtil = 0;
total_cluster=Config.num_epoch;
}
}
public override void doThrottling()
{
for(int i=0;i<Config.N;i++)
{
if((throttleTable[i]==currentAllow)||(throttleTable[i]==0))
setThrottleRate(i,false);
else
setThrottleRate(i, true);
}
currentAllow++;
//interval based
if(currentAllow > total_cluster)
currentAllow=1;
}
/**
* @brief Add cluster to be short live to reduce netutil
*
* 1.determine netutil
* 2.add cluster that has short life
* 3.Pick the highest MPKI node from each cluster and add it to
* the new cluster
* TODO: shufftle the apps to be picked
**/
public void addShortLifeCluster()
{
int short_life_id=total_cluster+1;
int empty_count=0;
//id=0 means not throttled. Pick apps from the original clusters
for(int id=1;id<=Config.num_epoch;id++)
{
int max_id=-1;
double maxMPKI=0.0;
for(int i=0;i<Config.N;i++)
{
if(throttleTable[i]==id && MPKI[i]>maxMPKI)
{
maxMPKI=MPKI[i];
max_id=i;
}
}
if(max_id>-1)
{
#if EXTRA_DEBUG
Console.WriteLine("Node {0} added to Scluster {1}",max_id,short_life_id);
#endif
throttleTable[max_id]=short_life_id;
}
else
empty_count++;
}
if(empty_count<Config.num_epoch)
total_cluster++;
}
/**
* @brief Removes all the short life clusters and
* distribute apps in the cluster to other clusters randomly.
**/
public void removeShortLifeCluster()
{
#if EXTRA_DEBUG
Console.WriteLine("\n****Removing the short life cluster");
#endif
//reset it
total_cluster=Config.num_epoch;
for(int i=0;i<Config.N;i++)
{
if(throttleTable[i]>Config.num_epoch)
{
//randomly distribute it to another cluster
int randseed=Simulator.rand.Next(1,Config.num_epoch+1);
if(randseed==0 || randseed>Config.num_epoch)
throw new Exception("rand seed errors: out of range!");
throttleTable[i]=randseed;
}
}
}
public override void doStep()
{
//throttle stats
for(int i=0;i<Config.N;i++)
{
if(throttleTable[i]!=0 && throttleTable[i]!=currentAllow && isThrottling)
Simulator.stats.throttle_time_bysrc[i].Add();
}
//sampling period: Examine the network state and determine whether to throttle or not
if (Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0)
{
//In case the removecluster never happends at small intervals. Deallocate
//this cluster to ensure reshuffling of apps in the short life cluster.
if(total_cluster>Config.num_epoch)
removeShortLifeCluster();
setThrottling();
lastNetUtil = Simulator.stats.netutil.Total;
resetStat();
}
//once throttle mode is turned on. Let each cluster run for a certain time interval
//to ensure fairness. Otherwise it's throttled most of the time.
if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)Config.interval_length) == 0)
{
ulong cycles_elapsed=Simulator.CurrentRound%(ulong)Config.throttle_sampling_period;
double netutil=(cycles_elapsed==0)?(double)Simulator.stats.netutil.Total:
((double)(Simulator.stats.netutil.Total -lastNetUtil)/cycles_elapsed);
#if EXTRA_DEBUG
//Console.WriteLine("Interval: netutil {0} should be a double",netutil);
#endif
doThrottling();
if(netutil>Config.netutil_throttling_threshold)
addShortLifeCluster();
if(netutil<Config.netutil_throttling_threshold && total_cluster>Config.num_epoch)
removeShortLifeCluster();
}
else if(isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
//more than 1 short life cluster
total_cluster>Config.num_epoch &&
//After a short life cluster has run by looking at next currentAllow
//b/c currentAllow will only be back to the first or within the extra id region.
(currentAllow==1||currentAllow>(Config.num_epoch+1)) &&
(Simulator.CurrentRound % (ulong)Config.short_life_interval)==0)
{
//after a short life for the cluster, yield its left over interval to other clusters
doThrottling();
}
if(total_cluster<Config.num_epoch)
{
Console.WriteLine("Incorrect total cluster {0}",total_cluster);
throw new Exception("Incorrect total cluster");
}
}
public override bool thresholdTrigger()
{
double netutil=((double)(Simulator.stats.netutil.Total -lastNetUtil)/ (double)Config.throttle_sampling_period);
#if DEBUG_NETUTIL
Console.WriteLine("avg netUtil = {0} thres at {1}",netutil,Config.netutil_throttling_threshold);
#endif
return (netutil > (double)Config.netutil_throttling_threshold)?true:false;
}
public override void setThrottling()
{
#if DEBUG_NETUTIL
Console.Write("\n:: cycle {0} ::",
Simulator.CurrentRound);
#endif
//get the MPKI value
for (int i = 0; i < Config.N; i++)
{
prev_MPKI[i]=MPKI[i];
if(num_ins_last_epoch[i]==0)
MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count);
else
{
if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]>0)
MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]);
else if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]==0)
MPKI[i]=0;
else
throw new Exception("MPKI error!");
}
}
recordStats();
if(isThrottling)
{
//see if we can un-throttle the netowork
#if DEBUG_NETUTIL
Console.WriteLine("In throttle mode: avg netUtil = {0} thres at {1}",(double)((Simulator.stats.netutil.Total-lastNetUtil)/(double)Config.throttle_sampling_period), Config.netutil_throttling_threshold);
#endif
if(((double)(Simulator.stats.netutil.Total -lastNetUtil)/ (double)Config.throttle_sampling_period) < (double)Config.netutil_throttling_threshold)
{
isThrottling = false;
//un-throttle the network
for(int i=0;i<Config.N;i++)
setThrottleRate(i,false);
}
}
else
{
if (thresholdTrigger()) // an abstract fn() that trigger whether to start throttling or not
{
//determine if the node is high intensive by using MPKI
int total_high = 0;
for (int i = 0; i < Config.N; i++)
{
if (MPKI[i] > Config.MPKI_high_node)
{
total_high++;
setThrottleRate(i, true);
#if DEBUG
Console.Write("#ON#:Node {0} with MPKI {1} ",i,MPKI[i]);
#endif
}
else
{
throttleTable[i]=0;
setThrottleRate(i, false);
#if DEBUG
Console.Write("@OFF@:Node {0} with MPKI {1} prev_MPKI {2} ",i,MPKI[i],prev_MPKI[i]);
#endif
}
}
setThrottleTable();
#if DEBUG
Console.WriteLine(")");
#endif
isThrottling = true;
currentAllow = 1;
}
}
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// Group
/// </summary>
[DataContract]
public partial class Group : IEquatable<Group>, IValidatableObject
{
public Group()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="Group" /> class.
/// </summary>
/// <param name="DsGroupId">DsGroupId.</param>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="GroupId">The DocuSign group ID for the group..</param>
/// <param name="GroupName">The name of the group..</param>
/// <param name="GroupType">The group type..</param>
/// <param name="PermissionProfileId">The ID of the permission profile associated with the group..</param>
/// <param name="Users">Users.</param>
/// <param name="UsersCount">UsersCount.</param>
public Group(string DsGroupId = default(string), ErrorDetails ErrorDetails = default(ErrorDetails), string GroupId = default(string), string GroupName = default(string), string GroupType = default(string), string PermissionProfileId = default(string), List<UserInfo> Users = default(List<UserInfo>), string UsersCount = default(string))
{
this.DsGroupId = DsGroupId;
this.ErrorDetails = ErrorDetails;
this.GroupId = GroupId;
this.GroupName = GroupName;
this.GroupType = GroupType;
this.PermissionProfileId = PermissionProfileId;
this.Users = Users;
this.UsersCount = UsersCount;
}
/// <summary>
/// Gets or Sets DsGroupId
/// </summary>
[DataMember(Name="dsGroupId", EmitDefaultValue=false)]
public string DsGroupId { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
/// The DocuSign group ID for the group.
/// </summary>
/// <value>The DocuSign group ID for the group.</value>
[DataMember(Name="groupId", EmitDefaultValue=false)]
public string GroupId { get; set; }
/// <summary>
/// The name of the group.
/// </summary>
/// <value>The name of the group.</value>
[DataMember(Name="groupName", EmitDefaultValue=false)]
public string GroupName { get; set; }
/// <summary>
/// The group type.
/// </summary>
/// <value>The group type.</value>
[DataMember(Name="groupType", EmitDefaultValue=false)]
public string GroupType { get; set; }
/// <summary>
/// The ID of the permission profile associated with the group.
/// </summary>
/// <value>The ID of the permission profile associated with the group.</value>
[DataMember(Name="permissionProfileId", EmitDefaultValue=false)]
public string PermissionProfileId { get; set; }
/// <summary>
/// Gets or Sets Users
/// </summary>
[DataMember(Name="users", EmitDefaultValue=false)]
public List<UserInfo> Users { get; set; }
/// <summary>
/// Gets or Sets UsersCount
/// </summary>
[DataMember(Name="usersCount", EmitDefaultValue=false)]
public string UsersCount { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Group {\n");
sb.Append(" DsGroupId: ").Append(DsGroupId).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" GroupId: ").Append(GroupId).Append("\n");
sb.Append(" GroupName: ").Append(GroupName).Append("\n");
sb.Append(" GroupType: ").Append(GroupType).Append("\n");
sb.Append(" PermissionProfileId: ").Append(PermissionProfileId).Append("\n");
sb.Append(" Users: ").Append(Users).Append("\n");
sb.Append(" UsersCount: ").Append(UsersCount).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Group);
}
/// <summary>
/// Returns true if Group instances are equal
/// </summary>
/// <param name="other">Instance of Group to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Group other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.DsGroupId == other.DsGroupId ||
this.DsGroupId != null &&
this.DsGroupId.Equals(other.DsGroupId)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.GroupId == other.GroupId ||
this.GroupId != null &&
this.GroupId.Equals(other.GroupId)
) &&
(
this.GroupName == other.GroupName ||
this.GroupName != null &&
this.GroupName.Equals(other.GroupName)
) &&
(
this.GroupType == other.GroupType ||
this.GroupType != null &&
this.GroupType.Equals(other.GroupType)
) &&
(
this.PermissionProfileId == other.PermissionProfileId ||
this.PermissionProfileId != null &&
this.PermissionProfileId.Equals(other.PermissionProfileId)
) &&
(
this.Users == other.Users ||
this.Users != null &&
this.Users.SequenceEqual(other.Users)
) &&
(
this.UsersCount == other.UsersCount ||
this.UsersCount != null &&
this.UsersCount.Equals(other.UsersCount)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.DsGroupId != null)
hash = hash * 59 + this.DsGroupId.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.GroupId != null)
hash = hash * 59 + this.GroupId.GetHashCode();
if (this.GroupName != null)
hash = hash * 59 + this.GroupName.GetHashCode();
if (this.GroupType != null)
hash = hash * 59 + this.GroupType.GetHashCode();
if (this.PermissionProfileId != null)
hash = hash * 59 + this.PermissionProfileId.GetHashCode();
if (this.Users != null)
hash = hash * 59 + this.Users.GetHashCode();
if (this.UsersCount != null)
hash = hash * 59 + this.UsersCount.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using UnityEngine.Experimental.Rendering.HDPipeline.Attributes;
using UnityEngine.Rendering;
//using System.Runtime.InteropServices;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class StackLit : RenderPipelineMaterial
{
[GenerateHLSL(PackingRules.Exact)]
public enum MaterialFeatureFlags
{
StackLitStandard = 1 << 0,
StackLitDualSpecularLobe = 1 << 1,
StackLitAnisotropy = 1 << 2,
StackLitCoat = 1 << 3,
StackLitIridescence = 1 << 4,
StackLitSubsurfaceScattering = 1 << 5,
StackLitTransmission = 1 << 6,
StackLitCoatNormalMap = 1 << 7,
StackLitSpecularColor = 1 << 8,
StackLitHazyGloss = 1 << 9,
};
// We will use keywords no need for [GenerateHLSL] as we don't test in HLSL such a value
public enum BaseParametrization
{
BaseMetallic = 0,
SpecularColor = 1, // MaterialFeatureFlags.StackLitSpecularColor
};
// We will use keywords no need for [GenerateHLSL] as we don't test in HLSL such a value
public enum DualSpecularLobeParametrization
{
Direct = 0,
HazyGloss = 1, // MaterialFeatureFlags.StackLitHazyGloss
// Pascal Barla, Romain Pacanowski, Peter Vangorp. A Composite BRDF Model for Hazy Gloss.
// Computer Graphics Forum, Wiley, 2018, 37, <10.1111/cgf.13475>. <hal-01818666v2>
// https://hal.inria.fr/hal-01818666v2
// Submitted on 6 Jul 2018
};
//-----------------------------------------------------------------------------
// SurfaceData
//-----------------------------------------------------------------------------
// Main structure that store the user data (i.e user input of master node in material graph)
[GenerateHLSL(PackingRules.Exact, false, false, true, 1100)]
public struct SurfaceData
{
[SurfaceDataAttributes("Material Features")]
public uint materialFeatures;
// Bottom interface (2 lobes BSDF)
// Standard parametrization
[MaterialSharedPropertyMapping(MaterialSharedProperty.Albedo)]
[SurfaceDataAttributes("Base Color", false, true)]
public Vector3 baseColor;
[MaterialSharedPropertyMapping(MaterialSharedProperty.AmbientOcclusion)]
[SurfaceDataAttributes("Ambient Occlusion")]
public float ambientOcclusion;
[MaterialSharedPropertyMapping(MaterialSharedProperty.Metal)]
[SurfaceDataAttributes("Metallic")]
public float metallic;
[SurfaceDataAttributes("Dielectric IOR")]
public float dielectricIor;
[MaterialSharedPropertyMapping(MaterialSharedProperty.Specular)]
[SurfaceDataAttributes("Specular Color", false, true)]
public Vector3 specularColor;
[MaterialSharedPropertyMapping(MaterialSharedProperty.Normal)]
[SurfaceDataAttributes(new string[] {"Normal", "Normal View Space"}, true)]
public Vector3 normalWS;
[SurfaceDataAttributes(new string[] {"Geometric Normal", "Geometric Normal View Space"}, true)]
public Vector3 geomNormalWS;
[SurfaceDataAttributes(new string[] {"Coat Normal", "Coat Normal View Space"}, true)]
public Vector3 coatNormalWS;
[SurfaceDataAttributes(new string[] {"Bent Normal", "Bent Normal View Space"}, true)]
public Vector3 bentNormalWS;
[MaterialSharedPropertyMapping(MaterialSharedProperty.Smoothness)]
[SurfaceDataAttributes("Smoothness A")]
public float perceptualSmoothnessA;
// Dual specular lobe: Direct parametrization (engine parameters)
[SurfaceDataAttributes("Smoothness B")]
public float perceptualSmoothnessB;
[SurfaceDataAttributes("Lobe Mixing")]
public float lobeMix;
// Dual specular lobe: DualSpecularLobeParametrization == HazyGloss parametrization.
//
// Lobe B is the haze.
//
// In that mode, perceptual parameters of "haziness" and "hazeExtent" are used.
// The base layer f0 parameter when the DualSpecularLobeParametrization was == "Direct"
// is now also a perceptual parameter corresponding to a pseudo-f0 term, Fc(0) or
// "coreFresnel0" (r_c in the paper). Although an intermediate value, this original
// fresnel0 never reach the engine side (BSDFData).
//
// [ Without the HazyGloss parametrization, the original base layer f0 is directly inferred
// as f0 = f(baseColor, metallic) when the BaseParametrization is BaseMetallic
// or directly given via f0 = SpecularColor when the BaseParametrization == SpecularColor.
//
// When the DualSpecularLobeParametrization is "HazyGloss", this base layer f0 is
// now reinterpreted as the perceptual "core lobe reflectivity" or Fc(0) or r_c in
// the paper.]
//
// From these perceptual parameters, the engine-used lobeMix, fresnel0 (SpecularColor)
// and SmoothnessB parameters are set.
//
// [ TODO: We could actually scrap metallic and dielectricIor here and update specularColor
// to always hold the f0 intermediate value (r_c), although you could then go further and
// put the final "engine input" f0 in there, and other perceptuals like haziness and
// hazeExtent and update directly lobeMix here. For now we keep the shader mostly organized
// like Lit ]
[SurfaceDataAttributes("Haziness")]
public float haziness;
[SurfaceDataAttributes("Haze Extent")]
public float hazeExtent;
[SurfaceDataAttributes("Hazy Gloss Max Dielectric f0 When Using Metallic Input")]
public float hazyGlossMaxDielectricF0;
// Anisotropy
[SurfaceDataAttributes("Tangent", true)]
public Vector3 tangentWS;
[SurfaceDataAttributes("AnisotropyA")]
public float anisotropyA; // anisotropic ratio(0->no isotropic; 1->full anisotropy in tangent direction, -1->full anisotropy in bitangent direction)
// Anisotropy for secondary specular lobe
[SurfaceDataAttributes("AnisotropyB")]
public float anisotropyB; // anisotropic ratio(0->no isotropic; 1->full anisotropy in tangent direction, -1->full anisotropy in bitangent direction)
// Iridescence
[SurfaceDataAttributes("IridescenceIor")]
public float iridescenceIor;
[SurfaceDataAttributes("IridescenceThickness")]
public float iridescenceThickness;
[SurfaceDataAttributes("Iridescence Mask")]
public float iridescenceMask;
// Top interface and media (clearcoat)
[SurfaceDataAttributes("Coat Smoothness")]
public float coatPerceptualSmoothness;
[SurfaceDataAttributes("Coat IOR")]
public float coatIor;
[SurfaceDataAttributes("Coat Thickness")]
public float coatThickness;
[SurfaceDataAttributes("Coat Extinction Coefficient")]
public Vector3 coatExtinction;
// SSS
[SurfaceDataAttributes("Diffusion Profile Hash")]
public uint diffusionProfileHash;
[SurfaceDataAttributes("Subsurface Mask")]
public float subsurfaceMask;
// Transmission
// + Diffusion Profile
[SurfaceDataAttributes("Thickness")]
public float thickness;
};
//-----------------------------------------------------------------------------
// BSDFData
//-----------------------------------------------------------------------------
[GenerateHLSL(PackingRules.Exact, false, false, true, 1150)]
public struct BSDFData
{
public uint materialFeatures;
// Bottom interface (2 lobes BSDF)
// Standard parametrization
[SurfaceDataAttributes("", false, true)]
public Vector3 diffuseColor;
public Vector3 fresnel0;
public float ambientOcclusion;
[SurfaceDataAttributes(new string[] { "Normal WS", "Normal View Space" }, true)]
public Vector3 normalWS;
[SurfaceDataAttributes(new string[] {"Geometric Normal", "Geometric Normal View Space"}, true)]
public Vector3 geomNormalWS;
[SurfaceDataAttributes(new string[] {"Coat Normal", "Coat Normal View Space"}, true)]
public Vector3 coatNormalWS;
[SurfaceDataAttributes(new string[] {"Bent Normal", "Bent Normal View Space"}, true)]
public Vector3 bentNormalWS;
public float perceptualRoughnessA;
// Dual specular lobe
public float perceptualRoughnessB;
public float lobeMix;
// Anisotropic
[SurfaceDataAttributes("", true)]
public Vector3 tangentWS;
[SurfaceDataAttributes("", true)]
public Vector3 bitangentWS;
public float roughnessAT;
public float roughnessAB;
public float roughnessBT;
public float roughnessBB;
public float anisotropyA;
public float anisotropyB;
// Top interface and media (clearcoat)
public float coatRoughness;
public float coatPerceptualRoughness;
public float coatIor;
public float coatThickness;
public Vector3 coatExtinction;
// iridescence
public float iridescenceIor;
public float iridescenceThickness;
public float iridescenceMask;
// SSS
public uint diffusionProfileIndex;
public float subsurfaceMask;
// Transmission
// + Diffusion Profile
public float thickness;
public bool useThickObjectMode; // Read from the diffusion profile
public Vector3 transmittance; // Precomputation of transmittance
};
//-----------------------------------------------------------------------------
// Init precomputed textures
//-----------------------------------------------------------------------------
public StackLit() {}
public override void Build(HDRenderPipelineAsset hdAsset)
{
PreIntegratedFGD.instance.Build(PreIntegratedFGD.FGDIndex.FGD_GGXAndDisneyDiffuse);
LTCAreaLight.instance.Build();
SPTDistribution.instance.Build();
}
public override void Cleanup()
{
PreIntegratedFGD.instance.Cleanup(PreIntegratedFGD.FGDIndex.FGD_GGXAndDisneyDiffuse);
LTCAreaLight.instance.Cleanup();
SPTDistribution.instance.Cleanup();
}
public override void RenderInit(CommandBuffer cmd)
{
PreIntegratedFGD.instance.RenderInit(PreIntegratedFGD.FGDIndex.FGD_GGXAndDisneyDiffuse, cmd);
}
public override void Bind(CommandBuffer cmd)
{
PreIntegratedFGD.instance.Bind(cmd, PreIntegratedFGD.FGDIndex.FGD_GGXAndDisneyDiffuse);
LTCAreaLight.instance.Bind(cmd);
SPTDistribution.instance.Bind(cmd);
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.Threading;
using Newtonsoft.Json.Utilities;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Specialized;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a token that can contain other tokens.
/// </summary>
public abstract class JContainer : JToken, IList<JToken>, IList
{
/// <summary>
/// Gets the container's children tokens.
/// </summary>
/// <value>The container's children tokens.</value>
protected abstract IList<JToken> ChildrenTokens { get; }
private object _syncRoot;
#pragma warning disable 649
private bool _busy;
#pragma warning restore 649
internal JContainer()
{
}
internal JContainer(JContainer other)
{
ValidationUtils.ArgumentNotNull(other, "c");
foreach (JToken child in other)
{
Add(child);
}
}
internal void CheckReentrancy()
{
if (_busy)
throw new InvalidOperationException("Cannot change {0} during a collection change event.".FormatWith(CultureInfo.InvariantCulture, GetType()));
}
/// <summary>
/// Gets a value indicating whether this token has childen tokens.
/// </summary>
/// <value>
/// <c>true</c> if this token has child values; otherwise, <c>false</c>.
/// </value>
public override bool HasValues
{
get { return ChildrenTokens.Count > 0; }
}
internal bool ContentsEqual(JContainer container)
{
JToken t1 = First;
JToken t2 = container.First;
if (t1 == t2)
return true;
do
{
if (t1 == null && t2 == null)
return true;
if (t1 != null && t2 != null && t1.DeepEquals(t2))
{
t1 = (t1 != Last) ? t1.Next : null;
t2 = (t2 != container.Last) ? t2.Next : null;
}
else
{
return false;
}
}
while (true);
}
/// <summary>
/// Get the first child token of this token.
/// </summary>
/// <value>
/// A <see cref="JToken"/> containing the first child token of the <see cref="JToken"/>.
/// </value>
public override JToken First
{
get { return ChildrenTokens.FirstOrDefault(); }
}
/// <summary>
/// Get the last child token of this token.
/// </summary>
/// <value>
/// A <see cref="JToken"/> containing the last child token of the <see cref="JToken"/>.
/// </value>
public override JToken Last
{
get { return ChildrenTokens.LastOrDefault(); }
}
/// <summary>
/// Returns a collection of the child tokens of this token, in document order.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> containing the child tokens of this <see cref="JToken"/>, in document order.
/// </returns>
public override JEnumerable<JToken> Children()
{
return new JEnumerable<JToken>(ChildrenTokens);
}
/// <summary>
/// Returns a collection of the child values of this token, in document order.
/// </summary>
/// <typeparam name="T">The type to convert the values to.</typeparam>
/// <returns>
/// A <see cref="IEnumerable{T}"/> containing the child values of this <see cref="JToken"/>, in document order.
/// </returns>
public override IEnumerable<T> Values<T>()
{
return ChildrenTokens.Convert<JToken, T>();
}
/// <summary>
/// Returns a collection of the descendant tokens for this token in document order.
/// </summary>
/// <returns>An <see cref="IEnumerable{JToken}"/> containing the descendant tokens of the <see cref="JToken"/>.</returns>
public IEnumerable<JToken> Descendants()
{
foreach (JToken o in ChildrenTokens)
{
yield return o;
JContainer c = o as JContainer;
if (c != null)
{
foreach (JToken d in c.Descendants())
{
yield return d;
}
}
}
}
internal bool IsMultiContent(object content)
{
return (content is IEnumerable && !(content is string) && !(content is JToken) && !(content is byte[]));
}
internal JToken EnsureParentToken(JToken item)
{
if (item == null)
return new JValue((object) null);
if (item.Parent != null)
{
item = item.CloneToken();
}
else
{
// check whether attempting to add a token to itself
JContainer parent = this;
while (parent.Parent != null)
{
parent = parent.Parent;
}
if (item == parent)
{
item = item.CloneToken();
}
}
return item;
}
private class JTokenReferenceEqualityComparer : IEqualityComparer<JToken>
{
public static readonly JTokenReferenceEqualityComparer Instance = new JTokenReferenceEqualityComparer();
public bool Equals(JToken x, JToken y)
{
return ReferenceEquals(x, y);
}
public int GetHashCode(JToken obj)
{
if (obj == null)
return 0;
return obj.GetHashCode();
}
}
internal int IndexOfItem(JToken item)
{
return ChildrenTokens.IndexOf(item, JTokenReferenceEqualityComparer.Instance);
}
internal virtual void InsertItem(int index, JToken item)
{
if (index > ChildrenTokens.Count)
throw new ArgumentOutOfRangeException("index", "Index must be within the bounds of the List.");
CheckReentrancy();
item = EnsureParentToken(item);
JToken previous = (index == 0) ? null : ChildrenTokens[index - 1];
// haven't inserted new token yet so next token is still at the inserting index
JToken next = (index == ChildrenTokens.Count) ? null : ChildrenTokens[index];
ValidateToken(item, null);
item.Parent = this;
item.Previous = previous;
if (previous != null)
previous.Next = item;
item.Next = next;
if (next != null)
next.Previous = item;
ChildrenTokens.Insert(index, item);
}
internal virtual void RemoveItemAt(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException("index", "Index is less than 0.");
if (index >= ChildrenTokens.Count)
throw new ArgumentOutOfRangeException("index", "Index is equal to or greater than Count.");
CheckReentrancy();
JToken item = ChildrenTokens[index];
JToken previous = (index == 0) ? null : ChildrenTokens[index - 1];
JToken next = (index == ChildrenTokens.Count - 1) ? null : ChildrenTokens[index + 1];
if (previous != null)
previous.Next = next;
if (next != null)
next.Previous = previous;
item.Parent = null;
item.Previous = null;
item.Next = null;
//IList implementation is broken on Web Player (Unity Bug) and RemoveAt will not remove the item
#if !UNITY_WEBPLAYER
ChildrenTokens.RemoveAt(index);
#else
if(ChildrenTokens is JObject.JPropertKeyedCollection)
{
(ChildrenTokens as JObject.JPropertKeyedCollection).RemoveItemAt(index);
}
#endif
}
internal virtual bool RemoveItem(JToken item)
{
int index = IndexOfItem(item);
if (index >= 0)
{
RemoveItemAt(index);
return true;
}
return false;
}
internal virtual JToken GetItem(int index)
{
return ChildrenTokens[index];
}
internal virtual void SetItem(int index, JToken item)
{
if (index < 0)
throw new ArgumentOutOfRangeException("index", "Index is less than 0.");
if (index >= ChildrenTokens.Count)
throw new ArgumentOutOfRangeException("index", "Index is equal to or greater than Count.");
JToken existing = ChildrenTokens[index];
if (IsTokenUnchanged(existing, item))
return;
CheckReentrancy();
item = EnsureParentToken(item);
ValidateToken(item, existing);
JToken previous = (index == 0) ? null : ChildrenTokens[index - 1];
JToken next = (index == ChildrenTokens.Count - 1) ? null : ChildrenTokens[index + 1];
item.Parent = this;
item.Previous = previous;
if (previous != null)
previous.Next = item;
item.Next = next;
if (next != null)
next.Previous = item;
ChildrenTokens[index] = item;
existing.Parent = null;
existing.Previous = null;
existing.Next = null;
}
internal virtual void ClearItems()
{
CheckReentrancy();
foreach (JToken item in ChildrenTokens)
{
item.Parent = null;
item.Previous = null;
item.Next = null;
}
ChildrenTokens.Clear();
}
internal virtual void ReplaceItem(JToken existing, JToken replacement)
{
if (existing == null || existing.Parent != this)
return;
int index = IndexOfItem(existing);
SetItem(index, replacement);
}
internal virtual bool ContainsItem(JToken item)
{
return (IndexOfItem(item) != -1);
}
internal virtual void CopyItemsTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
if (arrayIndex >= array.Length)
throw new ArgumentException("arrayIndex is equal to or greater than the length of array.");
if (Count > array.Length - arrayIndex)
throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.");
int index = 0;
foreach (JToken token in ChildrenTokens)
{
array.SetValue(token, arrayIndex + index);
index++;
}
}
internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue)
{
JValue v1 = currentValue as JValue;
if (v1 != null)
{
// null will get turned into a JValue of type null
if (v1.Type == JTokenType.Null && newValue == null)
return true;
return v1.Equals(newValue);
}
return false;
}
internal virtual void ValidateToken(JToken o, JToken existing)
{
ValidationUtils.ArgumentNotNull(o, "o");
if (o.Type == JTokenType.Property)
throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType()));
}
/// <summary>
/// Adds the specified content as children of this <see cref="JToken"/>.
/// </summary>
/// <param name="content">The content to be added.</param>
public virtual void Add(object content)
{
AddInternal(ChildrenTokens.Count, content);
}
/// <summary>
/// Adds the specified content as the first children of this <see cref="JToken"/>.
/// </summary>
/// <param name="content">The content to be added.</param>
public void AddFirst(object content)
{
AddInternal(0, content);
}
internal void AddInternal(int index, object content)
{
if (IsMultiContent(content))
{
IEnumerable enumerable = (IEnumerable)content;
int multiIndex = index;
foreach (object c in enumerable)
{
AddInternal(multiIndex, c);
multiIndex++;
}
}
else
{
JToken item = CreateFromContent(content);
InsertItem(index, item);
}
}
internal JToken CreateFromContent(object content)
{
if (content is JToken)
return (JToken)content;
return new JValue(content);
}
/// <summary>
/// Creates an <see cref="JsonWriter"/> that can be used to add tokens to the <see cref="JToken"/>.
/// </summary>
/// <returns>An <see cref="JsonWriter"/> that is ready to have content written to it.</returns>
public JsonWriter CreateWriter()
{
return new JTokenWriter(this);
}
/// <summary>
/// Replaces the children nodes of this token with the specified content.
/// </summary>
/// <param name="content">The content.</param>
public void ReplaceAll(object content)
{
ClearItems();
Add(content);
}
/// <summary>
/// Removes the child nodes from this token.
/// </summary>
public void RemoveAll()
{
ClearItems();
}
internal void ReadTokenFrom(JsonReader r)
{
int startDepth = r.Depth;
if (!r.Read())
throw new Exception("Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
ReadContentFrom(r);
int endDepth = r.Depth;
if (endDepth > startDepth)
throw new Exception("Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
}
internal void ReadContentFrom(JsonReader r)
{
ValidationUtils.ArgumentNotNull(r, "r");
IJsonLineInfo lineInfo = r as IJsonLineInfo;
JContainer parent = this;
do
{
if (parent is JProperty && ((JProperty)parent).Value != null)
{
if (parent == this)
return;
parent = parent.Parent;
}
switch (r.TokenType)
{
case JsonToken.None:
// new reader. move to actual content
break;
case JsonToken.StartArray:
JArray a = new JArray();
a.SetLineInfo(lineInfo);
parent.Add(a);
parent = a;
break;
case JsonToken.EndArray:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.StartObject:
JObject o = new JObject();
o.SetLineInfo(lineInfo);
parent.Add(o);
parent = o;
break;
case JsonToken.EndObject:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.StartConstructor:
JConstructor constructor = new JConstructor(r.Value.ToString());
constructor.SetLineInfo(constructor);
parent.Add(constructor);
parent = constructor;
break;
case JsonToken.EndConstructor:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.String:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Date:
case JsonToken.Boolean:
case JsonToken.Bytes:
JValue v = new JValue(r.Value);
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.Comment:
v = JValue.CreateComment(r.Value.ToString());
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.Null:
v = new JValue(null, JTokenType.Null);
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.Undefined:
v = new JValue(null, JTokenType.Undefined);
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.PropertyName:
string propertyName = r.Value.ToString();
JProperty property = new JProperty(propertyName);
property.SetLineInfo(lineInfo);
JObject parentObject = (JObject) parent;
// handle multiple properties with the same name in JSON
JProperty existingPropertyWithName = parentObject.Property(propertyName);
if (existingPropertyWithName == null)
parent.Add(property);
else
existingPropertyWithName.Replace(property);
parent = property;
break;
default:
throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(CultureInfo.InvariantCulture, r.TokenType));
}
}
while (r.Read());
}
internal int ContentsHashCode()
{
int hashCode = 0;
foreach (JToken item in ChildrenTokens)
{
hashCode ^= item.GetDeepHashCode();
}
return hashCode;
}
#region IList<JToken> Members
int IList<JToken>.IndexOf(JToken item)
{
return IndexOfItem(item);
}
void IList<JToken>.Insert(int index, JToken item)
{
InsertItem(index, item);
}
void IList<JToken>.RemoveAt(int index)
{
RemoveItemAt(index);
}
JToken IList<JToken>.this[int index]
{
get { return GetItem(index); }
set { SetItem(index, value); }
}
#endregion
#region ICollection<JToken> Members
void ICollection<JToken>.Add(JToken item)
{
Add(item);
}
void ICollection<JToken>.Clear()
{
ClearItems();
}
bool ICollection<JToken>.Contains(JToken item)
{
return ContainsItem(item);
}
void ICollection<JToken>.CopyTo(JToken[] array, int arrayIndex)
{
CopyItemsTo(array, arrayIndex);
}
bool ICollection<JToken>.IsReadOnly
{
get { return false; }
}
bool ICollection<JToken>.Remove(JToken item)
{
return RemoveItem(item);
}
#endregion
private JToken EnsureValue(object value)
{
if (value == null)
return null;
if (value is JToken)
return (JToken) value;
throw new ArgumentException("Argument is not a JToken.");
}
#region IList Members
int IList.Add(object value)
{
Add(EnsureValue(value));
return Count - 1;
}
void IList.Clear()
{
ClearItems();
}
bool IList.Contains(object value)
{
return ContainsItem(EnsureValue(value));
}
int IList.IndexOf(object value)
{
return IndexOfItem(EnsureValue(value));
}
void IList.Insert(int index, object value)
{
InsertItem(index, EnsureValue(value));
}
bool IList.IsFixedSize
{
get { return false; }
}
bool IList.IsReadOnly
{
get { return false; }
}
void IList.Remove(object value)
{
RemoveItem(EnsureValue(value));
}
void IList.RemoveAt(int index)
{
RemoveItemAt(index);
}
object IList.this[int index]
{
get { return GetItem(index); }
set { SetItem(index, EnsureValue(value)); }
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
CopyItemsTo(array, index);
}
/// <summary>
/// Gets the count of child JSON tokens.
/// </summary>
/// <value>The count of child JSON tokens</value>
public int Count
{
get { return ChildrenTokens.Count; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
return _syncRoot;
}
}
#endregion
#region IBindingList Members
#endregion
}
}
#endif
| |
// 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.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools;
using SR = Microsoft.NodejsTools.Project.SR;
namespace Microsoft.NodejsTools.Jade
{
/// <summary>
/// Asynchronous task that start on next idle slot
/// </summary>
internal sealed class IdleTimeAsyncTask : IDisposable
{
private Func<object> _taskAction;
private Action<object> _callbackAction;
private Action<object> _cancelAction;
private bool _taskRunning = false;
private bool _connectedToIdle = false;
private long _closed = 0;
private int _delay = 0;
private DateTime _idleConnectTime;
public object Tag { get; private set; }
public IdleTimeAsyncTask()
{
}
/// <summary>
/// Asynchronous idle time task constructor
/// </summary>
/// <param name="taskAction">Task to perform in a background thread</param>
/// <param name="callbackAction">Callback to invoke when task completes</param>
/// <param name="cancelAction">Callback to invoke if task is canceled</param>
public IdleTimeAsyncTask(Func<object> taskAction, Action<object> callbackAction, Action<object> cancelAction)
: this()
{
Debug.Assert(taskAction != null);
if (taskAction == null)
throw new ArgumentNullException("taskAction");
this._taskAction = taskAction;
this._callbackAction = callbackAction;
this._cancelAction = cancelAction;
}
/// <summary>
/// Asynchronous idle time task constructor
/// </summary>
/// <param name="taskAction">Task to perform in a background thread</param>
/// <param name="callbackAction">Callback to invoke when task completes</param>
public IdleTimeAsyncTask(Func<object> taskAction, Action<object> callbackAction)
: this(taskAction, callbackAction, null)
{
}
/// <summary>
/// Asynchronous idle time task constructor
/// </summary>
/// <param name="taskAction">Task to perform in a background thread</param>
public IdleTimeAsyncTask(Func<object> taskAction)
: this(taskAction, null)
{
}
/// <summary>
/// Asynchronous idle time task constructor
/// </summary>
/// <param name="taskAction">Task to perform in a background thread</param>
/// <param name="msDelay">Milliseconds to delay before performing task on idle</param>
public IdleTimeAsyncTask(Func<object> taskAction, int msDelay)
: this(taskAction, null)
{
this._delay = msDelay;
}
public void DoTaskNow()
{
if (Interlocked.Read(ref this._closed) == 0)
DoTaskInternal();
}
/// <summary>
/// Run task on next idle slot
/// </summary>
public void DoTaskOnIdle()
{
if (this._taskAction == null)
throw new InvalidOperationException("Task action is null");
if (Interlocked.Read(ref this._closed) == 0)
ConnectToIdle();
}
/// <summary>
/// Run task on next idle slot after certain amount of milliseconds
/// </summary>
/// <param name="msDelay"></param>
public void DoTaskOnIdle(int msDelay)
{
if (this._taskAction == null)
throw new InvalidOperationException("Task action is null");
this._delay = msDelay;
if (Interlocked.Read(ref this._closed) == 0)
ConnectToIdle();
}
/// <summary>
/// Runs specified task on next idle. Task must not be currently running.
/// </summary>
/// <param name="taskAction">Task to perform in a background thread</param>
/// <param name="callbackAction">Callback to invoke when task completes</param>
/// <param name="cancelAction">Callback to invoke if task is canceled</param>
public void DoTaskOnIdle(Func<object> taskAction, Action<object> callbackAction, Action<object> cancelAction, object tag = null)
{
if (this.TaskRunning)
throw new InvalidOperationException("Task is running");
if (taskAction == null)
throw new ArgumentNullException("taskAction");
this.Tag = tag;
this._taskAction = taskAction;
this._callbackAction = callbackAction;
this._cancelAction = cancelAction;
DoTaskOnIdle();
}
public bool TaskRunning => this._connectedToIdle || this._taskRunning;
public bool TaskScheduled => this.TaskRunning;
private void DoTaskInternal()
{
if (!this._taskRunning)
{
this._taskRunning = true;
Task.Factory.StartNew(() =>
{
if (Interlocked.Read(ref this._closed) == 0)
{
object result = null;
try
{
result = this._taskAction();
}
catch (Exception ex)
{
Debug.Fail(
string.Format(CultureInfo.CurrentCulture, "Background task exception {0}. Inner exception: {1}",
ex.Message,
ex.InnerException != null ? ex.InnerException.Message : "(none)")
);
result = ex;
}
finally
{
NodejsPackage.Instance.GetUIThread().InvokeAsync(() => UIThreadCompletedCallback(result))
.HandleAllExceptions(SR.ProductName)
.DoNotWait();
}
}
else if (Interlocked.Read(ref this._closed) > 0)
{
NodejsPackage.Instance.GetUIThread().InvokeAsync((() => UIThreadCanceledCallback(null)))
.HandleAllExceptions(SR.ProductName)
.DoNotWait();
}
});
}
}
private void UIThreadCompletedCallback(object result)
{
try
{
if (this._callbackAction != null && Interlocked.Read(ref this._closed) == 0)
{
this._callbackAction(result);
}
}
catch (Exception ex)
{
Debug.Fail(
string.Format(CultureInfo.CurrentCulture, "Background task UI thread callback exception {0}. Inner exception: {1}",
ex.Message, ex.InnerException != null ? ex.InnerException.Message : "(none)"));
}
this._taskRunning = false;
}
private void UIThreadCanceledCallback(object result)
{
if (this._cancelAction != null && Interlocked.Read(ref this._closed) > 0)
{
this._cancelAction(result);
}
this._taskRunning = false;
}
private void OnIdle(object sender, EventArgs e)
{
if (this._delay == 0 || TimeUtility.MillisecondsSince(this._idleConnectTime) > this._delay)
{
DoTaskInternal();
DisconnectFromIdle();
}
}
private void ConnectToIdle()
{
if (!this._connectedToIdle)
{
this._connectedToIdle = true;
this._idleConnectTime = DateTime.Now;
// make sure our package is loaded so we can use its
// OnIdle event
var nodePackage = new Guid(Guids.NodejsPackageString);
IVsPackage package;
var shell = (IVsShell)NodejsPackage.GetGlobalService(typeof(SVsShell));
shell.LoadPackage(ref nodePackage, out package);
NodejsPackage.Instance.OnIdle += this.OnIdle;
}
}
private void DisconnectFromIdle()
{
if (this._connectedToIdle)
{
this._connectedToIdle = false;
NodejsPackage.Instance.OnIdle -= this.OnIdle;
}
}
#region IDisposable
public void Dispose()
{
DisconnectFromIdle();
Interlocked.Exchange(ref this._closed, 1);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BaseResourcesBuildProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Compilation {
using System;
using System.Resources;
using System.Resources.Tools;
using System.Reflection;
using System.Globalization;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Compilation;
using System.Web.UI;
using System.Web.Util;
using Util=System.Web.UI.Util;
/// Base class for BuildProviders that generate resources
[BuildProviderAppliesTo(BuildProviderAppliesTo.Resources)]
internal abstract class BaseResourcesBuildProvider : BuildProvider {
internal const string DefaultResourcesNamespace = "Resources";
// The generated namespace and type name
private string _ns;
private string _typeName;
private string _cultureName;
private bool _dontGenerateStronglyTypedClass;
internal void DontGenerateStronglyTypedClass() {
_dontGenerateStronglyTypedClass = true;
}
public override void GenerateCode(AssemblyBuilder assemblyBuilder) {
_cultureName = GetCultureName();
if (!_dontGenerateStronglyTypedClass) {
// Get the namespace and type name that we will use
_ns = Util.GetNamespaceAndTypeNameFromVirtualPath(VirtualPathObject,
(_cultureName == null) ? 1 : 2 /*chunksToIgnore*/, out _typeName);
// Always prepend the namespace with Resources.
if (_ns.Length == 0)
_ns = DefaultResourcesNamespace;
else
_ns = DefaultResourcesNamespace + "." + _ns;
}
// Get an input stream for our virtual path, and get a resource reader from it
using (Stream inputStream = OpenStream()) {
IResourceReader reader = GetResourceReader(inputStream);
try {
GenerateResourceFile(assemblyBuilder, reader);
}
catch (ArgumentException e) {
// If the inner exception is Xml, throw that instead, as it contains more
// useful info
if (e.InnerException != null &&
(e.InnerException is XmlException || e.InnerException is XmlSchemaException)) {
throw e.InnerException;
}
// Otherwise, so just rethrow
throw;
}
// Skip the code part for satellite assemblies, or if dontGenerate is set
if (_cultureName == null && !_dontGenerateStronglyTypedClass)
GenerateStronglyTypedClass(assemblyBuilder, reader);
}
}
protected abstract IResourceReader GetResourceReader(Stream inputStream);
private void GenerateResourceFile(AssemblyBuilder assemblyBuilder, IResourceReader reader) {
// Get the name of the generated .resource file
string resourceFileName;
if (_ns == null) {
// In the case where we don't generate code, just name the resource file
// after the virtual file
resourceFileName = UrlPath.GetFileNameWithoutExtension(VirtualPath) + ".resources";
}
else if (_cultureName == null) {
// Name the resource file after the generated class, since that's what the
// generated class expects
resourceFileName = _ns + "." + _typeName + ".resources";
}
else {
// If it's a non-default resource, include the culture in the name
resourceFileName = _ns + "." + _typeName + "." + _cultureName + ".resources";
}
// Make it lower case, since GetManifestResourceStream (which we use later on) is
// case sensitive
resourceFileName = resourceFileName.ToLower(CultureInfo.InvariantCulture);
Stream outputStream = null;
try {
try {
try {
}
finally {
// Put the assignment in a finally block to avoid a ThreadAbortException from
// causing the created stream to not get assigned and become leaked (Dev10 bug 844463)
outputStream = assemblyBuilder.CreateEmbeddedResource(this, resourceFileName);
}
}
catch (ArgumentException) {
// This throws an ArgumentException if the resource file name was already added.
// Catch the situation, and give a better error message (VSWhidbey 87110)
throw new HttpException(SR.GetString(SR.Duplicate_Resource_File, VirtualPath));
}
// Create an output stream from the .resource file
using (outputStream) {
using (ResourceWriter writer = new ResourceWriter(outputStream)) {
// Enable resource writer to be target-aware
writer.TypeNameConverter = System.Web.UI.TargetFrameworkUtil.TypeNameConverter;
// Copy the resources
foreach (DictionaryEntry de in reader) {
writer.AddResource((string)de.Key, de.Value);
}
}
}
}
finally {
// Always close the stream to avoid a ThreadAbortException from causing the stream
// to be leaked (Dev10 bug 844463)
if (outputStream != null) {
outputStream.Close();
}
}
}
private void GenerateStronglyTypedClass(AssemblyBuilder assemblyBuilder, IResourceReader reader) {
// Copy the resources into an IDictionary
IDictionary resourceList;
using (reader) {
resourceList = GetResourceList(reader);
}
// Generate a strongly typed class from the resources
CodeDomProvider provider = assemblyBuilder.CodeDomProvider;
string[] unmatchable;
CodeCompileUnit ccu = StronglyTypedResourceBuilder.Create(
resourceList, _typeName, _ns,
provider, false /*internalClass*/, out unmatchable);
// Ignore the unmatchable items. We just won't generate code for them,
// but they'll still be usable via the ResourceManager (VSWhidbey 248226)
// We decided to cut support for My.Resources (VSWhidbey 358088)
#if OLD
// generate a My.Resources.* override (VSWhidbey 251554)
CodeNamespace ns = new CodeNamespace();
ns.Name = "My." + _ns;
CodeTypeDeclaration type = new CodeTypeDeclaration();
type.Name = _typeName;
CodeTypeReference baseType = new CodeTypeReference(_ns + "." + _typeName);
// Need to use a global reference to avoid a conflict, since the classes have the same name
baseType.Options = CodeTypeReferenceOptions.GlobalReference;
type.BaseTypes.Add(baseType);
ns.Types.Add(type);
ccu.Namespaces.Add(ns);
#endif
// Add the code compile unit to the compilation
assemblyBuilder.AddCodeCompileUnit(this, ccu);
}
private IDictionary GetResourceList(IResourceReader reader) {
// Read the resources into a dictionary.
IDictionary resourceList = new Hashtable(StringComparer.OrdinalIgnoreCase);
foreach(DictionaryEntry de in reader)
resourceList.Add(de.Key, de.Value);
return resourceList;
}
}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium
{
[TestFixture]
public class AlertsTest : DriverTestFixture
{
[Test]
public void ShouldBeAbleToOverrideTheWindowAlertMethod()
{
driver.Url = CreateAlertPage("cheese");
((IJavaScriptExecutor)driver).ExecuteScript(
"window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }");
driver.FindElement(By.Id("alert")).Click();
}
[Test]
[IgnoreBrowser(Browser.Edge, "Issue getting alert text in Edge driver")]
public void ShouldAllowUsersToAcceptAnAlertManually()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void ShouldThrowArgumentNullExceptionWhenKeysNull()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
Assert.That(() => alert.SendKeys(null), Throws.ArgumentNullException);
}
finally
{
alert.Accept();
}
}
[Test]
[IgnoreBrowser(Browser.Edge, "Issue getting alert text in Edge driver")]
public void ShouldAllowUsersToAcceptAnAlertWithNoTextManually()
{
driver.Url = CreateAlertPage("");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.IE, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
[IgnoreBrowser(Browser.Chrome, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
[IgnoreBrowser(Browser.Edge, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
public void ShouldGetTextOfAlertOpenedInSetTimeout()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithScripts(
"function slowAlert() { window.setTimeout(function(){ alert('Slow'); }, 200); }")
.WithBody(
"<a href='#' id='slow-alert' onclick='slowAlert();'>click me</a>"));
driver.FindElement(By.Id("slow-alert")).Click();
// DO NOT WAIT OR SLEEP HERE.
// This is a regression test for a bug where only the first switchTo call would throw,
// and only if it happens before the alert actually loads.
IAlert alert = driver.SwitchTo().Alert();
try
{
Assert.AreEqual("Slow", alert.Text);
}
finally
{
alert.Accept();
}
}
[Test]
[IgnoreBrowser(Browser.Edge, "Issue getting alert text in Edge driver")]
public void ShouldAllowUsersToDismissAnAlertManually()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.Edge, "Driver does not properly handle prompt() dialogs.")]
public void ShouldAllowAUserToAcceptAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Prompt", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.Edge, "Driver does not properly handle prompt() dialogs.")]
public void ShouldAllowAUserToDismissAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Prompt", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.Edge, "Driver does not properly handle prompt() dialogs.")]
public void ShouldAllowAUserToSetTheValueOfAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.SendKeys("cheese");
alert.Accept();
string result = driver.FindElement(By.Id("text")).Text;
Assert.AreEqual("cheese", result);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome does not throw when setting the text of an alert")]
[IgnoreBrowser(Browser.Edge, "Setting value of alert hangs Edge.")]
public void SettingTheValueOfAnAlertThrows()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
alert.SendKeys("cheese");
Assert.Fail("Expected exception");
}
catch (ElementNotInteractableException)
{
}
finally
{
alert.Accept();
}
}
[Test]
[IgnoreBrowser(Browser.Edge, "Driver does not properly get text of alert.")]
public void ShouldAllowTheUserToGetTheTextOfAnAlert()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("cheese", value);
}
[Test]
[IgnoreBrowser(Browser.Edge, "Driver does not properly handle prompt() dialogs.")]
public void ShouldAllowTheUserToGetTheTextOfAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("Enter something", value);
}
[Test]
public void AlertShouldNotAllowAdditionalCommandsIfDimissed()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
string text;
Assert.That(() => text = alert.Text, Throws.InstanceOf<NoAlertPresentException>());
}
[Test]
public void ShouldAllowUsersToAcceptAnAlertInAFrame()
{
string iframe = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody("<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click me</a>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithBody(String.Format("<iframe src='{0}' name='iframeWithAlert'></iframe>", iframe)));
driver.SwitchTo().Frame("iframeWithAlert");
driver.FindElement(By.Id("alertInFrame")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void ShouldAllowUsersToAcceptAnAlertInANestedFrame()
{
string iframe = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody("<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click me</a>"));
string iframe2 = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format("<iframe src='{0}' name='iframeWithAlert'></iframe>", iframe)));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithBody(string.Format("<iframe src='{0}' name='iframeWithIframe'></iframe>", iframe2)));
driver.SwitchTo().Frame("iframeWithIframe").SwitchTo().Frame("iframeWithAlert");
driver.FindElement(By.Id("alertInFrame")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void SwitchingToMissingAlertThrows()
{
driver.Url = CreateAlertPage("cheese");
Assert.That(() => AlertToBePresent(), Throws.InstanceOf<NoAlertPresentException>());
}
[Test]
public void SwitchingToMissingAlertInAClosedWindowThrows()
{
string blank = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage());
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(String.Format(
"<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", blank)));
string mainWindow = driver.CurrentWindowHandle;
try
{
driver.FindElement(By.Id("open-new-window")).Click();
WaitFor(WindowHandleCountToBe(2), "Window count was not 2");
WaitFor(WindowWithName("newwindow"), "Could not find window with name 'newwindow'");
driver.Close();
WaitFor(WindowHandleCountToBe(1), "Window count was not 1");
try
{
AlertToBePresent().Accept();
Assert.Fail("Expected exception");
}
catch (NoSuchWindowException)
{
// Expected
}
}
finally
{
driver.SwitchTo().Window(mainWindow);
WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text 'open new window'");
}
}
[Test]
[IgnoreBrowser(Browser.Edge, "Driver does not properly handle prompt() dialogs.")]
public void PromptShouldUseDefaultValueIfNoKeysSent()
{
driver.Url = CreatePromptPage("This is a default value");
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
IWebElement element = driver.FindElement(By.Id("text"));
WaitFor(ElementTextToEqual(element, "This is a default value"), "Element text was not 'This is a default value'");
Assert.AreEqual("This is a default value", element.Text);
}
[Test]
public void PromptShouldHaveNullValueIfDismissed()
{
driver.Url = CreatePromptPage("This is a default value");
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
IWebElement element = driver.FindElement(By.Id("text"));
WaitFor(ElementTextToEqual(element, "null"), "Element text was not 'null'");
Assert.AreEqual("null", element.Text);
}
[Test]
[IgnoreBrowser(Browser.Remote)]
[IgnoreBrowser(Browser.Edge, "Driver does not properly handle prompt() dialogs.")]
public void HandlesTwoAlertsFromOneInteraction()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithScripts(
"function setInnerText(id, value) {",
" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",
"}",
"function displayTwoPrompts() {",
" setInnerText('text1', prompt('First'));",
" setInnerText('text2', prompt('Second'));",
"}")
.WithBody(
"<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>",
"<div id='text1'></div>",
"<div id='text2'></div>"));
driver.FindElement(By.Id("double-prompt")).Click();
IAlert alert1 = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert1.SendKeys("brie");
alert1.Accept();
IAlert alert2 = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert2.SendKeys("cheddar");
alert2.Accept();
IWebElement element1 = driver.FindElement(By.Id("text1"));
WaitFor(ElementTextToEqual(element1, "brie"), "Element text was not 'brie'");
Assert.AreEqual("brie", element1.Text);
IWebElement element2 = driver.FindElement(By.Id("text2"));
WaitFor(ElementTextToEqual(element2, "cheddar"), "Element text was not 'cheddar'");
Assert.AreEqual("cheddar", element2.Text);
}
[Test]
public void ShouldHandleAlertOnPageLoad()
{
string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnLoad("javascript:alert(\"onload\")")
.WithBody("<p>Page with onload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format("<a id='open-page-with-onload-alert' href='{0}'>open new page</a>", pageWithOnLoad)));
driver.FindElement(By.Id("open-page-with-onload-alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onload", value);
IWebElement element = driver.FindElement(By.TagName("p"));
WaitFor(ElementTextToEqual(element, "Page with onload event handler"), "Element text was not 'Page with onload event handler'");
}
[Test]
[IgnoreBrowser(Browser.Edge, "Alert during onload hangs browser when page loaded via direct navigation.")]
public void ShouldHandleAlertOnPageLoadUsingGet()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnLoad("javascript:alert(\"onload\")")
.WithBody("<p>Page with onload event handler</p>"));
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onload", value);
WaitFor(ElementTextToEqual(driver.FindElement(By.TagName("p")), "Page with onload event handler"), "Could not find element with text 'Page with onload event handler'");
}
[Test]
[IgnoreBrowser(Browser.Firefox, "Firefox waits too long, may be hangs")]
[IgnoreBrowser(Browser.Chrome, "Test with onLoad alert hangs Chrome.")]
[IgnoreBrowser(Browser.Safari, "Safari driver does not allow commands in any window when an alert is active")]
public void ShouldNotHandleAlertInAnotherWindow()
{
string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnLoad("javascript:alert(\"onload\")")
.WithBody("<p>Page with onload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format(
"<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", pageWithOnLoad)));
string mainWindow = driver.CurrentWindowHandle;
string onloadWindow = null;
try
{
driver.FindElement(By.Id("open-new-window")).Click();
List<String> allWindows = new List<string>(driver.WindowHandles);
allWindows.Remove(mainWindow);
Assert.AreEqual(1, allWindows.Count);
onloadWindow = allWindows[0];
try
{
IWebElement el = driver.FindElement(By.Id("open-new-window"));
WaitFor<IAlert>(AlertToBePresent, TimeSpan.FromSeconds(5), "No alert found");
Assert.Fail("Expected exception");
}
catch (WebDriverException)
{
// An operation timed out exception is expected,
// since we're using WaitFor<T>.
}
}
finally
{
driver.SwitchTo().Window(onloadWindow);
WaitFor<IAlert>(AlertToBePresent, "No alert found").Dismiss();
driver.Close();
driver.SwitchTo().Window(mainWindow);
WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text 'open new window'");
}
}
[Test]
[IgnoreBrowser(Browser.Firefox, "After version 27, Firefox does not trigger alerts on unload.")]
[IgnoreBrowser(Browser.Chrome, "Chrome does not trigger alerts on unload.")]
public void ShouldHandleAlertOnPageUnload()
{
string pageWithOnBeforeUnload = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnBeforeUnload("return \"onunload\";")
.WithBody("<p>Page with onbeforeunload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format("<a id='open-page-with-onunload-alert' href='{0}'>open new page</a>", pageWithOnBeforeUnload)));
IWebElement element = WaitFor<IWebElement>(ElementToBePresent(By.Id("open-page-with-onunload-alert")), "Could not find element with id 'open-page-with-onunload-alert'");
element.Click();
driver.Navigate().Back();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onunload", value);
element = WaitFor<IWebElement>(ElementToBePresent(By.Id("open-page-with-onunload-alert")), "Could not find element with id 'open-page-with-onunload-alert'");
WaitFor(ElementTextToEqual(element, "open new page"), "Element text was not 'open new page'");
}
[Test]
[IgnoreBrowser(Browser.Firefox, "After version 27, Firefox does not trigger alerts on unload.")]
[IgnoreBrowser(Browser.Chrome, "Chrome does not implicitly handle onBeforeUnload alert")]
[IgnoreBrowser(Browser.Safari, "Safari driver does not implicitly (or otherwise) handle onBeforeUnload alerts")]
[IgnoreBrowser(Browser.Edge, "Edge driver does not implicitly (or otherwise) handle onBeforeUnload alerts")]
public void ShouldImplicitlyHandleAlertOnPageBeforeUnload()
{
string blank = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage().WithTitle("Success"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Page with onbeforeunload handler")
.WithBody(String.Format(
"<a id='link' href='{0}'>Click here to navigate to another page.</a>", blank)));
SetSimpleOnBeforeUnload("onbeforeunload message");
driver.FindElement(By.Id("link")).Click();
WaitFor(() => driver.Title == "Success", "Title was not 'Success'");
}
[Test]
[IgnoreBrowser(Browser.IE, "Test as written does not trigger alert; also onbeforeunload alert on close will hang browser")]
[IgnoreBrowser(Browser.Chrome, "Test as written does not trigger alert")]
[IgnoreBrowser(Browser.Firefox, "After version 27, Firefox does not trigger alerts on unload.")]
public void ShouldHandleAlertOnWindowClose()
{
string pageWithOnBeforeUnload = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnBeforeUnload("javascript:alert(\"onbeforeunload\")")
.WithBody("<p>Page with onbeforeunload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format(
"<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", pageWithOnBeforeUnload)));
string mainWindow = driver.CurrentWindowHandle;
try
{
driver.FindElement(By.Id("open-new-window")).Click();
WaitFor(WindowHandleCountToBe(2), "Window count was not 2");
WaitFor(WindowWithName("newwindow"), "Could not find window with name 'newwindow'");
driver.Close();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onbeforeunload", value);
}
finally
{
driver.SwitchTo().Window(mainWindow);
WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text equal to 'open new window'");
}
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome does not supply text in UnhandledAlertException")]
[IgnoreBrowser(Browser.Edge)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Safari, "Safari driver does not do unhandled alerts")]
public void IncludesAlertTextInUnhandledAlertException()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
string title = driver.Title;
Assert.Fail("Expected UnhandledAlertException");
}
catch (UnhandledAlertException e)
{
Assert.AreEqual("cheese", e.AlertText);
}
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
[IgnoreBrowser(Browser.Opera)]
public void CanQuitWhenAnAlertIsPresent()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
EnvironmentManager.Instance.CloseCurrentDriver();
}
[Test]
[IgnoreBrowser(Browser.Firefox, "Dismissing alert causes entire window to close.")]
[IgnoreBrowser(Browser.Safari, "Safari driver cannot handle alert thrown via JavaScript")]
public void ShouldHandleAlertOnFormSubmit()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts").
WithBody("<form id='theForm' action='javascript:alert(\"Tasty cheese\");'>",
"<input id='unused' type='submit' value='Submit'>",
"</form>"));
IWebElement element = driver.FindElement(By.Id("theForm"));
element.Submit();
IAlert alert = driver.SwitchTo().Alert();
string text = alert.Text;
alert.Accept();
Assert.AreEqual("Tasty cheese", text);
Assert.AreEqual("Testing Alerts", driver.Title);
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
[IgnoreBrowser(Browser.Safari, "onBeforeUnload dialogs hang Safari")]
[IgnoreBrowser(Browser.Edge, "onBeforeUnload dialogs hang Edge")]
public void ShouldHandleAlertOnPageBeforeUnload()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("pageWithOnBeforeUnloadMessage.html");
IWebElement element = driver.FindElement(By.Id("navigate"));
element.Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
Assert.That(driver.Url, Does.Contain("pageWithOnBeforeUnloadMessage.html"));
// Can't move forward or even quit the driver
// until the alert is accepted.
element.Click();
alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
WaitFor(() => { return driver.Url.Contains(alertsPage); }, "Browser URL does not contain " + alertsPage);
Assert.That(driver.Url, Does.Contain(alertsPage));
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
[IgnoreBrowser(Browser.Safari, "onBeforeUnload dialogs hang Safari")]
public void ShouldHandleAlertOnPageBeforeUnloadAlertAtQuit()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("pageWithOnBeforeUnloadMessage.html");
IWebElement element = driver.FindElement(By.Id("navigate"));
element.Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
driver.Quit();
driver = null;
}
// Disabling test for all browsers. Authentication API is not supported by any driver yet.
// [Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.Edge)]
[IgnoreBrowser(Browser.Firefox)]
[IgnoreBrowser(Browser.IE)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Remote)]
[IgnoreBrowser(Browser.Safari)]
public void ShouldBeAbleToHandleAuthenticationDialog()
{
driver.Url = authenticationPage;
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.SetAuthenticationCredentials("test", "test");
alert.Accept();
Assert.That(driver.FindElement(By.TagName("h1")).Text, Does.Contain("authorized"));
}
// Disabling test for all browsers. Authentication API is not supported by any driver yet.
// [Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.Edge)]
[IgnoreBrowser(Browser.Firefox)]
[IgnoreBrowser(Browser.IE)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Remote)]
[IgnoreBrowser(Browser.Safari)]
public void ShouldBeAbleToDismissAuthenticationDialog()
{
driver.Url = authenticationPage;
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
}
// Disabling test for all browsers. Authentication API is not supported by any driver yet.
// [Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.Edge)]
[IgnoreBrowser(Browser.Firefox)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Remote)]
[IgnoreBrowser(Browser.Safari)]
public void ShouldThrowAuthenticatingOnStandardAlert()
{
driver.Url = alertsPage;
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
alert.SetAuthenticationCredentials("test", "test");
Assert.Fail("Should not be able to Authenticate");
}
catch (UnhandledAlertException)
{
// this is an expected exception
}
// but the next call should be good.
alert.Dismiss();
}
private IAlert AlertToBePresent()
{
return driver.SwitchTo().Alert();
}
private string CreateAlertPage(string alertText)
{
return EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithBody("<a href='#' id='alert' onclick='alert(\"" + alertText + "\");'>click me</a>"));
}
private string CreatePromptPage(string defaultText)
{
return EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Prompt")
.WithScripts(
"function setInnerText(id, value) {",
" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",
"}",
defaultText == null
? "function displayPrompt() { setInnerText('text', prompt('Enter something')); }"
: "function displayPrompt() { setInnerText('text', prompt('Enter something', '" + defaultText + "')); }")
.WithBody(
"<a href='#' id='prompt' onclick='displayPrompt();'>click me</a>",
"<div id='text'>acceptor</div>"));
}
private void SetSimpleOnBeforeUnload(string returnText)
{
((IJavaScriptExecutor)driver).ExecuteScript(
"var returnText = arguments[0]; window.onbeforeunload = function() { return returnText; }",
returnText);
}
private Func<IWebElement> ElementToBePresent(By locator)
{
return () =>
{
IWebElement foundElement = null;
try
{
foundElement = driver.FindElement(By.Id("open-page-with-onunload-alert"));
}
catch (NoSuchElementException)
{
}
return foundElement;
};
}
private Func<bool> ElementTextToEqual(IWebElement element, string text)
{
return () =>
{
return element.Text == text;
};
}
private Func<bool> WindowWithName(string name)
{
return () =>
{
try
{
driver.SwitchTo().Window(name);
return true;
}
catch (NoSuchWindowException)
{
}
return false;
};
}
private Func<bool> WindowHandleCountToBe(int count)
{
return () =>
{
return driver.WindowHandles.Count == count;
};
}
}
}
| |
namespace Reverb.Data.Migrations
{
using Contracts;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
public sealed class Configuration : DbMigrationsConfiguration<ReverbDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = false;
this.AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(ReverbDbContext context)
{
// TODO: Seed database with music
this.SeedAdmin(context);
this.SeedSongs(context);
}
private void SeedSongs(ReverbDbContext context)
{
const string artistName1 = "Disturbed";
const string artistName2 = "Pentakill";
const string artistName3 = "Godsmack";
const string artistName4 = "Rise Against";
const string artistName5 = "Angel Vivaldi";
const string genre1 = "Heavy Metal";
const string genre2 = "Power Metal";
const string genre3 = "Hard Rock";
const string genre4 = "Punk Rock";
const string genre5 = "Instrumental Rock";
const string album1 = "Immortalized";
const string cover1 = "http://inyourspeakers.com/files/images/reviews/disturbed-immortalizedjpg-16148.jpeg";
const string song11 = "Immortalized";
const string song12 = "The Vengeful One";
const string song13 = "The Sound of Silence";
const string song14 = "You're Mine";
const string video11 = "https://www.youtube.com/embed/Auuqlcom6tM";
const string video12 = "https://www.youtube.com/embed/8nW-IPrzM1g";
const string video13 = "https://www.youtube.com/embed/u9Dg-g7t2l4";
const string video14 = "https://www.youtube.com/embed/vka6wPrB4E0";
const string album2 = "Grasp of the Undying";
const string cover2 = "https://allthatshreds.com/wp-content/uploads/2017/08/Pentakill-II-art.jpg";
const string song21 = "Mortal Reminder";
const string song22 = "Frozen Heart";
const string song23 = "Tear of the Goddess";
const string song24 = "The Bloodthirster";
const string song25 = "Deadman's Plate";
const string video21 = "https://www.youtube.com/embed/1UeMVfHN2P8";
const string video22 = "https://www.youtube.com/embed/QJRLhRhcfgs";
const string video23 = "https://www.youtube.com/embed/btSlfXILTkU";
const string video24 = "https://www.youtube.com/embed/KBq_KtuSIF0";
const string video25 = "https://www.youtube.com/embed/9ASxLLTu1ZY";
const string album3 = "Faceless";
const string cover3 = "https://i.pinimg.com/originals/a7/ef/54/a7ef54ea1ae678e6b1c8d1b8c7da1b8d.jpg";
const string song31 = "I Stand Alone";
const string song32 = "Straight Out of Line";
const string video31 = "https://www.youtube.com/embed/OYjZK_6i37M";
const string video32 = "https://www.youtube.com/embed/z9FmOc0ofGc";
const string album4 = "The Sufferer the Witness";
const string cover4 = "https://www.music-bazaar.com/album-images/vol1/62/62341/287918-big/The-Sufferer-And-The-Witness-cover.jpg";
const string song41 = "Prayer of the Refugee";
const string song42 = "Drones";
const string song43 = "The Good Left Undones";
const string video41 = "https://www.youtube.com/embed/9-SQGOYOjxs";
const string video42 = "https://www.youtube.com/embed/94vo6NzQD5c";
const string video43 = "https://www.youtube.com/embed/70hIRnj9kf8";
const string album5 = "Universal Language";
const string cover5 = "https://f4.bcbits.com/img/a2941452586_10.jpg";
const string song51 = "A Venutian Spring";
const string song52 = "A Mercurian Summer";
const string song53 = "An Erisian Autumn";
const string song54 = "A Martian Winter";
const string video51 = "https://www.youtube.com/embed/hwPsSdAQCHY";
const string video52 = "https://www.youtube.com/embed/uZLtzchX32c";
const string video53 = "https://www.youtube.com/embed/86y0vYWDmm4";
const string video54 = "https://www.youtube.com/embed/qFWoIyqSjlA";
int? duration = 246;
const string lyrics = "Comming soon";
if (!context.Songs.Any())
{
var artist1 = new Artist()
{
Name = artistName1
};
var artist2 = new Artist()
{
Name = artistName2
};
var artist3 = new Artist()
{
Name = artistName3
};
var artist4 = new Artist()
{
Name = artistName4
};
var artist5 = new Artist()
{
Name = artistName5
};
context.Artists.Add(artist1);
context.Artists.Add(artist2);
context.Artists.Add(artist3);
context.Artists.Add(artist4);
context.Artists.Add(artist5);
var newGenre1 = new Genre()
{
Name = genre1
};
var newGenre2 = new Genre()
{
Name = genre2
};
var newGenre3 = new Genre()
{
Name = genre3
};
var newGenre4 = new Genre()
{
Name = genre4
};
var newGenre5 = new Genre()
{
Name = genre5
};
context.Genres.Add(newGenre1);
context.Genres.Add(newGenre2);
context.Genres.Add(newGenre3);
context.Genres.Add(newGenre4);
context.Genres.Add(newGenre5);
var newAlbum1 = new Album()
{
Title = album1,
Artist = artist1,
CoverUrl = cover1
};
var newAlbum2 = new Album()
{
Title = album2,
Artist = artist2,
CoverUrl = cover2
};
var newAlbum3 = new Album()
{
Title = album3,
Artist = artist3,
CoverUrl = cover3
};
var newAlbum4 = new Album()
{
Title = album4,
Artist = artist4,
CoverUrl = cover4
};
var newAlbum5 = new Album()
{
Title = album5,
Artist = artist5,
CoverUrl = cover5
};
context.Albums.Add(newAlbum1);
context.Albums.Add(newAlbum2);
context.Albums.Add(newAlbum3);
context.Albums.Add(newAlbum4);
context.Albums.Add(newAlbum5);
var newSong11 = new Song()
{
Title = song11,
Album = newAlbum1,
Artist = artist1,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre1
},
VideoUrl = video11
};
var newSong12 = new Song()
{
Title = song12,
Album = newAlbum1,
Artist = artist1,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre1
},
VideoUrl = video12
};
var newSong13 = new Song()
{
Title = song13,
Album = newAlbum1,
Artist = artist1,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre1
},
VideoUrl = video13
};
var newSong14 = new Song()
{
Title = song14,
Album = newAlbum1,
Artist = artist1,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre1
},
VideoUrl = video14
};
var newSong21 = new Song()
{
Title = song21,
Album = newAlbum2,
Artist = artist2,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre2
},
VideoUrl = video21
};
var newSong22 = new Song()
{
Title = song22,
Album = newAlbum2,
Artist = artist2,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre2
},
VideoUrl = video22
};
var newSong23 = new Song()
{
Title = song23,
Album = newAlbum2,
Artist = artist2,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre2
},
VideoUrl = video23
};
var newSong24 = new Song()
{
Title = song24,
Album = newAlbum2,
Artist = artist2,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre2
},
VideoUrl = video24
};
var newSong25 = new Song()
{
Title = song25,
Album = newAlbum2,
Artist = artist2,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre2
},
VideoUrl = video25
};
var newSong31 = new Song()
{
Title = song31,
Album = newAlbum3,
Artist = artist3,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre3
},
VideoUrl = video31
};
var newSong32 = new Song()
{
Title = song32,
Album = newAlbum3,
Artist = artist3,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre3
},
VideoUrl = video32
};
var newSong41 = new Song()
{
Title = song41,
Album = newAlbum4,
Artist = artist4,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre4
},
VideoUrl = video41
};
var newSong42 = new Song()
{
Title = song42,
Album = newAlbum4,
Artist = artist4,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre4
},
VideoUrl = video42
};
var newSong43 = new Song()
{
Title = song43,
Album = newAlbum4,
Artist = artist4,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre4
},
VideoUrl = video43
};
var newSong51 = new Song()
{
Title = song51,
Album = newAlbum5,
Artist = artist5,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre5
},
VideoUrl = video51
};
var newSong52 = new Song()
{
Title = song52,
Album = newAlbum5,
Artist = artist5,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre5
},
VideoUrl = video52
};
var newSong53 = new Song()
{
Title = song53,
Album = newAlbum5,
Artist = artist5,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre5
},
VideoUrl = video53
};
var newSong54 = new Song()
{
Title = song54,
Album = newAlbum5,
Artist = artist5,
Duration = duration,
Lyrics = lyrics,
Genres = new HashSet<Genre>()
{
newGenre5
},
VideoUrl = video54
};
context.Songs.Add(newSong11);
context.Songs.Add(newSong12);
context.Songs.Add(newSong13);
context.Songs.Add(newSong14);
context.Songs.Add(newSong21);
context.Songs.Add(newSong22);
context.Songs.Add(newSong23);
context.Songs.Add(newSong24);
context.Songs.Add(newSong25);
context.Songs.Add(newSong31);
context.Songs.Add(newSong32);
context.Songs.Add(newSong41);
context.Songs.Add(newSong42);
context.Songs.Add(newSong43);
context.Songs.Add(newSong51);
context.Songs.Add(newSong52);
context.Songs.Add(newSong53);
context.Songs.Add(newSong54);
context.SaveChanges();
}
}
private void SeedAdmin(ReverbDbContext context)
{
const string AdminUserName = "admin@mail.bg";
const string AdminPassword = "asdasd";
const string RegualarUserName = "pesho@mail.bg";
const string RegularPassword = "asdasd";
if (!context.Roles.Any())
{
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var role = new IdentityRole { Name = "Admin" };
var role2 = new IdentityRole { Name = "User" };
roleManager.Create(role);
roleManager.Create(role2);
var userStore = new UserStore<User>(context);
var userManager = new UserManager<User>(userStore);
var user = new User
{
UserName = AdminUserName,
Email = AdminUserName,
EmailConfirmed = true,
CreatedOn = DateTime.Now
};
var user2 = new User
{
UserName = RegualarUserName,
Email = RegualarUserName,
EmailConfirmed = true,
CreatedOn = DateTime.Now
};
userManager.Create(user, AdminPassword);
userManager.AddToRole(user.Id, "Admin");
userManager.Create(user2, RegularPassword);
userManager.AddToRole(user2.Id, "User");
}
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using FeedBuilder.Properties;
namespace FeedBuilder
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
#region " Private constants/variables"
private const string DialogFilter = "Feed configuration files (*.config)|*.config|All files (*.*)|*.*";
private const string DefaultFileName = "FeedBuilder.config";
private OpenFileDialog _openDialog;
#endregion
private ArgumentsParser _argParser;
#region " Properties"
public string FileName { get; set; }
public bool ShowGui { get; set; }
#endregion
#region " Loading/Initialization/Lifetime"
private void frmMain_Load(Object sender, EventArgs e)
{
Visible = false;
InitializeFormSettings();
string[] args = Environment.GetCommandLineArgs();
// The first arg is the path to ourself
//If args.Count >= 2 Then
// If File.Exists(args(1)) Then
// Dim p As New FeedBuilderSettingsProvider()
// p.LoadFrom(args(1))
// Me.FileName = args(1)
// End If
//End If
// The first arg is the path to ourself
_argParser = new ArgumentsParser(args);
if (!_argParser.HasArgs) return;
FileName = _argParser.FileName;
if (!string.IsNullOrEmpty(FileName)) {
if (File.Exists(FileName)) {
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.LoadFrom(FileName);
} else {
_argParser.ShowGui = true;
_argParser.Build = false;
FileName = _argParser.FileName;
UpdateTitle();
}
}
if (_argParser.ShowGui) Show();
if (_argParser.Build) Build();
if (!_argParser.ShowGui) Close();
}
private void InitializeFormSettings()
{
if (!string.IsNullOrEmpty(Settings.Default.OutputFolder) && Directory.Exists(Settings.Default.OutputFolder)) txtOutputFolder.Text = Settings.Default.OutputFolder;
if (!string.IsNullOrEmpty(Settings.Default.FeedXML)) txtFeedXML.Text = Settings.Default.FeedXML;
if (!string.IsNullOrEmpty(Settings.Default.BaseURL)) txtBaseURL.Text = Settings.Default.BaseURL;
chkVersion.Checked = Settings.Default.CompareVersion;
chkSize.Checked = Settings.Default.CompareSize;
chkDate.Checked = Settings.Default.CompareDate;
chkHash.Checked = Settings.Default.CompareHash;
chkIgnoreSymbols.Checked = Settings.Default.IgnoreDebugSymbols;
chkIgnoreVsHost.Checked = Settings.Default.IgnoreVsHosting;
chkCopyFiles.Checked = Settings.Default.CopyFiles;
chkCleanUp.Checked = Settings.Default.CleanUp;
if (Settings.Default.IgnoreFiles == null) Settings.Default.IgnoreFiles = new StringCollection();
ReadFiles();
UpdateTitle();
}
private void UpdateTitle()
{
if (string.IsNullOrEmpty(FileName)) Text = "Feed Builder";
else Text = "Feed Builder - " + FileName;
}
private void SaveFormSettings()
{
if (!string.IsNullOrEmpty(txtOutputFolder.Text.Trim()) && Directory.Exists(txtOutputFolder.Text.Trim())) Settings.Default.OutputFolder = txtOutputFolder.Text.Trim();
// ReSharper disable AssignNullToNotNullAttribute
if (!string.IsNullOrEmpty(txtFeedXML.Text.Trim()) && Directory.Exists(Path.GetDirectoryName(txtFeedXML.Text.Trim()))) Settings.Default.FeedXML = txtFeedXML.Text.Trim();
// ReSharper restore AssignNullToNotNullAttribute
if (!string.IsNullOrEmpty(txtBaseURL.Text.Trim())) Settings.Default.BaseURL = txtBaseURL.Text.Trim();
Settings.Default.CompareVersion = chkVersion.Checked;
Settings.Default.CompareSize = chkSize.Checked;
Settings.Default.CompareDate = chkDate.Checked;
Settings.Default.CompareHash = chkHash.Checked;
Settings.Default.IgnoreDebugSymbols = chkIgnoreSymbols.Checked;
Settings.Default.IgnoreVsHosting = chkIgnoreVsHost.Checked;
Settings.Default.CopyFiles = chkCopyFiles.Checked;
Settings.Default.CleanUp = chkCleanUp.Checked;
if (Settings.Default.IgnoreFiles==null) Settings.Default.IgnoreFiles = new StringCollection();
Settings.Default.IgnoreFiles.Clear();
foreach (ListViewItem thisItem in lstFiles.Items) {
if (!thisItem.Checked) Settings.Default.IgnoreFiles.Add(thisItem.Text);
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
SaveFormSettings();
}
#endregion
#region " Commands Events"
private void cmdBuild_Click(Object sender, EventArgs e)
{
Build();
}
private void btnOpenOutputs_Click(object sender, EventArgs e)
{
OpenOutputsFolder();
}
private void btnNew_Click(Object sender, EventArgs e)
{
Settings.Default.Reset();
InitializeFormSettings();
}
private void btnOpen_Click(Object sender, EventArgs e)
{
OpenFileDialog dlg;
if (_openDialog == null) {
dlg = new OpenFileDialog {
CheckFileExists = true,
FileName = string.IsNullOrEmpty(FileName) ? DefaultFileName : FileName
};
_openDialog = dlg;
} else dlg = _openDialog;
dlg.Filter = DialogFilter;
if (dlg.ShowDialog() != DialogResult.OK) return;
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.LoadFrom(dlg.FileName);
FileName = dlg.FileName;
InitializeFormSettings();
}
private void btnSave_Click(Object sender, EventArgs e)
{
Save(false);
}
private void btnSaveAs_Click(Object sender, EventArgs e)
{
Save(true);
}
private void btnRefresh_Click(Object sender, EventArgs e)
{
ReadFiles();
}
#endregion
#region " Options Events"
private void cmdOutputFolder_Click(Object sender, EventArgs e)
{
fbdOutputFolder.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (fbdOutputFolder.ShowDialog(this) != DialogResult.OK) return;
txtOutputFolder.Text = fbdOutputFolder.SelectedPath;
ReadFiles();
}
private void cmdFeedXML_Click(Object sender, EventArgs e)
{
sfdFeedXML.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (sfdFeedXML.ShowDialog(this) == DialogResult.OK) txtFeedXML.Text = sfdFeedXML.FileName;
}
private void chkIgnoreSymbols_CheckedChanged(object sender, EventArgs e)
{
ReadFiles();
}
private void chkCopyFiles_CheckedChanged(Object sender, EventArgs e)
{
chkCleanUp.Enabled = chkCopyFiles.Checked;
if (!chkCopyFiles.Checked) chkCleanUp.Checked = false;
}
#endregion
#region " Helper Methods "
private void Build()
{
Console.WriteLine("Building NAppUpdater feed '{0}'", txtBaseURL.Text.Trim());
if (string.IsNullOrEmpty(txtFeedXML.Text)) {
const string msg = "The feed file location needs to be defined.\n" + "The outputs cannot be generated without this.";
if (_argParser.ShowGui) MessageBox.Show(msg);
Console.WriteLine(msg);
return;
}
// If the target folder doesn't exist, create a path to it
string dest = txtFeedXML.Text.Trim();
var destDir = Directory.GetParent(new FileInfo(dest).FullName);
if (!Directory.Exists(destDir.FullName)) Directory.CreateDirectory(destDir.FullName);
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
XmlElement feed = doc.CreateElement("Feed");
if (!string.IsNullOrEmpty(txtBaseURL.Text.Trim())) feed.SetAttribute("BaseUrl", txtBaseURL.Text.Trim());
doc.AppendChild(feed);
XmlElement tasks = doc.CreateElement("Tasks");
Console.WriteLine("Processing feed items");
int itemsCopied = 0;
int itemsCleaned = 0;
int itemsSkipped = 0;
int itemsFailed = 0;
int itemsMissingConditions = 0;
foreach (ListViewItem thisItem in lstFiles.Items) {
string destFile = "";
string folder = "";
string filename = "";
try {
folder = Path.GetDirectoryName(txtFeedXML.Text.Trim());
filename = thisItem.Text;
if (folder != null) destFile = Path.Combine(folder, filename);
} catch {}
if (destFile == "" || folder == "" || filename == "") {
string msg = string.Format("The file could not be pathed:\nFolder:'{0}'\nFile:{1}", folder, filename);
if (_argParser.ShowGui) MessageBox.Show(msg);
Console.WriteLine(msg);
continue;
}
if (thisItem.Checked) {
var fileInfoEx = (FileInfoEx)thisItem.Tag;
XmlElement task = doc.CreateElement("FileUpdateTask");
task.SetAttribute("localPath", fileInfoEx.RelativeName);
// generate FileUpdateTask metadata items
task.SetAttribute("lastModified", fileInfoEx.FileInfo.LastWriteTime.ToFileTime().ToString(CultureInfo.InvariantCulture));
task.SetAttribute("fileSize", fileInfoEx.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
if (!string.IsNullOrEmpty(fileInfoEx.FileVersion)) task.SetAttribute("version", fileInfoEx.FileVersion);
XmlElement conds = doc.CreateElement("Conditions");
XmlElement cond;
bool hasFirstCondition = false;
//File Exists
cond = doc.CreateElement("FileExistsCondition");
cond.SetAttribute("type", "or");
conds.AppendChild(cond);
//Version
if (chkVersion.Checked && !string.IsNullOrEmpty(fileInfoEx.FileVersion)) {
cond = doc.CreateElement("FileVersionCondition");
cond.SetAttribute("what", "below");
cond.SetAttribute("version", fileInfoEx.FileVersion);
conds.AppendChild(cond);
hasFirstCondition = true;
}
//Size
if (chkSize.Checked) {
cond = doc.CreateElement("FileSizeCondition");
cond.SetAttribute("type", hasFirstCondition ? "or-not" : "not");
cond.SetAttribute("what", "is");
cond.SetAttribute("size", fileInfoEx.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
conds.AppendChild(cond);
}
//Date
if (chkDate.Checked) {
cond = doc.CreateElement("FileDateCondition");
if (hasFirstCondition) cond.SetAttribute("type", "or");
cond.SetAttribute("what", "older");
// local timestamp, not UTC
cond.SetAttribute("timestamp", fileInfoEx.FileInfo.LastWriteTime.ToFileTime().ToString(CultureInfo.InvariantCulture));
conds.AppendChild(cond);
}
//Hash
if (chkHash.Checked) {
cond = doc.CreateElement("FileChecksumCondition");
cond.SetAttribute("type", hasFirstCondition ? "or-not" : "not");
cond.SetAttribute("checksumType", "sha256");
cond.SetAttribute("checksum", fileInfoEx.Hash);
conds.AppendChild(cond);
}
if (conds.ChildNodes.Count == 0) itemsMissingConditions++;
task.AppendChild(conds);
tasks.AppendChild(task);
if (chkCopyFiles.Checked) {
if (CopyFile(fileInfoEx.FileInfo.FullName, destFile)) itemsCopied++;
else itemsFailed++;
}
} else {
try {
if (chkCleanUp.Checked & File.Exists(destFile)) {
File.Delete(destFile);
itemsCleaned += 1;
} else itemsSkipped += 1;
} catch (IOException) {
itemsFailed += 1;
}
}
}
feed.AppendChild(tasks);
doc.Save(txtFeedXML.Text.Trim());
// open the outputs folder if we're running from the GUI or
// we have an explicit command line option to do so
if (!_argParser.HasArgs || _argParser.OpenOutputsFolder) OpenOutputsFolder();
Console.WriteLine("Done building feed.");
if (itemsCopied > 0) Console.WriteLine("{0,5} items copied", itemsCopied);
if (itemsCleaned > 0) Console.WriteLine("{0,5} items cleaned", itemsCleaned);
if (itemsSkipped > 0) Console.WriteLine("{0,5} items skipped", itemsSkipped);
if (itemsFailed > 0) Console.WriteLine("{0,5} items failed", itemsFailed);
if (itemsMissingConditions > 0) Console.WriteLine("{0,5} items without any conditions", itemsMissingConditions);
}
private bool CopyFile(string sourceFile, string destFile)
{
// If the target folder doesn't exist, create the path to it
var fi = new FileInfo(destFile);
var d = Directory.GetParent(fi.FullName);
if (!Directory.Exists(d.FullName)) CreateDirectoryPath(d.FullName);
// Copy with delayed retry
int retries = 3;
while (retries > 0) {
try {
if (File.Exists(destFile)) File.Delete(destFile);
File.Copy(sourceFile, destFile);
retries = 0; // success
return true;
} catch (IOException) {
// Failed... let's try sleeping a bit (slow disk maybe)
if (retries-- > 0) Thread.Sleep(200);
} catch (UnauthorizedAccessException) {
// same handling as IOException
if (retries-- > 0) Thread.Sleep(200);
}
}
return false;
}
private void CreateDirectoryPath(string directoryPath)
{
// Create the folder/path if it doesn't exist, with delayed retry
int retries = 3;
while (retries > 0 && !Directory.Exists(directoryPath)) {
Directory.CreateDirectory(directoryPath);
if (retries-- < 3) Thread.Sleep(200);
}
}
private void OpenOutputsFolder()
{
if (string.IsNullOrEmpty(txtFeedXML.Text.Trim())) return;
string dir = Path.GetDirectoryName(txtFeedXML.Text.Trim());
if (dir == null) return;
CreateDirectoryPath(dir);
Process process = new Process {
StartInfo = {
UseShellExecute = true,
FileName = dir
}
};
process.Start();
}
private int GetImageIndex(string ext)
{
switch (ext.Trim('.')) {
case "bmp":
return 1;
case "dll":
return 2;
case "doc":
case "docx":
return 3;
case "exe":
return 4;
case "htm":
case "html":
return 5;
case "jpg":
case "jpeg":
return 6;
case "pdf":
return 7;
case "png":
return 8;
case "txt":
return 9;
case "wav":
case "mp3":
return 10;
case "wmv":
return 11;
case "xls":
case "xlsx":
return 12;
case "zip":
return 13;
default:
return 0;
}
}
private void ReadFiles()
{
if (string.IsNullOrEmpty(txtOutputFolder.Text.Trim()) || !Directory.Exists(txtOutputFolder.Text.Trim())) return;
lstFiles.BeginUpdate();
lstFiles.Items.Clear();
string outputDir = txtOutputFolder.Text.Trim();
int outputDirLength = txtOutputFolder.Text.Trim().Length;
FileSystemEnumerator enumerator = new FileSystemEnumerator(txtOutputFolder.Text.Trim(), "*.*", true);
foreach (FileInfo fi in enumerator.Matches()) {
string thisFile = fi.FullName;
if ((IsIgnorable(thisFile))) continue;
FileInfoEx thisInfo = new FileInfoEx(thisFile,outputDirLength);
ListViewItem thisItem = new ListViewItem(thisInfo.RelativeName, GetImageIndex(thisInfo.FileInfo.Extension));
thisItem.SubItems.Add(thisInfo.FileVersion);
thisItem.SubItems.Add(thisInfo.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
thisItem.SubItems.Add(thisInfo.FileInfo.LastWriteTime.ToString(CultureInfo.InvariantCulture));
thisItem.SubItems.Add(thisInfo.Hash);
thisItem.Checked = (!Settings.Default.IgnoreFiles.Contains(thisInfo.FileInfo.Name));
thisItem.Tag = thisInfo;
lstFiles.Items.Add(thisItem);
}
lstFiles.EndUpdate();
}
private bool IsIgnorable(string filename)
{
string ext = Path.GetExtension(filename);
if ((chkIgnoreSymbols.Checked && ext == ".pdb")) return true;
return (chkIgnoreVsHost.Checked && filename.ToLower().Contains("vshost.exe"));
}
private void Save(bool forceDialog)
{
SaveFormSettings();
if (forceDialog || string.IsNullOrEmpty(FileName)) {
SaveFileDialog dlg = new SaveFileDialog {
Filter = DialogFilter,
FileName = DefaultFileName
};
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK) {
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.SaveAs(dlg.FileName);
FileName = dlg.FileName;
}
} else {
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.SaveAs(FileName);
}
UpdateTitle();
}
#endregion
private void frmMain_DragEnter(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files.Length == 0) return;
e.Effect = files[0].EndsWith(".config") ? DragDropEffects.Move : DragDropEffects.None;
}
private void frmMain_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files.Length == 0) return;
try {
string fileName = files[0];
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.LoadFrom(fileName);
FileName = fileName;
InitializeFormSettings();
} catch (Exception ex) {
MessageBox.Show("The file could not be opened: \n" + ex.Message);
}
}
}
}
| |
//
// BEncodedString.cs
//
// Authors:
// Alan McGovern alan.mcgovern@gmail.com
//
// Copyright (C) 2006 Alan McGovern
//
// 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 OctoTorrent.BEncoding
{
using System;
using System.Linq;
using System.Text;
using Common;
using Client.Messages;
/// <summary>
/// Class representing a BEncoded string
/// </summary>
public class BEncodedString : BEncodedValue, IComparable<BEncodedString>
{
#region Member Variables
/// <summary>
/// The value of the BEncodedString
/// </summary>
public string Text
{
get { return Encoding.UTF8.GetString(TextBytes); }
set { TextBytes = Encoding.UTF8.GetBytes(value); }
}
/// <summary>
/// The underlying byte[] associated with this BEncodedString
/// </summary>
public byte[] TextBytes { get; private set; }
#endregion
#region Constructors
/// <summary>
/// Create a new BEncodedString using UTF8 encoding
/// </summary>
public BEncodedString()
: this(new byte[0])
{
}
/// <summary>
/// Create a new BEncodedString using UTF8 encoding
/// </summary>
/// <param name="value"></param>
public BEncodedString(char[] value)
: this(Encoding.UTF8.GetBytes(value))
{
}
/// <summary>
/// Create a new BEncodedString using UTF8 encoding
/// </summary>
/// <param name="value">Initial value for the string</param>
public BEncodedString(string value)
: this(Encoding.UTF8.GetBytes(value))
{
}
/// <summary>
/// Create a new BEncodedString using UTF8 encoding
/// </summary>
/// <param name="value"></param>
public BEncodedString(byte[] value)
{
TextBytes = value;
}
public static implicit operator BEncodedString(string value)
{
return new BEncodedString(value);
}
public static implicit operator BEncodedString(char[] value)
{
return new BEncodedString(value);
}
public static implicit operator BEncodedString(byte[] value)
{
return new BEncodedString(value);
}
#endregion
#region Encode/Decode Methods
/// <summary>
/// Encodes the BEncodedString to a byte[] using the supplied Encoding
/// </summary>
/// <param name="buffer">The buffer to encode the string to</param>
/// <param name="offset">The offset at which to save the data to</param>
/// <returns>The number of bytes encoded</returns>
public override int Encode(byte[] buffer, int offset)
{
var written = offset;
written += Message.WriteAscii(buffer, written, TextBytes.Length.ToString ());
written += Message.WriteAscii(buffer, written, ":");
written += Message.Write(buffer, written, TextBytes);
return written - offset;
}
/// <summary>
/// Decodes a BEncodedString from the supplied StreamReader
/// </summary>
/// <param name="reader">The StreamReader containing the BEncodedString</param>
internal override void DecodeInternal(RawReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
int letterCount;
var length = string.Empty;
while ((reader.PeekByte() != -1) && (reader.PeekByte() != ':')) // read in how many characters
length += (char)reader.ReadByte(); // the string is
if (reader.ReadByte() != ':') // remove the ':'
throw new BEncodingException("Invalid data found. Aborting");
if (!int.TryParse(length, out letterCount))
throw new BEncodingException(string.Format("Invalid BEncodedString. Length was '{0}' instead of a number", length));
TextBytes = new byte[letterCount];
if (reader.Read(TextBytes, 0, letterCount) != letterCount)
throw new BEncodingException("Couldn't decode string");
}
#endregion
#region Helper Methods
public string Hex
{
get { return BitConverter.ToString(TextBytes); }
}
public override int LengthInBytes()
{
// The length is equal to the length-prefix + ':' + length of data
var prefix = 1; // Account for ':'
// Count the number of characters needed for the length prefix
for (var i = TextBytes.Length; i != 0; i = i/10)
prefix += 1;
if (TextBytes.Length == 0)
prefix++;
return prefix + TextBytes.Length;
}
public int CompareTo(object other)
{
return CompareTo(other as BEncodedString);
}
public int CompareTo(BEncodedString other)
{
if (other == null)
return 1;
int difference;
var length = TextBytes.Length > other.TextBytes.Length
? other.TextBytes.Length
: TextBytes.Length;
for (var i = 0; i < length; i++)
if ((difference = TextBytes[i].CompareTo(other.TextBytes[i])) != 0)
return difference;
if (TextBytes.Length == other.TextBytes.Length)
return 0;
return TextBytes.Length > other.TextBytes.Length ? 1 : -1;
}
#endregion
#region Overridden Methods
public override bool Equals(object obj)
{
if (obj == null)
return false;
BEncodedString other;
if (obj is string)
other = new BEncodedString((string)obj);
else if (obj is BEncodedString)
other = (BEncodedString)obj;
else
return false;
return Toolbox.ByteMatch(TextBytes, other.TextBytes);
}
public override int GetHashCode()
{
return TextBytes.Aggregate(0, (current, t) => current + t);
}
public override string ToString()
{
return System.Text.Encoding.UTF8.GetString(TextBytes);
}
#endregion
}
}
| |
/*
* 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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Securities;
using QuantConnect.Util;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace QuantConnect.Brokerages.Binance
{
/// <summary>
/// Binance REST API implementation
/// </summary>
public class BinanceRestApiClient : IDisposable
{
private const string UserDataStreamEndpoint = "/api/v3/userDataStream";
private readonly SymbolPropertiesDatabaseSymbolMapper _symbolMapper;
private readonly ISecurityProvider _securityProvider;
private readonly IRestClient _restClient;
private readonly RateGate _restRateLimiter = new RateGate(10, TimeSpan.FromSeconds(1));
private readonly object _listenKeyLocker = new object();
/// <summary>
/// Event that fires each time an order is filled
/// </summary>
public event EventHandler<BinanceOrderSubmitEventArgs> OrderSubmit;
/// <summary>
/// Event that fires each time an order is filled
/// </summary>
public event EventHandler<OrderEvent> OrderStatusChanged;
/// <summary>
/// Event that fires when an error is encountered in the brokerage
/// </summary>
public event EventHandler<BrokerageMessageEvent> Message;
/// <summary>
/// Key Header
/// </summary>
public readonly string KeyHeader = "X-MBX-APIKEY";
/// <summary>
/// The api secret
/// </summary>
protected string ApiSecret;
/// <summary>
/// The api key
/// </summary>
protected string ApiKey;
/// <summary>
/// Represents UserData Session listen key
/// </summary>
public string SessionId { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="BinanceRestApiClient"/> class.
/// </summary>
/// <param name="symbolMapper">The symbol mapper.</param>
/// <param name="securityProvider">The holdings provider.</param>
/// <param name="apiKey">The Binance API key</param>
/// <param name="apiSecret">The The Binance API secret</param>
/// <param name="restApiUrl">The Binance API rest url</param>
public BinanceRestApiClient(SymbolPropertiesDatabaseSymbolMapper symbolMapper, ISecurityProvider securityProvider,
string apiKey, string apiSecret, string restApiUrl)
{
_symbolMapper = symbolMapper;
_securityProvider = securityProvider;
_restClient = new RestClient(restApiUrl);
ApiKey = apiKey;
ApiSecret = apiSecret;
}
/// <summary>
/// Gets all open positions
/// </summary>
/// <returns></returns>
public List<Holding> GetAccountHoldings()
{
return new List<Holding>();
}
/// <summary>
/// Gets the total account cash balance for specified account type
/// </summary>
/// <returns></returns>
public Messages.AccountInformation GetCashBalance()
{
var queryString = $"timestamp={GetNonce()}";
var endpoint = $"/api/v3/account?{queryString}&signature={AuthenticationToken(queryString)}";
var request = new RestRequest(endpoint, Method.GET);
request.AddHeader(KeyHeader, ApiKey);
var response = ExecuteRestRequest(request);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"BinanceBrokerage.GetCashBalance: request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
}
return JsonConvert.DeserializeObject<Messages.AccountInformation>(response.Content);
}
/// <summary>
/// Gets all orders not yet closed
/// </summary>
/// <returns></returns>
public IEnumerable<Messages.OpenOrder> GetOpenOrders()
{
var queryString = $"timestamp={GetNonce()}";
var endpoint = $"/api/v3/openOrders?{queryString}&signature={AuthenticationToken(queryString)}";
var request = new RestRequest(endpoint, Method.GET);
request.AddHeader(KeyHeader, ApiKey);
var response = ExecuteRestRequest(request);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"BinanceBrokerage.GetCashBalance: request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
}
return JsonConvert.DeserializeObject<Messages.OpenOrder[]>(response.Content);
}
/// <summary>
/// Places a new order and assigns a new broker ID to the order
/// </summary>
/// <param name="order">The order to be placed</param>
/// <returns>True if the request for a new order has been placed, false otherwise</returns>
public bool PlaceOrder(Order order)
{
// supported time in force values {GTC, IOC, FOK}
// use GTC as LEAN doesn't support others yet
IDictionary<string, object> body = new Dictionary<string, object>()
{
{ "symbol", _symbolMapper.GetBrokerageSymbol(order.Symbol) },
{ "quantity", Math.Abs(order.Quantity).ToString(CultureInfo.InvariantCulture) },
{ "side", ConvertOrderDirection(order.Direction) }
};
switch (order)
{
case LimitOrder limitOrder:
body["type"] = (order.Properties as BinanceOrderProperties)?.PostOnly == true
? "LIMIT_MAKER"
: "LIMIT";
body["price"] = limitOrder.LimitPrice.ToString(CultureInfo.InvariantCulture);
// timeInForce is not required for LIMIT_MAKER
if (Equals(body["type"], "LIMIT"))
body["timeInForce"] = "GTC";
break;
case MarketOrder:
body["type"] = "MARKET";
break;
case StopLimitOrder stopLimitOrder:
var ticker = GetTickerPrice(order);
var stopPrice = stopLimitOrder.StopPrice;
if (order.Direction == OrderDirection.Sell)
{
body["type"] = stopPrice <= ticker ? "STOP_LOSS_LIMIT" : "TAKE_PROFIT_LIMIT";
}
else
{
body["type"] = stopPrice <= ticker ? "TAKE_PROFIT_LIMIT" : "STOP_LOSS_LIMIT";
}
body["timeInForce"] = "GTC";
body["stopPrice"] = stopPrice.ToStringInvariant();
body["price"] = stopLimitOrder.LimitPrice.ToStringInvariant();
break;
default:
throw new NotSupportedException($"BinanceBrokerage.ConvertOrderType: Unsupported order type: {order.Type}");
}
const string endpoint = "/api/v3/order";
body["timestamp"] = GetNonce();
body["signature"] = AuthenticationToken(body.ToQueryString());
var request = new RestRequest(endpoint, Method.POST);
request.AddHeader(KeyHeader, ApiKey);
request.AddParameter(
"application/x-www-form-urlencoded",
Encoding.UTF8.GetBytes(body.ToQueryString()),
ParameterType.RequestBody
);
var response = ExecuteRestRequest(request);
if (response.StatusCode == HttpStatusCode.OK)
{
var raw = JsonConvert.DeserializeObject<Messages.NewOrder>(response.Content);
if (string.IsNullOrEmpty(raw?.Id))
{
var errorMessage = $"Error parsing response from place order: {response.Content}";
OnOrderEvent(new OrderEvent(
order,
DateTime.UtcNow,
OrderFee.Zero,
"Binance Order Event")
{ Status = OrderStatus.Invalid, Message = errorMessage });
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, (int)response.StatusCode, errorMessage));
return true;
}
OnOrderSubmit(raw, order);
return true;
}
var message = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {response.Content}";
OnOrderEvent(new OrderEvent(
order,
DateTime.UtcNow,
OrderFee.Zero,
"Binance Order Event")
{ Status = OrderStatus.Invalid });
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, message));
return true;
}
/// <summary>
/// Cancels the order with the specified ID
/// </summary>
/// <param name="order">The order to cancel</param>
/// <returns>True if the request was submitted for cancellation, false otherwise</returns>
public bool CancelOrder(Order order)
{
var success = new List<bool>();
IDictionary<string, object> body = new Dictionary<string, object>()
{
{ "symbol", _symbolMapper.GetBrokerageSymbol(order.Symbol) }
};
foreach (var id in order.BrokerId)
{
if (body.ContainsKey("signature"))
{
body.Remove("signature");
}
body["orderId"] = id;
body["timestamp"] = GetNonce();
body["signature"] = AuthenticationToken(body.ToQueryString());
var request = new RestRequest("/api/v3/order", Method.DELETE);
request.AddHeader(KeyHeader, ApiKey);
request.AddParameter(
"application/x-www-form-urlencoded",
Encoding.UTF8.GetBytes(body.ToQueryString()),
ParameterType.RequestBody
);
var response = ExecuteRestRequest(request);
success.Add(response.StatusCode == HttpStatusCode.OK);
}
var canceled = false;
if (success.All(a => a))
{
OnOrderEvent(new OrderEvent(order,
DateTime.UtcNow,
OrderFee.Zero,
"Binance Order Event")
{ Status = OrderStatus.Canceled });
canceled = true;
}
return canceled;
}
/// <summary>
/// Gets the history for the requested security
/// </summary>
/// <param name="request">The historical data request</param>
/// <returns>An enumerable of bars covering the span specified in the request</returns>
public IEnumerable<Messages.Kline> GetHistory(Data.HistoryRequest request)
{
var resolution = ConvertResolution(request.Resolution);
var resolutionInMs = (long)request.Resolution.ToTimeSpan().TotalMilliseconds;
var symbol = _symbolMapper.GetBrokerageSymbol(request.Symbol);
var startMs = (long)Time.DateTimeToUnixTimeStamp(request.StartTimeUtc) * 1000;
var endMs = (long)Time.DateTimeToUnixTimeStamp(request.EndTimeUtc) * 1000;
// we always use the real endpoint for history requests
var endpoint = $"https://api.binance.com/api/v3/klines?symbol={symbol}&interval={resolution}&limit=1000";
while (endMs - startMs >= resolutionInMs)
{
var timeframe = $"&startTime={startMs}&endTime={endMs}";
var restRequest = new RestRequest(endpoint + timeframe, Method.GET);
var response = ExecuteRestRequest(restRequest);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"BinanceBrokerage.GetHistory: request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
}
var klines = JsonConvert.DeserializeObject<object[][]>(response.Content)
.Select(entries => new Messages.Kline(entries))
.ToList();
if (klines.Count > 0)
{
var lastValue = klines[klines.Count - 1];
if (Log.DebuggingEnabled)
{
var windowStartTime = Time.UnixMillisecondTimeStampToDateTime(klines[0].OpenTime);
var windowEndTime = Time.UnixMillisecondTimeStampToDateTime(lastValue.OpenTime + resolutionInMs);
Log.Debug($"BinanceRestApiClient.GetHistory(): Received [{symbol}] data for timeperiod from {windowStartTime.ToStringInvariant()} to {windowEndTime.ToStringInvariant()}..");
}
startMs = lastValue.OpenTime + resolutionInMs;
foreach (var kline in klines)
{
yield return kline;
}
}
else
{
// if there is no data just break
break;
}
}
}
/// <summary>
/// Check User Data stream listen key is alive
/// </summary>
/// <returns></returns>
public bool SessionKeepAlive()
{
if (string.IsNullOrEmpty(SessionId))
{
throw new Exception("BinanceBrokerage:UserStream. listenKey wasn't allocated or has been refused.");
}
var ping = new RestRequest(UserDataStreamEndpoint, Method.PUT);
ping.AddHeader(KeyHeader, ApiKey);
ping.AddParameter(
"application/x-www-form-urlencoded",
Encoding.UTF8.GetBytes($"listenKey={SessionId}"),
ParameterType.RequestBody
);
var pong = ExecuteRestRequest(ping);
return pong.StatusCode == HttpStatusCode.OK;
}
/// <summary>
/// Stops the session
/// </summary>
public void StopSession()
{
if (!string.IsNullOrEmpty(SessionId))
{
var request = new RestRequest(UserDataStreamEndpoint, Method.DELETE);
request.AddHeader(KeyHeader, ApiKey);
request.AddParameter(
"application/x-www-form-urlencoded",
Encoding.UTF8.GetBytes($"listenKey={SessionId}"),
ParameterType.RequestBody
);
ExecuteRestRequest(request);
}
}
/// <summary>
/// Provides the current tickers price
/// </summary>
/// <returns></returns>
public Messages.PriceTicker[] GetTickers()
{
const string endpoint = "/api/v3/ticker/price";
var req = new RestRequest(endpoint, Method.GET);
var response = ExecuteRestRequest(req);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"BinanceBrokerage.GetTick: request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
}
return JsonConvert.DeserializeObject<Messages.PriceTicker[]>(response.Content);
}
/// <summary>
/// Start user data stream
/// </summary>
public void CreateListenKey()
{
var request = new RestRequest(UserDataStreamEndpoint, Method.POST);
request.AddHeader(KeyHeader, ApiKey);
var response = ExecuteRestRequest(request);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"BinanceBrokerage.StartSession: request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
}
var content = JObject.Parse(response.Content);
lock (_listenKeyLocker)
{
SessionId = content.Value<string>("listenKey");
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_restRateLimiter.DisposeSafely();
}
/// <summary>
/// If an IP address exceeds a certain number of requests per minute
/// HTTP 429 return code is used when breaking a request rate limit.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
private IRestResponse ExecuteRestRequest(IRestRequest request)
{
const int maxAttempts = 10;
var attempts = 0;
IRestResponse response;
do
{
if (!_restRateLimiter.WaitToProceed(TimeSpan.Zero))
{
Log.Trace("Brokerage.OnMessage(): " + new BrokerageMessageEvent(BrokerageMessageType.Warning, "RateLimit",
"The API request has been rate limited. To avoid this message, please reduce the frequency of API calls."));
_restRateLimiter.WaitToProceed();
}
response = _restClient.Execute(request);
// 429 status code: Too Many Requests
} while (++attempts < maxAttempts && (int)response.StatusCode == 429);
return response;
}
private decimal GetTickerPrice(Order order)
{
var security = _securityProvider.GetSecurity(order.Symbol);
var tickerPrice = order.Direction == OrderDirection.Buy ? security.AskPrice : security.BidPrice;
if (tickerPrice == 0)
{
var brokerageSymbol = _symbolMapper.GetBrokerageSymbol(order.Symbol);
var tickers = GetTickers();
var ticker = tickers.FirstOrDefault(t => t.Symbol == brokerageSymbol);
if (ticker == null)
{
throw new KeyNotFoundException($"BinanceBrokerage: Unable to resolve currency conversion pair: {order.Symbol}");
}
tickerPrice = ticker.Price;
}
return tickerPrice;
}
/// <summary>
/// Timestamp in milliseconds
/// </summary>
/// <returns></returns>
private long GetNonce()
{
return (long)(Time.TimeStamp() * 1000);
}
/// <summary>
/// Creates a signature for signed endpoints
/// </summary>
/// <param name="payload">the body of the request</param>
/// <returns>a token representing the request params</returns>
private string AuthenticationToken(string payload)
{
using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(ApiSecret)))
{
return hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)).ToHexString();
}
}
private static string ConvertOrderDirection(OrderDirection orderDirection)
{
if (orderDirection == OrderDirection.Buy || orderDirection == OrderDirection.Sell)
{
return orderDirection.ToString().LazyToUpper();
}
throw new NotSupportedException($"BinanceBrokerage.ConvertOrderDirection: Unsupported order direction: {orderDirection}");
}
private readonly Dictionary<Resolution, string> _knownResolutions = new Dictionary<Resolution, string>()
{
{ Resolution.Minute, "1m" },
{ Resolution.Hour, "1h" },
{ Resolution.Daily, "1d" }
};
private string ConvertResolution(Resolution resolution)
{
if (_knownResolutions.ContainsKey(resolution))
{
return _knownResolutions[resolution];
}
else
{
throw new ArgumentException($"BinanceBrokerage.ConvertResolution: Unsupported resolution type: {resolution}");
}
}
/// <summary>
/// Event invocator for the OrderFilled event
/// </summary>
/// <param name="newOrder">The brokerage order submit result</param>
/// <param name="order">The lean order</param>
private void OnOrderSubmit(Messages.NewOrder newOrder, Order order)
{
try
{
OrderSubmit?.Invoke(
this,
new BinanceOrderSubmitEventArgs(newOrder.Id, order));
// Generate submitted event
OnOrderEvent(new OrderEvent(
order,
Time.UnixMillisecondTimeStampToDateTime(newOrder.TransactionTime),
OrderFee.Zero,
"Binance Order Event")
{ Status = OrderStatus.Submitted }
);
Log.Trace($"Order submitted successfully - OrderId: {order.Id}");
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Event invocator for the OrderFilled event
/// </summary>
/// <param name="e">The OrderEvent</param>
private void OnOrderEvent(OrderEvent e)
{
try
{
Log.Debug("Brokerage.OnOrderEvent(): " + e);
OrderStatusChanged?.Invoke(this, e);
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Event invocator for the Message event
/// </summary>
/// <param name="e">The error</param>
protected virtual void OnMessage(BrokerageMessageEvent e)
{
try
{
if (e.Type == BrokerageMessageType.Error)
{
Log.Error("Brokerage.OnMessage(): " + e);
}
else
{
Log.Trace("Brokerage.OnMessage(): " + e);
}
Message?.Invoke(this, e);
}
catch (Exception err)
{
Log.Error(err);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.CSharp.Analyzers.Maintainability.CSharpUseNameofInPlaceOfStringAnalyzer,
Microsoft.CodeQuality.Analyzers.Maintainability.UseNameOfInPlaceOfStringFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.VisualBasic.Analyzers.Maintainability.BasicUseNameofInPlaceOfStringAnalyzer,
Microsoft.CodeQuality.Analyzers.Maintainability.UseNameOfInPlaceOfStringFixer>;
namespace Microsoft.CodeQuality.Analyzers.Maintainability.UnitTests
{
public class UseNameofInPlaceOfStringTests
{
#region Unit tests for no analyzer diagnostic
[Fact]
[WorkItem(3023, "https://github.com/dotnet/roslyn-analyzers/issues/3023")]
public async Task NoDiagnostic_ArgListAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public void M(__arglist)
{
M(__arglist());
}
}");
}
[Fact]
public async Task NoDiagnostic_NoArgumentsAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
throw new ArgumentNullException();
}
}");
}
[Fact]
public async Task NoDiagnostic_NullLiteralAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
throw new ArgumentNullException(null);
}
}");
}
[Fact]
public async Task NoDiagnostic_StringIsAReservedWordAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
throw new ArgumentNullException(""static"");
}
}");
}
[Fact]
public async Task NoDiagnostic_NoMatchingParametersInScopeAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int y)
{
throw new ArgumentNullException(""x"");
}
}");
}
[Fact]
public async Task NoDiagnostic_NameColonOtherParameterNameAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int y)
{
Console.WriteLine(format:""x"");
}
}");
}
[Fact]
public async Task NoDiagnostic_NotStringLiteralAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
string param = ""x"";
throw new ArgumentNullException(param);
}
}");
}
[Fact]
public async Task NoDiagnostic_NotValidIdentifierAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
throw new ArgumentNullException(""9x"");
}
}");
}
[Fact]
public async Task NoDiagnostic_NoArgumentListAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
throw new ArgumentNullException({|CS1002:|}{|CS1026:|}
}
}");
}
[Fact]
public async Task NoDiagnostic_NoMatchingParameterAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
throw new {|CS1729:ArgumentNullException|}(""test"", ""test2"", ""test3"");
}
}");
}
[Fact]
public async Task NoDiagnostic_MatchesParameterButNotCalledParamNameAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
Console.WriteLine(""x"");
}
}");
}
[Fact]
public async Task NoDiagnostic_MatchesPropertyButNotCalledPropertyNameAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.ComponentModel;
public class Person : INotifyPropertyChanged
{
private string name;
public event PropertyChangedEventHandler PropertyChanged;
public string PersonName {
get { return name; }
set
{
name = value;
Console.WriteLine(""PersonName"");
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}");
}
[Fact]
public async Task NoDiagnostic_PositionalArgumentOtherParameterNameAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
Console.WriteLine(""x"");
}
}");
}
[WorkItem(1426, "https://github.com/dotnet/roslyn-analyzers/issues/1426")]
[Fact]
public async Task NoDiagnostic_1426Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Runtime.CompilerServices;
public class C
{
int M([CallerMemberName] string propertyName = """")
{
return 0;
}
public bool Property
{
set
{
M();
}
}
}");
}
[WorkItem(1524, "https://github.com/dotnet/roslyn-analyzers/issues/1524")]
[Fact]
public async Task NoDiagnostic_CSharp5Async()
{
await new VerifyCS.Test
{
TestCode = @"
using System;
class C
{
void M(int x)
{
throw new ArgumentNullException(""x"");
}
}",
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp5
}.RunAsync();
}
[WorkItem(1524, "https://github.com/dotnet/roslyn-analyzers/issues/1524")]
[Fact]
public async Task Diagnostic_CSharp6Async()
{
await new VerifyCS.Test
{
TestCode = @"
using System;
class C
{
void M(int x)
{
throw new ArgumentNullException(""x"");
}
}",
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp6,
ExpectedDiagnostics =
{
GetCSharpNameofResultAt(7, 41, "x"),
}
}.RunAsync();
}
[WorkItem(1524, "https://github.com/dotnet/roslyn-analyzers/issues/1524")]
[Fact]
public async Task NoDiagnostic_VB12Async()
{
await new VerifyVB.Test
{
TestCode = @"
Imports System
Module Mod1
Sub f(s As String)
Throw New ArgumentNullException(""s"")
End Sub
End Module",
LanguageVersion = CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic12
}.RunAsync();
}
[WorkItem(1524, "https://github.com/dotnet/roslyn-analyzers/issues/1524")]
[Fact]
public async Task Diagnostic_VB14Async()
{
await new VerifyVB.Test
{
TestCode = @"
Imports System
Module Mod1
Sub f(s As String)
Throw New ArgumentNullException(""s"")
End Sub
End Module",
LanguageVersion = CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14,
ExpectedDiagnostics =
{
GetBasicNameofResultAt(6, 41, "s"),
}
}.RunAsync();
}
#endregion
#region Unit tests for analyzer diagnostic(s)
[Fact]
public async Task Diagnostic_ArgumentMatchesAParameterInScopeAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
throw new ArgumentNullException(""x"");
}
}",
GetCSharpNameofResultAt(7, 41, "x"));
}
[Fact]
public async Task Diagnostic_VB_ArgumentMatchesAParameterInScopeAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Module Mod1
Sub f(s As String)
Throw New ArgumentNullException(""s"")
End Sub
End Module",
GetBasicNameofResultAt(6, 41, "s"));
}
[Fact]
public async Task Diagnostic_ArgumentMatchesAPropertyInScopeAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.ComponentModel;
public class Person : INotifyPropertyChanged
{
private string name;
public event PropertyChangedEventHandler PropertyChanged;
public string PersonName {
get { return name; }
set
{
name = value;
OnPropertyChanged(""PersonName"");
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}",
GetCSharpNameofResultAt(14, 31, "PersonName"));
}
[Fact]
public async Task Diagnostic_ArgumentMatchesAPropertyInScope2Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.ComponentModel;
public class Person : INotifyPropertyChanged
{
private string name;
public event PropertyChangedEventHandler PropertyChanged;
public string PersonName
{
get { return name; }
set
{
name = value;
OnPropertyChanged(""PersonName"");
}
}
public string PersonName2
{
get { return name; }
set
{
name = value;
OnPropertyChanged(nameof(PersonName2));
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}",
GetCSharpNameofResultAt(15, 31, "PersonName"));
}
[Fact]
public async Task Diagnostic_ArgumentNameColonParamNameAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C
{
void M(int x)
{
throw new ArgumentNullException(paramName:""x"");
}
}",
GetCSharpNameofResultAt(7, 51, "x"));
}
[Fact]
public async Task Diagnostic_ArgumentNameColonPropertyNameAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.ComponentModel;
public class Person : INotifyPropertyChanged
{
private string name;
public event PropertyChangedEventHandler PropertyChanged;
public string PersonName {
get { return name; }
set
{
name = value;
OnPropertyChanged(propertyName:""PersonName"");
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}",
GetCSharpNameofResultAt(14, 44, "PersonName"));
}
[Fact]
public async Task Diagnostic_AnonymousFunctionMultiline1Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Test
{
void Method(int x)
{
Action<int> a = (int y) =>
{
throw new ArgumentException(""somemessage"", ""x"");
};
}
}",
GetCSharpNameofResultAt(10, 56, "x"));
}
[Fact]
public async Task Diagnostic_AnonymousFunctionMultiLine2Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Test
{
void Method(int x)
{
Action<int> a = (int y) =>
{
throw new ArgumentException(""somemessage"", ""y"");
};
}
}",
GetCSharpNameofResultAt(10, 56, "y"));
}
[Fact]
public async Task Diagnostic_AnonymousFunctionSingleLine1Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Test
{
void Method(int x)
{
Action<int> a = (int y) => throw new ArgumentException(""somemessage"", ""y"");
}
}",
GetCSharpNameofResultAt(8, 79, "y"));
}
[Fact]
public async Task Diagnostic_AnonymousFunctionSingleLine2Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Test
{
void Method(int x)
{
Action<int> a = (int y) => throw new ArgumentException(""somemessage"", ""x"");
}
}",
GetCSharpNameofResultAt(8, 79, "x"));
}
[Fact]
public async Task Diagnostic_AnonymousFunctionMultipleParametersAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Test
{
void Method(int x)
{
Action<int, int> a = (j, k) => throw new ArgumentException(""somemessage"", ""x"");
}
}",
GetCSharpNameofResultAt(8, 83, "x"));
}
[Fact]
public async Task Diagnostic_LocalFunction1Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Test
{
void Method(int x)
{
void AnotherMethod(int y, int z)
{
throw new ArgumentException(""somemessage"", ""x"");
}
}
}",
GetCSharpNameofResultAt(10, 60, "x"));
}
[Fact]
public async Task Diagnostic_LocalFunction2Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Test
{
void Method(int x)
{
void AnotherMethod(int y, int z)
{
throw new ArgumentException(""somemessage"", ""y"");
}
}
}",
GetCSharpNameofResultAt(10, 60, "y"));
}
[Fact]
public async Task Diagnostic_DelegateAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace ConsoleApp14
{
class Program
{
class test
{
Action<int> x2 = delegate (int xyz)
{
throw new ArgumentNullException(""xyz"");
};
}
}
}",
GetCSharpNameofResultAt(12, 49, "xyz"));
}
#endregion
private static DiagnosticResult GetBasicNameofResultAt(int line, int column, string name)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(name);
private static DiagnosticResult GetCSharpNameofResultAt(int line, int column, string name)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(name);
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Transactions;
namespace System.Data.ProviderBase
{
internal abstract partial class DbConnectionInternal
{
private bool _isInStasis;
private Transaction _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically
// _enlistedTransaction is a clone, so that transaction information can be queried even if the original transaction object is disposed.
// However, there are times when we need to know if the original transaction object was disposed, so we keep a reference to it here.
// This field should only be assigned a value at the same time _enlistedTransaction is updated.
// Also, this reference should not be disposed, since we aren't taking ownership of it.
private Transaction _enlistedTransactionOriginal;
protected internal Transaction EnlistedTransaction
{
get
{
return _enlistedTransaction;
}
set
{
Transaction currentEnlistedTransaction = _enlistedTransaction;
if (((null == currentEnlistedTransaction) && (null != value))
|| ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value)))
{ // WebData 20000024
// Pay attention to the order here:
// 1) defect from any notifications
// 2) replace the transaction
// 3) re-enlist in notifications for the new transaction
// SQLBUDT #230558 we need to use a clone of the transaction
// when we store it, or we'll end up keeping it past the
// duration of the using block of the TransactionScope
Transaction valueClone = null;
Transaction previousTransactionClone = null;
try
{
if (null != value)
{
valueClone = value.Clone();
}
// NOTE: rather than take locks around several potential round-
// trips to the server, and/or virtual function calls, we simply
// presume that you aren't doing something illegal from multiple
// threads, and check once we get around to finalizing things
// inside a lock.
lock (this)
{
// NOTE: There is still a race condition here, when we are
// called from EnlistTransaction (which cannot re-enlist)
// instead of EnlistDistributedTransaction (which can),
// however this should have been handled by the outer
// connection which checks to ensure that it's OK. The
// only case where we have the race condition is multiple
// concurrent enlist requests to the same connection, which
// is a bit out of line with something we should have to
// support.
// enlisted transaction can be nullified in Dispose call without lock
previousTransactionClone = Interlocked.Exchange(ref _enlistedTransaction, valueClone);
_enlistedTransactionOriginal = value;
value = valueClone;
valueClone = null; // we've stored it, don't dispose it.
}
}
finally
{
// we really need to dispose our clones; they may have
// native resources and GC may not happen soon enough.
// VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction
if (null != previousTransactionClone &&
!object.ReferenceEquals(previousTransactionClone, _enlistedTransaction))
{
previousTransactionClone.Dispose();
}
if (null != valueClone && !object.ReferenceEquals(valueClone, _enlistedTransaction))
{
valueClone.Dispose();
}
}
// I don't believe that we need to lock to protect the actual
// enlistment in the transaction; it would only protect us
// against multiple concurrent calls to enlist, which really
// isn't supported anyway.
if (null != value)
{
TransactionOutcomeEnlist(value);
}
}
}
}
/// <summary>
/// Get boolean value that indicates whether the enlisted transaction has been disposed.
/// </summary>
/// <value>
/// True if there is an enlisted transaction, and it has been disposed.
/// False if there is an enlisted transaction that has not been disposed, or if the transaction reference is null.
/// </value>
/// <remarks>
/// This method must be called while holding a lock on the DbConnectionInternal instance.
/// </remarks>
protected bool EnlistedTransactionDisposed
{
get
{
// Until the Transaction.Disposed property is public it is necessary to access a member
// that throws if the object is disposed to determine if in fact the transaction is disposed.
try
{
bool disposed;
Transaction currentEnlistedTransactionOriginal = _enlistedTransactionOriginal;
if (currentEnlistedTransactionOriginal != null)
{
disposed = currentEnlistedTransactionOriginal.TransactionInformation == null;
}
else
{
// Don't expect to get here in the general case,
// Since this getter is called by CheckEnlistedTransactionBinding
// after checking for a non-null enlisted transaction (and it does so under lock).
disposed = false;
}
return disposed;
}
catch (ObjectDisposedException)
{
return true;
}
}
}
internal bool IsTxRootWaitingForTxEnd
{
get
{
return _isInStasis;
}
}
protected virtual bool UnbindOnTransactionCompletion
{
get
{
return true;
}
}
// Is this a connection that must be put in stasis (or is already in stasis) pending the end of it's transaction?
protected internal virtual bool IsNonPoolableTransactionRoot
{
get
{
return false; // if you want to have delegated transactions that are non-poolable, you better override this...
}
}
internal virtual bool IsTransactionRoot
{
get
{
return false; // if you want to have delegated transactions, you better override this...
}
}
protected virtual bool ReadyToPrepareTransaction
{
get
{
return true;
}
}
protected abstract void Activate(Transaction transaction);
internal void ActivateConnection(Transaction transaction)
{
// Internal method called from the connection pooler so we don't expose
// the Activate method publicly.
Activate(transaction);
}
internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
{
// The implementation here is the implementation required for the
// "open" internal connections, since our own private "closed"
// singleton internal connection objects override this method to
// prevent anything funny from happening (like disposing themselves
// or putting them into a connection pool)
//
// Derived class should override DbConnectionInternal.Deactivate and DbConnectionInternal.Dispose
// for cleaning up after DbConnection.Close
// protected override void Deactivate() { // override DbConnectionInternal.Close
// // do derived class connection deactivation for both pooled & non-pooled connections
// }
// public override void Dispose() { // override DbConnectionInternal.Close
// // do derived class cleanup
// base.Dispose();
// }
//
// overriding DbConnection.Close is also possible, but must provider for their own synchronization
// public override void Close() { // override DbConnection.Close
// base.Close();
// // do derived class outer connection for both pooled & non-pooled connections
// // user must do their own synchronization here
// }
//
// if the DbConnectionInternal derived class needs to close the connection it should
// delegate to the DbConnection if one exists or directly call dispose
// DbConnection owningObject = (DbConnection)Owner;
// if (null != owningObject) {
// owningObject.Close(); // force the closed state on the outer object.
// }
// else {
// Dispose();
// }
//
////////////////////////////////////////////////////////////////
// DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING!
////////////////////////////////////////////////////////////////
Debug.Assert(null != owningObject, "null owningObject");
Debug.Assert(null != connectionFactory, "null connectionFactory");
// if an exception occurs after the state change but before the try block
// the connection will be stuck in OpenBusy state. The commented out try-catch
// block doesn't really help because a ThreadAbort during the finally block
// would just revert the connection to a bad state.
// Open->Closed: guarantee internal connection is returned to correct pool
if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this))
{
// Lock to prevent race condition with cancellation
lock (this)
{
object lockToken = ObtainAdditionalLocksForClose();
try
{
PrepareForCloseConnection();
DbConnectionPool connectionPool = Pool;
// Detach from enlisted transactions that are no longer active on close
DetachCurrentTransactionIfEnded();
// The singleton closed classes won't have owners and
// connection pools, and we won't want to put them back
// into the pool.
if (null != connectionPool)
{
connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us...
// NOTE: Before we leave the PutObject call, another
// thread may have already popped the connection from
// the pool, so don't expect to be able to verify it.
}
else
{
Deactivate(); // ensure we de-activate non-pooled connections, or the data readers and transactions may not get cleaned up...
// To prevent an endless recursion, we need to clear
// the owning object before we call dispose so that
// we can't get here a second time... Ordinarily, I
// would call setting the owner to null a hack, but
// this is safe since we're about to dispose the
// object and it won't have an owner after that for
// certain.
_owningObject.Target = null;
if (IsTransactionRoot)
{
SetInStasis();
}
else
{
Dispose();
}
}
}
finally
{
ReleaseAdditionalLocksForClose(lockToken);
// if a ThreadAbort puts us here then its possible the outer connection will not reference
// this and this will be orphaned, not reclaimed by object pool until outer connection goes out of scope.
connectionFactory.SetInnerConnectionEvent(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
}
}
}
}
internal virtual void DelegatedTransactionEnded()
{
// Called by System.Transactions when the delegated transaction has
// completed. We need to make closed connections that are in stasis
// available again, or disposed closed/leaked non-pooled connections.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
if (1 == _pooledCount)
{
// When _pooledCount is 1, it indicates a closed, pooled,
// connection so it is ready to put back into the pool for
// general use.
TerminateStasis(true);
Deactivate(); // call it one more time just in case
DbConnectionPool pool = Pool;
if (null == pool)
{
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool
}
pool.PutObjectFromTransactedPool(this);
}
else if (-1 == _pooledCount && !_owningObject.IsAlive)
{
// When _pooledCount is -1 and the owning object no longer exists,
// it indicates a closed (or leaked), non-pooled connection so
// it is safe to dispose.
TerminateStasis(false);
Deactivate(); // call it one more time just in case
// it's a non-pooled connection, we need to dispose of it
// once and for all, or the server will have fits about us
// leaving connections open until the client-side GC kicks
// in.
Dispose();
}
// When _pooledCount is 0, the connection is a pooled connection
// that is either open (if the owning object is alive) or leaked (if
// the owning object is not alive) In either case, we can't muck
// with the connection here.
}
public virtual void Dispose()
{
_connectionPool = null;
_connectionIsDoomed = true;
_enlistedTransactionOriginal = null; // should not be disposed
// Dispose of the _enlistedTransaction since it is a clone
// of the original reference.
// VSDD 780271 - _enlistedTransaction can be changed by another thread (TX end event)
Transaction enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null);
if (enlistedTransaction != null)
{
enlistedTransaction.Dispose();
}
}
public abstract void EnlistTransaction(Transaction transaction);
// Cleanup connection's transaction-specific structures (currently used by Delegated transaction).
// This is a separate method because cleanup can be triggered in multiple ways for a delegated
// transaction.
protected virtual void CleanupTransactionOnCompletion(Transaction transaction)
{
}
internal void DetachCurrentTransactionIfEnded()
{
Transaction enlistedTransaction = EnlistedTransaction;
if (enlistedTransaction != null)
{
bool transactionIsDead;
try
{
transactionIsDead = (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status);
}
catch (TransactionException)
{
// If the transaction is being processed (i.e. is part way through a rollback\commit\etc then TransactionInformation.Status will throw an exception)
transactionIsDead = true;
}
if (transactionIsDead)
{
DetachTransaction(enlistedTransaction, true);
}
}
}
// Detach transaction from connection.
internal void DetachTransaction(Transaction transaction, bool isExplicitlyReleasing)
{
// potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new
// transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should
// be the exception, not the rule.
lock (this)
{
// Detach if detach-on-end behavior, or if outer connection was closed
DbConnection owner = (DbConnection)Owner;
if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner)
{
Transaction currentEnlistedTransaction = _enlistedTransaction;
if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction))
{
EnlistedTransaction = null;
if (IsTxRootWaitingForTxEnd)
{
DelegatedTransactionEnded();
}
}
}
}
}
// Handle transaction detach, pool cleanup and other post-transaction cleanup tasks associated with
internal void CleanupConnectionOnTransactionCompletion(Transaction transaction)
{
DetachTransaction(transaction, false);
DbConnectionPool pool = Pool;
if (null != pool)
{
pool.TransactionEnded(transaction, this);
}
}
private void TransactionCompletedEvent(object sender, TransactionEventArgs e)
{
Transaction transaction = e.Transaction;
CleanupTransactionOnCompletion(transaction);
CleanupConnectionOnTransactionCompletion(transaction);
}
private void TransactionOutcomeEnlist(Transaction transaction)
{
transaction.TransactionCompleted += new TransactionCompletedEventHandler(TransactionCompletedEvent);
}
internal void SetInStasis()
{
_isInStasis = true;
}
private void TerminateStasis(bool returningToPool)
{
_isInStasis = false;
}
}
}
| |
/*****************************************************************************
*
* Copyright(c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution.If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com.By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
****************************************************************************/
/*****************************************************************************
* XSharp.BV
* Based on IronStudio/IronPythonTools/IronPythonTools/Navigation
*
****************************************************************************/
using System;
using System.Globalization;
using Microsoft.VisualStudio.Shell.Interop;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
using VSConstants = Microsoft.VisualStudio.VSConstants;
using XSharpModel;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.Shell;
namespace XSharp.LanguageService
{
// Value are from OMGlyphs.h
internal enum IconImageIndex
{
// access types
AccessPublic = 0,
AccessInternal = 1,
AccessFriend = 2,
AccessProtected = 3,
AccessPrivate = 4,
AccessShortcut = 5,
Base = 6,
// Each of the following icon type has 6 versions,
//corresponding to the access types
_Class = Base * 0,
_Constant = Base * 1,
_Delegate = Base * 2,
_Enumeration = Base * 3,
_EnumMember = Base * 4,
_Event = Base * 5,
_Exception = Base * 6,
_Field = Base * 7,
_Interface = Base * 8,
_Macro = Base * 9,
_Map = Base * 10,
_MapItem = Base * 11,
_Method = Base * 12,
_OverloadedMethod = Base * 13,
_Module = Base * 14,
_Namespace = Base * 15,
_Operator = Base * 16,
_Property = Base * 17,
_Struct = Base * 18,
_Template = Base * 19,
_Typedef = Base * 20,
_Type = Base * 21,
_Union = Base * 22,
_VVariable = Base * 23,
_ValueType = Base * 24,
_Intrinsic = Base * 25,
_JavaMethod = Base * 26,
_JavaField = Base * 27,
_JavaClass = Base * 28,
_JavaNamespace = Base * 29,
_JavaInterface = Base * 30,
// Miscellaneous icons with one icon for each type.
_Error = 187,
_GreyedClass = 188,
_GreyedPrivateMethod = 189,
_GreyedProtectedMethod = 190,
_GreyedPublicMethod = 191,
_BrowseResourceFile = 192,
_Reference = 193,
_Library = 194,
_VBProject = 195,
_VBWebProject = 196,
_CSProject = 197,
_CSWebProject = 198,
_VB6Project = 199,
_CPlusProject = 200,
_Form = 201,
_OpenFolder = 201,
_ClosedFolder = 202,
_Arrow = 203,
_CSClass = 205,
_Snippet = 206,
_Keyword = 206,
_Info = 207,
_CallBrowserCall = 208,
_CallBrowserCallRecursive = 210,
_XMLEditor = 211,
_VJProject = 212,
_VJClass = 213,
_ForwardedType = 214,
_CallsTo = 215,
_CallsFrom = 216,
_Warning = 217,
};
internal class SourcePosition
{
internal string FileName { get; set; }
internal int Line { get; set; }
internal int Column { get; set; }
}
[DebuggerDisplay("{Name}")]
internal class XSharpLibraryNode : LibraryNode
{
internal IVsHierarchy ownerHierarchy;
internal List<uint> filesId;
private string fileMoniker;
// Description Infos...
private List<Tuple<string, VSOBDESCRIPTIONSECTION>> description;
private readonly SourcePosition editorInfo;
private string nodeText;
// ClassName & Namespace
private string nameSpace = "";
private string className = "";
private readonly Kind kind;
private readonly Modifiers attributes;
const string NEWLINE = "\n";
const string CONSTRUCTOR = "Constructor";
const string DEFAULTNAMESPACE = "Default NameSpace";
const string SUMMARY = "\nSummary:\n";
const string PARAMETERS = "\nParameters:";
const string RETURNS = "\nReturns:\n";
const string REMARKS = "\nRemarks:\n";
internal string FullPath { get; } = "";
internal XSharpLibraryNode(string namePrefix, LibraryNodeType nType, string path)
: base(namePrefix)
{
//
this.filesId = new List<uint>();
FullPath = path;
//
this.ownerHierarchy = null;
this.Depends(0);
//this.member = null;
this.NodeType = nType;
if (this.NodeType == LibraryNodeType.Namespaces)
{
BuildImageData(Kind.Namespace, Modifiers.Public);
}
//
description = new List<Tuple<string, VSOBDESCRIPTIONSECTION>>();
editorInfo = null;
}
internal XSharpLibraryNode(XSourceEntity entity, string namePrefix, IVsHierarchy hierarchy, uint itemId)
: base(String.IsNullOrEmpty(entity.FullName) ? namePrefix : entity.FullName)
{
kind = entity.Kind;
attributes = entity.Attributes;
if (kind == Kind.Namespace)
{
this.NodeType = LibraryNodeType.Namespaces;
}
else if (kind.IsType())
{
this.NodeType = LibraryNodeType.Classes;
}
else
{
this.NodeType = LibraryNodeType.Members;
}
//
this.filesId = new List<uint>();
//
this.ownerHierarchy = hierarchy;
this.Depends(itemId);
//this.member = scope;
// Can we Goto ?
if ((ownerHierarchy != null) && (VSConstants.VSITEMID_NIL != itemId))
{
this.CanGoToSource = true;
this.editorInfo = new SourcePosition()
{
FileName = entity.File.FullPath,
Line = entity.Range.StartLine + 1,
Column = entity.Range.StartColumn,
};
}
//
this.BuildImageData(entity.Kind, entity.Visibility);
this.InitText(entity);
this.InitDescription(entity);
}
private void BuildImageData(Kind elementType, Modifiers accessType)
{
int iImage = 0;
// First get the Icon
switch (elementType)
{
case Kind.Class:
iImage = (int)IconImageIndex._Class;
break;
case Kind.Structure:
case Kind.VOStruct:
iImage = (int)IconImageIndex._Struct;
break;
case Kind.Union:
iImage = (int)IconImageIndex._Union;
break;
case Kind.Delegate:
iImage = (int)IconImageIndex._Delegate;
break;
case Kind.Namespace:
iImage = (int)IconImageIndex._Namespace;
break;
case Kind.Constructor:
case Kind.Destructor:
case Kind.Method:
case Kind.Function:
case Kind.Procedure:
case Kind.LocalFunc:
case Kind.LocalProc:
case Kind.VODLL:
iImage = (int)IconImageIndex._Method;
break;
case Kind.Property:
case Kind.Access:
case Kind.Assign:
iImage = (int)IconImageIndex._Property;
break;
case Kind.Field:
case Kind.VOGlobal:
iImage = (int)IconImageIndex._Field;
break;
case Kind.Interface:
iImage = (int)IconImageIndex._Interface;
break;
case Kind.Event:
iImage = (int)IconImageIndex._Event;
break;
case Kind.Operator:
iImage = (int)IconImageIndex._Operator;
break;
case Kind.Enum:
iImage = (int)IconImageIndex._Enumeration;
break;
case Kind.VODefine:
iImage = (int)IconImageIndex._Constant;
break;
case Kind.EnumMember:
iImage = (int)IconImageIndex._EnumMember;
break;
case Kind.Local:
case Kind.Parameter:
case Kind.DbField:
iImage = (int)IconImageIndex._VVariable;
break;
case Kind.Using:
iImage = (int)IconImageIndex._Reference;
break;
default:
break;
}
//
switch (accessType)
{
case Modifiers.Public:
iImage += (int)IconImageIndex.AccessPublic;
break;
case Modifiers.Hidden:
iImage += (int)IconImageIndex.AccessPrivate;
break;
case Modifiers.Protected:
iImage += (int)IconImageIndex.AccessProtected;
break;
case Modifiers.Internal:
iImage += (int)IconImageIndex.AccessInternal;
break;
}
//
this.displayData.Image = (ushort)iImage;
this.displayData.SelectedImage = (ushort)iImage;
}
internal XSharpLibraryNode(XSharpLibraryNode node) :
base(node)
{
this.filesId = new List<uint>();
this.Depends(node.filesId);
this.ownerHierarchy = node.ownerHierarchy;
this.fileMoniker = node.fileMoniker;
//this.member = node.member;
this.NodeType = node.NodeType;
this.editorInfo = node.editorInfo;
this.description = node.description;
this.kind = node.kind;
this.attributes = node.attributes;
}
/// <summary>
/// Indicate that the Node belongs to a file/Module
/// </summary>
/// <param name="itemId">The File/Module Id</param>
/// <returns>The number of Files/Modules that points to that node</returns>
public int Depends(uint itemId)
{
this.filesId.Add(itemId);
return this.filesId.Count;
}
/// <summary>
/// Indicate that the Node belongs to a list of files/Modules
/// </summary>
/// <param name="itemId">The List of Files/Modules Id</param>
/// <returns>The number of Files/Modules that points to that node</returns>
public int Depends(List<uint> itemsId)
{
this.filesId.AddRange(itemsId);
return this.filesId.Count;
}
/// <summary>
/// Remove that File/Module Id from the Node owner's
/// </summary>
/// <param name="itemId">The File/Module Id </param>
/// <returns>The number of Files/Modules that continues to point to that node</returns>
public int Freeing(uint itemId)
{
this.filesId.Remove(itemId);
return this.filesId.Count;
}
private uint ClassAccess()
{
_LIBCAT_CLASSACCESS result = 0;
if ((attributes & Modifiers.VisibilityMask) == Modifiers.None)
result |= _LIBCAT_CLASSACCESS.LCCA_PUBLIC;
else
{
if (attributes.HasFlag(Modifiers.Sealed))
result |= _LIBCAT_CLASSACCESS.LCCA_SEALED;
if (attributes.HasFlag(Modifiers.Protected))
result |= _LIBCAT_CLASSACCESS.LCCA_PROTECTED;
if (attributes.HasFlag(Modifiers.Private))
result |= _LIBCAT_CLASSACCESS.LCCA_PRIVATE;
if (attributes.HasFlag(Modifiers.Public))
result |= _LIBCAT_CLASSACCESS.LCCA_PUBLIC;
if (attributes.HasFlag(Modifiers.Internal))
result |= _LIBCAT_CLASSACCESS.LCCA_FRIEND;
}
return (uint)result;
}
private uint MemberAccess()
{
_LIBCAT_MEMBERACCESS result = 0;
if ((attributes & Modifiers.VisibilityMask) == Modifiers.None)
result |= _LIBCAT_MEMBERACCESS.LCMA_PUBLIC;
else
{
if (attributes.HasFlag(Modifiers.Sealed))
result |= _LIBCAT_MEMBERACCESS.LCMA_SEALED;
if (attributes.HasFlag(Modifiers.Protected))
result |= _LIBCAT_MEMBERACCESS.LCMA_PROTECTED;
if (attributes.HasFlag(Modifiers.Private))
result |= _LIBCAT_MEMBERACCESS.LCMA_PRIVATE;
if (attributes.HasFlag(Modifiers.Public))
result |= _LIBCAT_MEMBERACCESS.LCMA_PUBLIC;
if (attributes.HasFlag(Modifiers.Internal))
result |= _LIBCAT_MEMBERACCESS.LCMA_FRIEND;
}
return (uint) result;
}
private _LIBCAT_MEMBERTYPE MemberType()
{
switch (kind)
{
case Kind.Method:
case Kind.Constructor:
case Kind.Destructor:
return _LIBCAT_MEMBERTYPE.LCMT_METHOD;
case Kind.Function:
case Kind.LocalFunc:
case Kind.Procedure:
case Kind.LocalProc:
return _LIBCAT_MEMBERTYPE.LCMT_FUNCTION;
case Kind.Operator:
return _LIBCAT_MEMBERTYPE.LCMT_OPERATOR;
case Kind.Property:
case Kind.Access:
case Kind.Assign:
return _LIBCAT_MEMBERTYPE.LCMT_PROPERTY;
case Kind.Field:
case Kind.VOGlobal:
return _LIBCAT_MEMBERTYPE.LCMT_FIELD;
case Kind.Local:
case Kind.Parameter:
case Kind.DbField:
case Kind.MemVar:
return _LIBCAT_MEMBERTYPE.LCMT_VARIABLE;
case Kind.Event:
return _LIBCAT_MEMBERTYPE.LCMT_EVENT;
case Kind.VODefine:
return _LIBCAT_MEMBERTYPE.LCMT_CONSTANT;
case Kind.EnumMember:
return _LIBCAT_MEMBERTYPE.LCMT_ENUMITEM;
case Kind.Class:
case Kind.Structure:
case Kind.VOStruct:
case Kind.Interface:
case Kind.Enum:
case Kind.Delegate:
case Kind.Union:
return _LIBCAT_MEMBERTYPE.LCMT_TYPEDEF;
default:
return _LIBCAT_MEMBERTYPE.LCMT_ERROR;
}
}
private _LIBCAT_CLASSTYPE ClassType()
{
switch (kind)
{
case Kind.Class:
return _LIBCAT_CLASSTYPE.LCCT_CLASS;
case Kind.Interface:
return _LIBCAT_CLASSTYPE.LCCT_INTERFACE;
case Kind.Structure:
case Kind.VOStruct:
case Kind.Union:
return _LIBCAT_CLASSTYPE.LCCT_STRUCT;
case Kind.Enum:
return _LIBCAT_CLASSTYPE.LCCT_ENUM;
// LCCT_MODULE
// LCCT_INTRINSIC
case Kind.Delegate:
return _LIBCAT_CLASSTYPE.LCCT_DELEGATE;
// LCCT_EXCEPTION
// LCCT_MAP
// LCCT_GLOBAL
default:
return _LIBCAT_CLASSTYPE.LCCT_ERROR;
}
}
private _LIBCAT_MODIFIERTYPE ModifierType()
{
_LIBCAT_MODIFIERTYPE result = (_LIBCAT_MODIFIERTYPE)0;
if (attributes.HasFlag(Modifiers.Static))
result |= _LIBCAT_MODIFIERTYPE.LCMDT_STATIC;
if (attributes.HasFlag(Modifiers.Virtual))
result |= _LIBCAT_MODIFIERTYPE.LCMDT_VIRTUAL;
else if (attributes.HasFlag(Modifiers.Override))
result |= _LIBCAT_MODIFIERTYPE.LCMDT_VIRTUAL;
else
result |= _LIBCAT_MODIFIERTYPE.LCMDT_NONVIRTUAL;
if (attributes.HasFlag(Modifiers.Sealed))
result |= _LIBCAT_MODIFIERTYPE.LCMDT_FINAL;
return result;
}
protected override uint CategoryField(LIB_CATEGORY category)
{
switch (category)
{
case (LIB_CATEGORY)_LIB_CATEGORY2.LC_MEMBERINHERITANCE:
if (this.NodeType == LibraryNodeType.Members)
{
return (uint)_LIBCAT_MEMBERINHERITANCE.LCMI_IMMEDIATE;
}
break;
case LIB_CATEGORY.LC_MEMBERTYPE:
return (uint)MemberType();
case LIB_CATEGORY.LC_MEMBERACCESS:
return this.MemberAccess();
case LIB_CATEGORY.LC_CLASSTYPE:
return (uint) this.ClassType();
case LIB_CATEGORY.LC_CLASSACCESS:
return (uint)this.ClassAccess();
case LIB_CATEGORY.LC_ACTIVEPROJECT:
return (uint)_LIBCAT_ACTIVEPROJECT.LCAP_SHOWALWAYS;
case LIB_CATEGORY.LC_LISTTYPE:
break;
case LIB_CATEGORY.LC_VISIBILITY:
return (uint) _LIBCAT_VISIBILITY.LCV_VISIBLE;
case LIB_CATEGORY.LC_MODIFIER:
return (uint) ModifierType();
case LIB_CATEGORY.LC_NODETYPE:
break;
default:
break;
}
return base.CategoryField(category);
}
internal override LibraryNode Clone()
{
return new XSharpLibraryNode(this);
}
protected override void GotoSource(VSOBJGOTOSRCTYPE gotoType)
{
// We do not support the "Goto Reference"
if (gotoType == VSOBJGOTOSRCTYPE.GS_REFERENCE)
{
return;
}
//
if (this.CanGoToSource && this.editorInfo != null)
{
// Need to retrieve the Project, then the File...
var file = XSolution.FindFile(editorInfo.FileName);
XSettings.OpenDocument(file.FullPath, editorInfo.Line, editorInfo.Column, true);
}
}
protected override void SourceItems(out IVsHierarchy hierarchy, out uint itemId, out uint itemsCount)
{
hierarchy = ownerHierarchy;
itemId = this.filesId[0];
itemsCount = 1;
}
protected override void SourceContext(out string pbstrFilename, out uint pulLineNum)
{
// default
pbstrFilename = null;
pulLineNum = 0;
//
if (this.editorInfo != null)
{
pbstrFilename = this.editorInfo.FileName;
pulLineNum = (uint)this.editorInfo.Line - 1;
}
}
protected override void Text(VSTREETEXTOPTIONS tto, out string pbstrText)
{
string descText = this.Name;
switch (tto)
{
case VSTREETEXTOPTIONS.TTO_PREFIX2:
//
descText = nameSpace;
break;
case VSTREETEXTOPTIONS.TTO_PREFIX:
//
descText = className;
break;
default:
if (nodeText != null)
{
descText = nodeText;
// No description for Project
if ((tto == VSTREETEXTOPTIONS.TTO_SEARCHTEXT) && (this.NodeType == LibraryNodeType.Package))
{
descText = "";
}
}
break;
}
pbstrText = descText;
}
private void InitText(XSourceEntity member)
{
string descText = this.Name;
//
if (member != null)
{
if (member.Parent is XSourceTypeSymbol symbol)
{
nameSpace = symbol.Namespace;
className = symbol.Name;
}
//
descText = member.Name;
if (member is XSourceMemberSymbol)
{
var tm = member as XSourceMemberSymbol;
descText = tm.Kind == Kind.Constructor ? CONSTRUCTOR : member.Name;
if (tm.Kind.HasParameters())
{
descText += tm.Kind == Kind.Constructor ? "{" : "( ";
if (tm.HasParameters)
{
//
descText += tm.ParameterList;
}
descText += tm.Kind == Kind.Constructor ? "}" : ") ";
}
}
else if (member is XSourceTypeSymbol)
{
var tm = member as XSourceTypeSymbol;
if ((tm.Kind == Kind.Namespace) && (String.IsNullOrEmpty(descText)))
{
descText = DEFAULTNAMESPACE;
}
}
}
nodeText = descText;
}
public string NodeText => nodeText ?? "";
protected override void buildDescription(_VSOBJDESCOPTIONS flags, IVsObjectBrowserDescription3 obDescription)
{
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
obDescription.ClearDescriptionText();
try
{
foreach (var element in description)
{
obDescription.AddDescriptionText3(element.Item1, element.Item2, null);
}
}
catch { }
});
}
private Tuple<string, VSOBDESCRIPTIONSECTION> Item (string item1, VSOBDESCRIPTIONSECTION item2)
{
return new Tuple<string, VSOBDESCRIPTIONSECTION>(item1, item2);
}
private void InitDescription(XSourceEntity member) //, _VSOBJDESCOPTIONS flags, IVsObjectBrowserDescription3 description)
{
description = new List<Tuple<string, VSOBDESCRIPTIONSECTION>>();
string descText ;
if (member != null)
{
string modifier = "";
string access = "";
if ((member is XSourceTypeSymbol) && (member.Kind != Kind.Namespace))
{
modifier = member.Modifiers.ToDisplayString() ;
access = member.Visibility.ToDisplayString() ;
}
else if ((member is XSourceMemberSymbol) && ((member.Kind != Kind.Function) && (member.Kind != Kind.Procedure)))
{
modifier = member.Modifiers.ToDisplayString();
access = member.Visibility.ToDisplayString() ;
}
//
if (!string.IsNullOrEmpty(modifier))
{
description.Add(Item(modifier + " ", VSOBDESCRIPTIONSECTION.OBDS_ATTRIBUTE));
}
//
if (!string.IsNullOrEmpty(access))
{
description.Add(Item(access + " ", VSOBDESCRIPTIONSECTION.OBDS_ATTRIBUTE));
}
//
if (member.Kind != Kind.Field)
{
VSOBDESCRIPTIONSECTION descName = VSOBDESCRIPTIONSECTION.OBDS_MISC;
descText = XSettings.FormatKeyword(member.Kind.DisplayName()) + " ";
if (member.Kind == Kind.Constructor)
{
descName = VSOBDESCRIPTIONSECTION.OBDS_NAME;
}
description.Add(Item(descText, descName));
}
if (member.Kind != Kind.Constructor)
{
descText = member.Name;
description.Add(Item(descText, VSOBDESCRIPTIONSECTION.OBDS_NAME));
}
// Parameters ?
if (member.Kind.HasParameters())
{
descText = "(";
description.Add(Item(descText, VSOBDESCRIPTIONSECTION.OBDS_MISC));
XSourceMemberSymbol realmember;
XSourceTypeSymbol type = member as XSourceTypeSymbol;
if (member.Kind == Kind.Delegate && type?.XMembers.Count > 0)
realmember = type.XMembers[0] ;
else
realmember = member as XSourceMemberSymbol;
if (realmember != null && realmember.HasParameters)
{
//
int paramNum = 1;
foreach (IXParameterSymbol param in realmember.Parameters)
{
descText = param.Name;
description.Add(Item(descText, VSOBDESCRIPTIONSECTION.OBDS_PARAM));
descText = param.ParamTypeDesc;
description.Add(Item(descText, VSOBDESCRIPTIONSECTION.OBDS_MISC));
descText = param.TypeName;
//
description.Add(Item(descText, VSOBDESCRIPTIONSECTION.OBDS_TYPE));
// Need a comma ?
if (paramNum < realmember.ParameterCount)
{
paramNum++;
descText = ",";
description.Add(Item(descText, VSOBDESCRIPTIONSECTION.OBDS_COMMA));
}
}
}
descText = ")";
description.Add(Item(descText, VSOBDESCRIPTIONSECTION.OBDS_MISC));
}
if (member.Kind.HasReturnType())
{
descText = XLiterals.AsKeyWord;
description.Add(Item(descText, VSOBDESCRIPTIONSECTION.OBDS_MISC));
descText = member.TypeName;
description.Add(Item(descText, VSOBDESCRIPTIONSECTION.OBDS_TYPE));
}
description.Add(Item(null, VSOBDESCRIPTIONSECTION.OBDS_ENDDECL));
}
//
if (member.File?.Project != null)
{
string summary=null, returns=null, remarks=null;
List<string> pNames = new List<string>();
List<string> pDescriptions = new List<string>();
if (member is XSourceMemberSymbol symbol1)
{
summary = XSharpXMLDocMember.GetMemberSummary(symbol1, member.File?.Project, out returns, out remarks);
XSharpXMLDocMember.GetMemberParameters(symbol1, member.File?.Project, pNames, pDescriptions);
}
else if (member is XSourceTypeSymbol symbol)
{
summary = XSharpXMLDocMember.GetTypeSummary(symbol, member.File?.Project, out returns, out remarks);
}
if (!string.IsNullOrEmpty(summary))
{
description.Add(Item(NEWLINE, VSOBDESCRIPTIONSECTION.OBDS_MISC));
description.Add(Item(SUMMARY, VSOBDESCRIPTIONSECTION.OBDS_NAME));
description.Add(Item(summary, VSOBDESCRIPTIONSECTION.OBDS_MISC));
}
if (pNames.Count > 0)
{
description.Add(Item(NEWLINE, VSOBDESCRIPTIONSECTION.OBDS_MISC));
description.Add(Item(PARAMETERS, VSOBDESCRIPTIONSECTION.OBDS_NAME));
for( int i =0; i < pNames.Count; i++)
{
description.Add(Item(NEWLINE + pNames[i], VSOBDESCRIPTIONSECTION.OBDS_PARAM));
description.Add(Item(" : ", VSOBDESCRIPTIONSECTION.OBDS_MISC));
description.Add(Item(pDescriptions[i], VSOBDESCRIPTIONSECTION.OBDS_MISC));
}
}
if (!string.IsNullOrEmpty(returns))
{
description.Add(Item(NEWLINE, VSOBDESCRIPTIONSECTION.OBDS_MISC));
description.Add(Item(RETURNS, VSOBDESCRIPTIONSECTION.OBDS_NAME));
description.Add(Item(returns, VSOBDESCRIPTIONSECTION.OBDS_MISC));
}
if (!string.IsNullOrEmpty(remarks))
{
description.Add(Item(NEWLINE, VSOBDESCRIPTIONSECTION.OBDS_MISC));
description.Add(Item(REMARKS, VSOBDESCRIPTIONSECTION.OBDS_NAME));
description.Add(Item(remarks, VSOBDESCRIPTIONSECTION.OBDS_MISC));
}
}
}
public override string UniqueName
{
get
{
if (string.IsNullOrEmpty(fileMoniker))
{
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if ((this.filesId.Count > 0) && (this.filesId[0] != VSConstants.VSITEMID_NIL))
{
if (ownerHierarchy != null)
{
ErrorHandler.ThrowOnFailure(ownerHierarchy.GetCanonicalName(this.filesId[0], out fileMoniker));
}
}
});
}
string result = "";
if (fileMoniker != null)
result = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", fileMoniker, Name);
return result;
}
}
/// <summary>
/// Search for a class, whose Fully Qualified Name is known
/// </summary>
/// <param name="fqName">The Fully Qualified Name class to search for</param>
/// <returns></returns>
public LibraryNode SearchClass(string fqName)
{
//
var result = children.Find(node => MatchesName(node, fqName));
if (result == null)
{
foreach (XSharpLibraryNode child in children)
{
result = child.SearchClass(fqName);
if (result != null)
break;
}
}
return result;
}
bool MatchesName(LibraryNode node, string name)
{
return String.Compare(node.Name, name, true) == 0 &&
(node.NodeType & LibraryNodeType.Classes) != LibraryNodeType.None;
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using XmlCoreTest.Common;
using Xunit;
namespace System.Xml.Tests
{
public class TCAttribute
{
// Sanity test for WriteAttribute
[Theory]
[XmlWriterInlineData]
public void attribute_1(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteStartAttribute("attr1");
w.WriteEndAttribute();
w.WriteAttributeString("attr2", "val2");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root attr1=\"\" attr2=\"val2\" />"));
}
// Missing EndAttribute should be fixed
[Theory]
[XmlWriterInlineData]
public void attribute_2(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteStartAttribute("attr1");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root attr1=\"\" />"));
}
// WriteStartAttribute followed by WriteStartAttribute
[Theory]
[XmlWriterInlineData]
public void attribute_3(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteStartAttribute("attr1");
w.WriteStartAttribute("attr2");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root attr1=\"\" attr2=\"\" />"));
}
// Multiple WritetAttributeString
[Theory]
[XmlWriterInlineData]
public void attribute_4(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteAttributeString("attr1", "val1");
w.WriteAttributeString("attr2", "val2");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root attr1=\"val1\" attr2=\"val2\" />"));
}
// WriteStartAttribute followed by WriteString
[Theory]
[XmlWriterInlineData]
public void attribute_5(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteStartAttribute("attr1");
w.WriteString("test");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root attr1=\"test\" />"));
}
// Sanity test for overload WriteStartAttribute(name, ns)
[Theory]
[XmlWriterInlineData]
public void attribute_6(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteStartAttribute("attr1", "http://my.com");
w.WriteEndAttribute();
w.WriteEndElement();
}
Assert.True(utils.CompareString("<Root ~a p1 a~:attr1=\"\" xmlns:~a p1 A~=\"http://my.com\" />"));
}
// Sanity test for overload WriteStartAttribute(prefix, name, ns)
[Theory]
[XmlWriterInlineData]
public void attribute_7(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteStartAttribute("pre1", "attr1", "http://my.com");
w.WriteEndAttribute();
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root pre1:attr1=\"\" xmlns:pre1=\"http://my.com\" />"));
}
// DCR 64183: Duplicate attribute 'attr1'
[Theory]
[XmlWriterInlineData]
public void attribute_8(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
try
{
w.WriteStartElement("Root");
w.WriteStartAttribute("attr1");
w.WriteStartAttribute("attr1");
}
catch (XmlException e)
{
CError.WriteLineIgnore("Exception: " + e.ToString());
CError.Compare(w.WriteState, WriteState.Error, "WriteState should be Error");
return;
}
}
CError.WriteLine("Did not throw exception");
Assert.True(false);
}
// Duplicate attribute 'ns1:attr1'
[Theory]
[XmlWriterInlineData]
public void attribute_9(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
try
{
w.WriteStartElement("Root");
w.WriteStartAttribute("ns1", "attr1", "http://my.com");
w.WriteStartAttribute("ns1", "attr1", "http://my.com");
}
catch (XmlException e)
{
CError.WriteLineIgnore("Exception: " + e.ToString());
CError.Compare(w.WriteState, WriteState.Error, "WriteState should be Error");
return;
}
}
CError.WriteLine("Did not throw exception");
Assert.True(false);
}
// Attribute name = String.Empty should error
[Theory]
[XmlWriterInlineData]
public void attribute_10(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
try
{
w.WriteStartElement("Root");
w.WriteStartAttribute(string.Empty);
}
catch (ArgumentException e)
{
CError.WriteLineIgnore("Exception: " + e.ToString());
CError.Compare(w.WriteState, (utils.WriterType == WriterType.CharCheckingWriter) ? WriteState.Element : WriteState.Error, "WriteState should be Error");
return;
}
}
CError.WriteLine("Did not throw exception");
Assert.True(false);
}
// Attribute name = null
[Theory]
[XmlWriterInlineData]
public void attribute_11(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
try
{
w.WriteStartElement("Root");
w.WriteStartAttribute(null);
}
catch (ArgumentException e)
{
CError.WriteLineIgnore("Exception: " + e.ToString());
CError.Compare(w.WriteState, (utils.WriterType == WriterType.CharCheckingWriter) ? WriteState.Element : WriteState.Error, "WriteState should be Error");
return;
}
}
CError.WriteLine("Did not throw exception");
Assert.True(false);
}
// WriteAttribute with names Foo, fOo, foO, FOO
[Theory]
[XmlWriterInlineData]
public void attribute_12(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
string[] attrNames = { "Foo", "fOo", "foO", "FOO" };
w.WriteStartElement("Root");
for (int i = 0; i < attrNames.Length; i++)
{
w.WriteAttributeString(attrNames[i], "x");
}
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root Foo=\"x\" fOo=\"x\" foO=\"x\" FOO=\"x\" />"));
}
// Invalid value of xml:space
[Theory]
[XmlWriterInlineData]
public void attribute_13(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
try
{
w.WriteStartElement("Root");
w.WriteAttributeString("xml", "space", "http://www.w3.org/XML/1998/namespace", "invalid");
}
catch (ArgumentException e)
{
CError.WriteLineIgnore("Exception: " + e.ToString());
CError.Compare(w.WriteState, WriteState.Error, "WriteState should be Error");
return;
}
}
CError.WriteLine("Did not throw exception");
Assert.True(false);
}
// SingleQuote in attribute value should be allowed
[Theory]
[XmlWriterInlineData]
public void attribute_14(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteAttributeString("a", null, "b'c");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root a=\"b'c\" />"));
}
// DoubleQuote in attribute value should be escaped
[Theory]
[XmlWriterInlineData]
public void attribute_15(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteAttributeString("a", null, "b\"c");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root a=\"b"c\" />"));
}
// WriteAttribute with value = &, #65, #x20
[Theory]
[XmlWriterInlineData]
public void attribute_16(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteAttributeString("a", "&");
w.WriteAttributeString("b", "A");
w.WriteAttributeString("c", "C");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root a=\"&\" b=\"&#65;\" c=\"&#x43;\" />"));
}
// WriteAttributeString followed by WriteString
[Theory]
[XmlWriterInlineData]
public void attribute_17(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteAttributeString("a", null, "b");
w.WriteString("test");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root a=\"b\">test</Root>"));
}
// WriteAttribute followed by WriteString
[Theory]
[XmlWriterInlineData]
public void attribute_18(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteStartAttribute("a");
w.WriteString("test");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root a=\"test\" />"));
}
// WriteAttribute with all whitespace characters
[Theory]
[XmlWriterInlineData]
public void attribute_19(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteAttributeString("a", null, "\x20\x9\xD\xA");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root a=\" 	
\" />"));
}
// < > & chars should be escaped in attribute value
[Theory]
[XmlWriterInlineData]
public void attribute_20(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("Root");
w.WriteAttributeString("a", null, "< > &");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<Root a=\"< > &\" />"));
}
// Redefine auto generated prefix n1
[Theory]
[XmlWriterInlineData]
public void attribute_21(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("test");
w.WriteAttributeString("xmlns", "n1", null, "http://testbasens");
w.WriteStartElement("base");
w.WriteAttributeString("id", "http://testbasens", "5");
w.WriteAttributeString("lang", "http://common", "en");
w.WriteEndElement();
w.WriteEndElement();
}
string exp = utils.IsIndent() ?
"<test xmlns:n1=\"http://testbasens\">" + Environment.NewLine + " <base n1:id=\"5\" p4:lang=\"en\" xmlns:p4=\"http://common\" />" + Environment.NewLine + "</test>" :
"<test xmlns:~f n1 A~=\"http://testbasens\"><base ~f n1 a~:id=\"5\" ~a p4 a~:lang=\"en\" xmlns:~a p4 A~=\"http://common\" /></test>";
Assert.True(utils.CompareString(exp));
}
// Reuse and redefine existing prefix
[Theory]
[XmlWriterInlineData]
public void attribute_22(XmlWriterUtils utils)
{
string exp = "<test ~f p a~:a1=\"v\" xmlns:~f p A~=\"ns1\"><base ~f p b~:a2=\"v\" ~a p4 ab~:a3=\"v\" xmlns:~a p4 AB~=\"ns2\" /></test>";
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("test");
w.WriteAttributeString("p", "a1", "ns1", "v");
w.WriteStartElement("base");
w.WriteAttributeString("a2", "ns1", "v");
w.WriteAttributeString("p", "a3", "ns2", "v");
w.WriteEndElement();
w.WriteEndElement();
}
exp = utils.IsIndent() ?
"<test p:a1=\"v\" xmlns:p=\"ns1\">" + Environment.NewLine + " <base p:a2=\"v\" p4:a3=\"v\" xmlns:p4=\"ns2\" />" + Environment.NewLine + "</test>" : exp;
Assert.True(utils.CompareString(exp));
}
// WriteStartAttribute(attr) sanity test
[Theory]
[XmlWriterInlineData]
public void attribute_23(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("test");
w.WriteStartAttribute("attr");
w.WriteEndAttribute();
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<test attr=\"\" />"));
}
// WriteStartAttribute(attr) inside an element with changed default namespace
[Theory]
[XmlWriterInlineData]
public void attribute_24(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement(string.Empty, "test", "ns");
w.WriteStartAttribute("attr");
w.WriteEndAttribute();
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<test attr=\"\" xmlns=\"ns\" />"));
}
// WriteStartAttribute(attr) and duplicate attrs
[Theory]
[XmlWriterInlineData]
public void attribute_25(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
try
{
w.WriteStartElement("test");
w.WriteStartAttribute(null, "attr", null);
w.WriteStartAttribute("attr");
}
catch (XmlException e)
{
CError.WriteLineIgnore("Exception: " + e.ToString());
return;
}
}
CError.WriteLine("Did not throw error for duplicate attrs");
Assert.True(false);
}
// WriteStartAttribute(attr) when element has ns:attr
[Theory]
[XmlWriterInlineData]
public void attribute_26(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("pre", "test", "ns");
w.WriteStartAttribute(null, "attr", "ns");
w.WriteStartAttribute("attr");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<pre:test pre:attr=\"\" attr=\"\" xmlns:pre=\"ns\" />"));
}
// XmlCharCheckingWriter should not normalize newLines in attribute values when NewLinesHandling = Replace
[Theory]
[XmlWriterInlineData]
public void attribute_27(XmlWriterUtils utils)
{
XmlWriterSettings s = new XmlWriterSettings();
s.NewLineHandling = NewLineHandling.Replace;
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("root");
w.WriteAttributeString("a", "|\x0D|\x0A|\x0D\x0A|");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<root a=\"|
|
|
|\" />"));
}
// Wrapped XmlTextWriter: Invalid replacement of newline characters in text values
[Theory]
[XmlWriterInlineData]
public void attribute_28(XmlWriterUtils utils)
{
XmlWriterSettings s = new XmlWriterSettings();
s.NewLineHandling = NewLineHandling.Replace;
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("root");
w.WriteAttributeString("a", "|\x0D\x0A|");
w.WriteElementString("foo", "|\x0D\x0A|");
w.WriteEndElement();
}
Assert.True(utils.CompareReader("<root a=\"|
|\"><foo>|\x0D\x0A|</foo></root>"));
}
// WriteAttributeString doesn't fail on invalid surrogate pair sequences
[Theory]
[XmlWriterInlineData]
public void attribute_29(XmlWriterUtils utils)
{
using (XmlWriter w = utils.CreateWriter())
{
w.WriteStartElement("root");
try
{
w.WriteAttributeString("attribute", "\ud800\ud800");
}
catch (ArgumentException e)
{
CError.WriteLineIgnore(e.ToString());
return;
}
}
Assert.True(false);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.SiteRecovery;
using Microsoft.Azure.Management.SiteRecovery.Models;
namespace Microsoft.Azure.Management.SiteRecovery
{
public static partial class VCenterOperationsExtensions
{
/// <summary>
/// Creates a vCenter
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='input'>
/// Required. Input to create vCenter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginCreating(this IVCenterOperations operations, string fabricName, string vCenterName, CreateVCenterInput input, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).BeginCreatingAsync(fabricName, vCenterName, input, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a vCenter
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='input'>
/// Required. Input to create vCenter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginCreatingAsync(this IVCenterOperations operations, string fabricName, string vCenterName, CreateVCenterInput input, CustomRequestHeaders customRequestHeaders)
{
return operations.BeginCreatingAsync(fabricName, vCenterName, input, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Deletes a vCenter
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginDeleting(this IVCenterOperations operations, string fabricName, string vCenterName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).BeginDeletingAsync(fabricName, vCenterName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a vCenter
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginDeletingAsync(this IVCenterOperations operations, string fabricName, string vCenterName, CustomRequestHeaders customRequestHeaders)
{
return operations.BeginDeletingAsync(fabricName, vCenterName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Update vCenter.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='input'>
/// Required. Input to update vCenter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginUpdating(this IVCenterOperations operations, string fabricName, string vCenterName, UpdateVCenterInput input, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).BeginUpdatingAsync(fabricName, vCenterName, input, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update vCenter.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='input'>
/// Required. Input to update vCenter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginUpdatingAsync(this IVCenterOperations operations, string fabricName, string vCenterName, UpdateVCenterInput input, CustomRequestHeaders customRequestHeaders)
{
return operations.BeginUpdatingAsync(fabricName, vCenterName, input, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Creates a vCenter
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='input'>
/// Required. Input to create vCenter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse Create(this IVCenterOperations operations, string fabricName, string vCenterName, CreateVCenterInput input, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).CreateAsync(fabricName, vCenterName, input, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a vCenter
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='input'>
/// Required. Input to create vCenter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> CreateAsync(this IVCenterOperations operations, string fabricName, string vCenterName, CreateVCenterInput input, CustomRequestHeaders customRequestHeaders)
{
return operations.CreateAsync(fabricName, vCenterName, input, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Deletes a vCenter
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse Delete(this IVCenterOperations operations, string fabricName, string vCenterName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).DeleteAsync(fabricName, vCenterName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a vCenter
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> DeleteAsync(this IVCenterOperations operations, string fabricName, string vCenterName, CustomRequestHeaders customRequestHeaders)
{
return operations.DeleteAsync(fabricName, vCenterName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the vCenter object by Id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the vCenter object
/// </returns>
public static VCenterResponse Get(this IVCenterOperations operations, string fabricName, string vCenterName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).GetAsync(fabricName, vCenterName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the vCenter object by Id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the vCenter object
/// </returns>
public static Task<VCenterResponse> GetAsync(this IVCenterOperations operations, string fabricName, string vCenterName, CustomRequestHeaders customRequestHeaders)
{
return operations.GetAsync(fabricName, vCenterName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static CreateVCenterOperationResponse GetCreateStatus(this IVCenterOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).GetCreateStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<CreateVCenterOperationResponse> GetCreateStatusAsync(this IVCenterOperations operations, string operationStatusLink)
{
return operations.GetCreateStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse GetDeleteStatus(this IVCenterOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).GetDeleteStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> GetDeleteStatusAsync(this IVCenterOperations operations, string operationStatusLink)
{
return operations.GetDeleteStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static UpdateVCenterOperationResponse GetUpdateStatus(this IVCenterOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).GetUpdateStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<UpdateVCenterOperationResponse> GetUpdateStatusAsync(this IVCenterOperations operations, string operationStatusLink)
{
return operations.GetUpdateStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Get the list of all vCenters under a fabric.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the list vCenters operation.
/// </returns>
public static VCenterListResponse List(this IVCenterOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).ListAsync(fabricName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of all vCenters under a fabric.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the list vCenters operation.
/// </returns>
public static Task<VCenterListResponse> ListAsync(this IVCenterOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders)
{
return operations.ListAsync(fabricName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the list of all vCenters under the vault.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the list vCenters operation.
/// </returns>
public static VCenterListResponse ListAll(this IVCenterOperations operations, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).ListAllAsync(customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of all vCenters under the vault.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the list vCenters operation.
/// </returns>
public static Task<VCenterListResponse> ListAllAsync(this IVCenterOperations operations, CustomRequestHeaders customRequestHeaders)
{
return operations.ListAllAsync(customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Update vCenter.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='input'>
/// Required. Input to update vCenter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse Update(this IVCenterOperations operations, string fabricName, string vCenterName, UpdateVCenterInput input, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVCenterOperations)s).UpdateAsync(fabricName, vCenterName, input, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update vCenter.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.SiteRecovery.IVCenterOperations.
/// </param>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='vCenterName'>
/// Required. vCenter Name.
/// </param>
/// <param name='input'>
/// Required. Input to update vCenter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> UpdateAsync(this IVCenterOperations operations, string fabricName, string vCenterName, UpdateVCenterInput input, CustomRequestHeaders customRequestHeaders)
{
return operations.UpdateAsync(fabricName, vCenterName, input, customRequestHeaders, CancellationToken.None);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Pgno = System.UInt32;
using i64 = System.Int64;
using u32 = System.UInt32;
using BITVEC_TELEM = System.Byte;
namespace System.Data.SQLite
{
public partial class Sqlite3
{
/*
** 2008 February 16
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements an object that represents a fixed-length
** bitmap. Bits are numbered starting with 1.
**
** A bitmap is used to record which pages of a database file have been
** journalled during a transaction, or which pages have the "dont-write"
** property. Usually only a few pages are meet either condition.
** So the bitmap is usually sparse and has low cardinality.
** But sometimes (for example when during a DROP of a large table) most
** or all of the pages in a database can get journalled. In those cases,
** the bitmap becomes dense with high cardinality. The algorithm needs
** to handle both cases well.
**
** The size of the bitmap is fixed when the object is created.
**
** All bits are clear when the bitmap is created. Individual bits
** may be set or cleared one at a time.
**
** Test operations are about 100 times more common that set operations.
** Clear operations are exceedingly rare. There are usually between
** 5 and 500 set operations per Bitvec object, though the number of sets can
** sometimes grow into tens of thousands or larger. The size of the
** Bitvec object is the number of pages in the database file at the
** start of a transaction, and is thus usually less than a few thousand,
** but can be as large as 2 billion for a really big database.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
/* Size of the Bitvec structure in bytes. */
static int BITVEC_SZ = 512;
/* Round the union size down to the nearest pointer boundary, since that's how
** it will be aligned within the Bitvec struct. */
//#define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
static int BITVEC_USIZE = (((BITVEC_SZ - (3 * sizeof(u32))) / 4) * 4);
/* Type of the array "element" for the bitmap representation.
** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
** Setting this to the "natural word" size of your CPU may improve
** performance. */
//#define BITVEC_TELEM u8
//using BITVEC_TELEM = System.Byte;
/* Size, in bits, of the bitmap element. */
//#define BITVEC_SZELEM 8
const int BITVEC_SZELEM = 8;
/* Number of elements in a bitmap array. */
//#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
static int BITVEC_NELEM = (int)(BITVEC_USIZE / sizeof(BITVEC_TELEM));
/* Number of bits in the bitmap array. */
//#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
static int BITVEC_NBIT = (BITVEC_NELEM * BITVEC_SZELEM);
/* Number of u32 values in hash table. */
//#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
static u32 BITVEC_NINT = (u32)(BITVEC_USIZE / sizeof(u32));
/* Maximum number of entries in hash table before
** sub-dividing and re-hashing. */
//#define BITVEC_MXHASH (BITVEC_NINT/2)
static int BITVEC_MXHASH = (int)(BITVEC_NINT / 2);
/* Hashing function for the aHash representation.
** Empirical testing showed that the *37 multiplier
** (an arbitrary prime)in the hash function provided
** no fewer collisions than the no-op *1. */
//#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
static u32 BITVEC_HASH(u32 X)
{
return (u32)(((X) * 1) % BITVEC_NINT);
}
static int BITVEC_NPTR = (int)(BITVEC_USIZE / 4);//sizeof(Bitvec *));
public class _u
{
public BITVEC_TELEM[] aBitmap = new byte[BITVEC_NELEM]; /* Bitmap representation */
public u32[] aHash = new u32[BITVEC_NINT]; /* Hash table representation */
public Bitvec[] apSub = new Bitvec[BITVEC_NPTR]; /* Recursive representation */
}
/// <summary>
/// A bitmap is an instance of the following structure.
///
/// This bitmap records the existence of zero or more bits
/// with values between 1 and iSize, inclusive.
///
/// There are three possible representations of the bitmap.
/// If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
/// bitmap. The least significant bit is bit 1.
///
/// If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
/// a hash table that will hold up to BITVEC_MXHASH distinct values.
///
/// Otherwise, the value i is redirected into one of BITVEC_NPTR
/// sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
/// handles up to iDivisor separate values of i. apSub[0] holds
/// values between 1 and iDivisor. apSub[1] holds values between
/// iDivisor+1 and 2*iDivisor. apSub[N] holds values between
/// N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
/// to hold deal with values between 1 and iDivisor.
/// </summary>
public class Bitvec
{
public u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
public u32 nSet; /* Number of bits that are set - only valid for aHash
** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
** this would be 125. */
public u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
/* Should >=0 for apSub element. */
/* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
/* For a BITVEC_SZ of 512, this would be 34,359,739. */
public _u u = new _u();
public static implicit operator bool(Bitvec b)
{
return (b != null);
}
};
/// <summary>
/// Create a new bitmap object able to handle bits between 0 and iSize,
/// inclusive. Return a pointer to the new object. Return NULL if
/// malloc fails.
/// </summary>
static Bitvec sqlite3BitvecCreate(u32 iSize)
{
Bitvec p;
//Debug.Assert( sizeof(p)==BITVEC_SZ );
p = new Bitvec();//sqlite3MallocZero( sizeof(p) );
if (p != null)
{
p.iSize = iSize;
}
return p;
}
/// <summary>
/// Check to see if the i-th bit is set. Return true or false.
/// If p is NULL (if the bitmap has not been created) or if
/// i is out of range, then return false.
/// </summary>
static int sqlite3BitvecTest(Bitvec p, u32 i)
{
if (p == null || i == 0)
return 0;
if (i > p.iSize)
return 0;
i--;
while (p.iDivisor != 0)
{
u32 bin = i / p.iDivisor;
i = i % p.iDivisor;
p = p.u.apSub[bin];
if (null == p)
{
return 0;
}
}
if (p.iSize <= BITVEC_NBIT)
{
return ((p.u.aBitmap[i / BITVEC_SZELEM] & (1 << (int)(i & (BITVEC_SZELEM - 1)))) != 0) ? 1 : 0;
}
else
{
u32 h = BITVEC_HASH(i++);
while (p.u.aHash[h] != 0)
{
if (p.u.aHash[h] == i)
return 1;
h = (h + 1) % BITVEC_NINT;
}
return 0;
}
}
/// <summary>
/// Set the i-th bit. Return 0 on success and an error code if
/// anything goes wrong.
///
/// This routine might cause sub-bitmaps to be allocated. Failing
/// to get the memory needed to hold the sub-bitmap is the only
/// that can go wrong with an insert, assuming p and i are valid.
///
/// The calling function must ensure that p is a valid Bitvec object
/// and that the value for "i" is within range of the Bitvec object.
/// Otherwise the behavior is undefined.
/// </summary>
static int sqlite3BitvecSet(Bitvec p, u32 i)
{
u32 h;
if (p == null)
return SQLITE_OK;
Debug.Assert(i > 0);
Debug.Assert(i <= p.iSize);
i--;
while ((p.iSize > BITVEC_NBIT) && p.iDivisor != 0)
{
u32 bin = i / p.iDivisor;
i = i % p.iDivisor;
if (p.u.apSub[bin] == null)
{
p.u.apSub[bin] = sqlite3BitvecCreate(p.iDivisor);
//if ( p.u.apSub[bin] == null )
// return SQLITE_NOMEM;
}
p = p.u.apSub[bin];
}
if (p.iSize <= BITVEC_NBIT)
{
p.u.aBitmap[i / BITVEC_SZELEM] |= (byte)(1 << (int)(i & (BITVEC_SZELEM - 1)));
return SQLITE_OK;
}
h = BITVEC_HASH(i++);
/* if there wasn't a hash collision, and this doesn't */
/* completely fill the hash, then just add it without */
/* worring about sub-dividing and re-hashing. */
if (0 == p.u.aHash[h])
{
if (p.nSet < (BITVEC_NINT - 1))
{
goto bitvec_set_end;
}
else
{
goto bitvec_set_rehash;
}
}
/* there was a collision, check to see if it's already */
/* in hash, if not, try to find a spot for it */
do
{
if (p.u.aHash[h] == i)
return SQLITE_OK;
h++;
if (h >= BITVEC_NINT)
h = 0;
} while (p.u.aHash[h] != 0);
/* we didn't find it in the hash. h points to the first */
/* available free spot. check to see if this is going to */
/* make our hash too "full". */
bitvec_set_rehash:
if (p.nSet >= BITVEC_MXHASH)
{
u32 j;
int rc;
u32[] aiValues = new u32[BITVEC_NINT];// = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
//if ( aiValues == null )
//{
// return SQLITE_NOMEM;
//}
//else
{
Buffer.BlockCopy(p.u.aHash, 0, aiValues, 0, aiValues.Length * (sizeof(u32)));// memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
p.u.apSub = new Bitvec[BITVEC_NPTR];//memset(p->u.apSub, 0, sizeof(p->u.apSub));
p.iDivisor = (u32)((p.iSize + BITVEC_NPTR - 1) / BITVEC_NPTR);
rc = sqlite3BitvecSet(p, i);
for (j = 0; j < BITVEC_NINT; j++)
{
if (aiValues[j] != 0)
rc |= sqlite3BitvecSet(p, aiValues[j]);
}
//sqlite3StackFree( null, aiValues );
return rc;
}
}
bitvec_set_end:
p.nSet++;
p.u.aHash[h] = i;
return SQLITE_OK;
}
/// <summary>
/// Clear the i-th bit.
///
/// pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
/// that BitvecClear can use to rebuilt its hash table.
/// </summary>
static void sqlite3BitvecClear(Bitvec p, u32 i, u32[] pBuf)
{
if (p == null)
return;
Debug.Assert(i > 0);
i--;
while (p.iDivisor != 0)
{
u32 bin = i / p.iDivisor;
i = i % p.iDivisor;
p = p.u.apSub[bin];
if (null == p)
{
return;
}
}
if (p.iSize <= BITVEC_NBIT)
{
p.u.aBitmap[i / BITVEC_SZELEM] &= (byte)~((1 << (int)(i & (BITVEC_SZELEM - 1))));
}
else
{
u32 j;
u32[] aiValues = pBuf;
Array.Copy(p.u.aHash, aiValues, p.u.aHash.Length);//memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
p.u.aHash = new u32[aiValues.Length];// memset(p->u.aHash, 0, sizeof(p->u.aHash));
p.nSet = 0;
for (j = 0; j < BITVEC_NINT; j++)
{
if (aiValues[j] != 0 && aiValues[j] != (i + 1))
{
u32 h = BITVEC_HASH(aiValues[j] - 1);
p.nSet++;
while (p.u.aHash[h] != 0)
{
h++;
if (h >= BITVEC_NINT)
h = 0;
}
p.u.aHash[h] = aiValues[j];
}
}
}
}
/// <summary>
/// Destroy a bitmap object. Reclaim all memory used.
/// </summary>
static void sqlite3BitvecDestroy(ref Bitvec p)
{
if (p == null)
return;
if (p.iDivisor != 0)
{
u32 i;
for (i = 0; i < BITVEC_NPTR; i++)
{
sqlite3BitvecDestroy(ref p.u.apSub[i]);
}
}
//sqlite3_free( ref p );
}
/// <summary>
/// Return the value of the iSize parameter specified when Bitvec *p
/// was created.
/// </summary>
static u32 sqlite3BitvecSize(Bitvec p)
{
return p.iSize;
}
#if !SQLITE_OMIT_BUILTIN_TEST
/// <summary>
/// Let V[] be an array of unsigned characters sufficient to hold
/// up to N bits. Let I be an integer between 0 and N. 0<=I<N.
/// Then the following macros can be used to set, clear, or test
/// individual bits within V.
/// </summary>
static void SETBIT(byte[] V, int I)
{
V[I >> 3] |= (byte)(1 << (I & 7));
}
static void CLEARBIT(byte[] V, int I)
{
V[I >> 3] &= (byte)~(1 << (I & 7));
}
static int TESTBIT(byte[] V, int I)
{
return (V[I >> 3] & (1 << (I & 7))) != 0 ? 1 : 0;
}
/// <summary>
/// This routine runs an extensive test of the Bitvec code.
///
/// The input is an array of integers that acts as a program
/// to test the Bitvec. The integers are opcodes followed
/// by 0, 1, or 3 operands, depending on the opcode. Another
/// opcode follows immediately after the last operand.
///
/// There are 6 opcodes numbered from 0 through 5. 0 is the
/// "halt" opcode and causes the test to end.
///
/// 0 Halt and return the number of errors
/// 1 N S X Set N bits beginning with S and incrementing by X
/// 2 N S X Clear N bits beginning with S and incrementing by X
/// 3 N Set N randomly chosen bits
/// 4 N Clear N randomly chosen bits
/// 5 N S X Set N bits from S increment X in array only, not in bitvec
///
/// The opcodes 1 through 4 perform set and clear operations are performed
/// on both a Bitvec object and on a linear array of bits obtained from malloc.
/// Opcode 5 works on the linear array only, not on the Bitvec.
/// Opcode 5 is used to deliberately induce a fault in order to
/// confirm that error detection works.
///
/// At the conclusion of the test the linear array is compared
/// against the Bitvec object. If there are any differences,
/// an error is returned. If they are the same, zero is returned.
///
/// If a memory allocation error occurs, return -1.
/// </summary>
static int sqlite3BitvecBuiltinTest(u32 sz, int[] aOp)
{
Bitvec pBitvec = null;
byte[] pV = null;
int rc = -1;
int i, nx, pc, op;
u32[] pTmpSpace;
/* Allocate the Bitvec to be tested and a linear array of
** bits to act as the reference */
pBitvec = sqlite3BitvecCreate(sz);
pV = sqlite3_malloc((int)(sz + 7) / 8 + 1);
pTmpSpace = new u32[BITVEC_SZ];// sqlite3_malloc( BITVEC_SZ );
if (pBitvec == null || pV == null || pTmpSpace == null)
goto bitvec_end;
Array.Clear(pV, 0, (int)(sz + 7) / 8 + 1);// memset( pV, 0, ( sz + 7 ) / 8 + 1 );
/* NULL pBitvec tests */
sqlite3BitvecSet(null, (u32)1);
sqlite3BitvecClear(null, 1, pTmpSpace);
/* Run the program */
pc = 0;
while ((op = aOp[pc]) != 0)
{
switch (op)
{
case 1:
case 2:
case 5:
{
nx = 4;
i = aOp[pc + 2] - 1;
aOp[pc + 2] += aOp[pc + 3];
break;
}
case 3:
case 4:
default:
{
nx = 2;
i64 i64Temp = 0;
sqlite3_randomness(sizeof(i64), ref i64Temp);
i = (int)i64Temp;
break;
}
}
if ((--aOp[pc + 1]) > 0)
nx = 0;
pc += nx;
i = (int)((i & 0x7fffffff) % sz);
if ((op & 1) != 0)
{
SETBIT(pV, (i + 1));
if (op != 5)
{
if (sqlite3BitvecSet(pBitvec, (u32)i + 1) != 0)
goto bitvec_end;
}
}
else
{
CLEARBIT(pV, (i + 1));
sqlite3BitvecClear(pBitvec, (u32)i + 1, pTmpSpace);
}
}
/* Test to make sure the linear array exactly matches the
** Bitvec object. Start with the assumption that they do
** match (rc==0). Change rc to non-zero if a discrepancy
** is found.
*/
rc = sqlite3BitvecTest(null, 0) + sqlite3BitvecTest(pBitvec, sz + 1)
+ sqlite3BitvecTest(pBitvec, 0)
+ (int)(sqlite3BitvecSize(pBitvec) - sz);
for (i = 1; i <= sz; i++)
{
if ((TESTBIT(pV, i)) != sqlite3BitvecTest(pBitvec, (u32)i))
{
rc = i;
break;
}
}
/* Free allocated structure */
bitvec_end:
//sqlite3_free( ref pTmpSpace );
//sqlite3_free( ref pV );
sqlite3BitvecDestroy(ref pBitvec);
return rc;
}
#endif //* SQLITE_OMIT_BUILTIN_TEST */
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#define DEBUG
namespace NLog.UnitTests.Common
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NLog.Common;
using Xunit;
using Xunit.Extensions;
public class InternalLoggerTests_Trace : NLogTestBase
{
[Theory]
[InlineData(null, null)]
[InlineData(false, null)]
[InlineData(null, false)]
[InlineData(false, false)]
public void ShouldNotLogInternalWhenLogToTraceIsDisabled(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace);
InternalLogger.Trace("Logger1 Hello");
Assert.Empty(mockTraceListener.Messages);
}
[Theory]
[InlineData(null, null)]
[InlineData(false, null)]
[InlineData(null, false)]
[InlineData(false, false)]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldNotLogInternalWhenLogLevelIsOff(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Off, internalLogToTrace, logToTrace);
InternalLogger.Trace("Logger1 Hello");
Assert.Empty(mockTraceListener.Messages);
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void VerifyInternalLoggerLevelFilter(bool? internalLogToTrace, bool? logToTrace)
{
foreach (LogLevel logLevelConfig in LogLevel.AllLevels)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(logLevelConfig, internalLogToTrace, logToTrace);
List<string> expected = new List<string>();
string input = "Logger1 Hello";
expected.Add(input);
InternalLogger.Trace(input);
InternalLogger.Debug(input);
InternalLogger.Info(input);
InternalLogger.Warn(input);
InternalLogger.Error(input);
InternalLogger.Fatal(input);
input += "No.{0}";
expected.Add(string.Format(input, 1));
InternalLogger.Trace(input, 1);
InternalLogger.Debug(input, 1);
InternalLogger.Info(input, 1);
InternalLogger.Warn(input, 1);
InternalLogger.Error(input, 1);
InternalLogger.Fatal(input, 1);
input += ", We come in {1}";
expected.Add(string.Format(input, 1, "Peace"));
InternalLogger.Trace(input, 1, "Peace");
InternalLogger.Debug(input, 1, "Peace");
InternalLogger.Info(input, 1, "Peace");
InternalLogger.Warn(input, 1, "Peace");
InternalLogger.Error(input, 1, "Peace");
InternalLogger.Fatal(input, 1, "Peace");
input += " and we are {2} to god";
expected.Add(string.Format(input, 1, "Peace", true));
InternalLogger.Trace(input, 1, "Peace", true);
InternalLogger.Debug(input, 1, "Peace", true);
InternalLogger.Info(input, 1, "Peace", true);
InternalLogger.Warn(input, 1, "Peace", true);
InternalLogger.Error(input, 1, "Peace", true);
InternalLogger.Fatal(input, 1, "Peace", true);
input += ", Please don't {3}";
expected.Add(string.Format(input, 1, "Peace", true, null));
InternalLogger.Trace(input, 1, "Peace", true, null);
InternalLogger.Debug(input, 1, "Peace", true, null);
InternalLogger.Info(input, 1, "Peace", true, null);
InternalLogger.Warn(input, 1, "Peace", true, null);
InternalLogger.Error(input, 1, "Peace", true, null);
InternalLogger.Fatal(input, 1, "Peace", true, null);
input += " the {4}";
expected.Add(string.Format(input, 1, "Peace", true, null, "Messenger"));
InternalLogger.Trace(input, 1, "Peace", true, null, "Messenger");
InternalLogger.Debug(input, 1, "Peace", true, null, "Messenger");
InternalLogger.Info(input, 1, "Peace", true, null, "Messenger");
InternalLogger.Warn(input, 1, "Peace", true, null, "Messenger");
InternalLogger.Error(input, 1, "Peace", true, null, "Messenger");
InternalLogger.Fatal(input, 1, "Peace", true, null, "Messenger");
Assert.Equal(expected.Count * (LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1), mockTraceListener.Messages.Count);
for (int i = 0; i < expected.Count; ++i)
{
int msgCount = LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1;
for (int j = 0; j < msgCount; ++j)
{
Assert.Contains(expected[i], mockTraceListener.Messages.First());
mockTraceListener.Messages.RemoveAt(0);
}
}
Assert.Empty(mockTraceListener.Messages);
}
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsTrace(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace);
InternalLogger.Trace("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Trace Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsDebug(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Debug, internalLogToTrace, logToTrace);
InternalLogger.Debug("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Debug Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsInfo(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Info, internalLogToTrace, logToTrace);
InternalLogger.Info("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Info Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsWarn(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Warn, internalLogToTrace, logToTrace);
InternalLogger.Warn("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Warn Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsError(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Error, internalLogToTrace, logToTrace);
InternalLogger.Error("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Error Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsFatal(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Fatal, internalLogToTrace, logToTrace);
InternalLogger.Fatal("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Fatal Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
#if !NETSTANDARD1_5
[Fact(Skip = "This test's not working - explenation is in documentation: https://msdn.microsoft.com/pl-pl/library/system.stackoverflowexception(v=vs.110).aspx#Anchor_5. To clarify if StackOverflowException should be thrown.")]
public void ShouldThrowStackOverFlowExceptionWhenUsingNLogTraceListener()
{
SetupTestConfiguration<NLogTraceListener>(LogLevel.Trace, true, null);
Assert.Throws<StackOverflowException>(() => Trace.WriteLine("StackOverFlowException"));
}
#endif
/// <summary>
/// Helper method to setup tests configuration
/// </summary>
/// <param name="logLevel">The <see cref="NLog.LogLevel"/> for the log event.</param>
/// <param name="internalLogToTrace">internalLogToTrace XML attribute value. If <c>null</c> attribute is omitted.</param>
/// <param name="logToTrace">Value of <see cref="InternalLogger.LogToTrace"/> property. If <c>null</c> property is not set.</param>
/// <returns><see cref="TraceListener"/> instance.</returns>
private T SetupTestConfiguration<T>(LogLevel logLevel, bool? internalLogToTrace, bool? logToTrace) where T : TraceListener
{
var internalLogToTraceAttribute = "";
if (internalLogToTrace.HasValue)
{
internalLogToTraceAttribute = $" internalLogToTrace='{internalLogToTrace.Value}'";
}
var xmlConfiguration = string.Format(XmlConfigurationFormat, logLevel, internalLogToTraceAttribute);
LogManager.Configuration = CreateConfigurationFromString(xmlConfiguration);
InternalLogger.IncludeTimestamp = false;
if (logToTrace.HasValue)
{
InternalLogger.LogToTrace = logToTrace.Value;
}
T traceListener;
if (typeof (T) == typeof (MockTraceListener))
{
traceListener = CreateMockTraceListener() as T;
}
else
{
traceListener = CreateNLogTraceListener() as T;
}
Trace.Listeners.Clear();
if (traceListener == null)
{
return null;
}
Trace.Listeners.Add(traceListener);
return traceListener;
}
private const string XmlConfigurationFormat = @"<nlog internalLogLevel='{0}'{1}>
<targets>
<target name='debug' type='Debug' layout='${{logger}} ${{level}} ${{message}}'/>
</targets>
<rules>
<logger name='*' level='{0}' writeTo='debug'/>
</rules>
</nlog>";
/// <summary>
/// Creates <see cref="MockTraceListener"/> instance.
/// </summary>
/// <returns><see cref="MockTraceListener"/> instance.</returns>
private static MockTraceListener CreateMockTraceListener()
{
return new MockTraceListener();
}
/// <summary>
/// Creates <see cref="NLogTraceListener"/> instance.
/// </summary>
/// <returns><see cref="NLogTraceListener"/> instance.</returns>
private static TraceListener CreateNLogTraceListener()
{
#if !NETSTANDARD1_5
return new NLogTraceListener {Name = "Logger1", ForceLogLevel = LogLevel.Trace};
#else
return null;
#endif
}
private class MockTraceListener : TraceListener
{
internal readonly List<string> Messages = new List<string>();
/// <summary>
/// When overridden in a derived class, writes the specified message to the listener you create in the derived class.
/// </summary>
/// <param name="message">A message to write. </param>
public override void Write(string message)
{
Messages.Add(message);
}
/// <summary>
/// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator.
/// </summary>
/// <param name="message">A message to write. </param>
public override void WriteLine(string message)
{
Messages.Add(message + Environment.NewLine);
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
using System.Numerics;
#endif
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text;
#if NET20
using Medivh.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Medivh.Json.Serialization;
namespace Medivh.Json.Utilities
{
#if (DOTNET || PORTABLE || PORTABLE40)
internal enum MemberTypes
{
Property = 0,
Field = 1,
Event = 2,
Method = 3,
Other = 4
}
#endif
#if PORTABLE
[Flags]
internal enum BindingFlags
{
Default = 0,
IgnoreCase = 1,
DeclaredOnly = 2,
Instance = 4,
Static = 8,
Public = 16,
NonPublic = 32,
FlattenHierarchy = 64,
InvokeMethod = 256,
CreateInstance = 512,
GetField = 1024,
SetField = 2048,
GetProperty = 4096,
SetProperty = 8192,
PutDispProperty = 16384,
ExactBinding = 65536,
PutRefDispProperty = 32768,
SuppressChangeType = 131072,
OptionalParamBinding = 262144,
IgnoreReturn = 16777216
}
#endif
internal static class ReflectionUtils
{
public static readonly Type[] EmptyTypes;
static ReflectionUtils()
{
#if !(PORTABLE40 || PORTABLE)
EmptyTypes = Type.EmptyTypes;
#else
EmptyTypes = new Type[0];
#endif
}
public static bool IsVirtual(this PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
MethodInfo m = propertyInfo.GetGetMethod();
if (m != null && m.IsVirtual)
{
return true;
}
m = propertyInfo.GetSetMethod();
if (m != null && m.IsVirtual)
{
return true;
}
return false;
}
public static MethodInfo GetBaseDefinition(this PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
MethodInfo m = propertyInfo.GetGetMethod();
if (m != null)
{
return m.GetBaseDefinition();
}
m = propertyInfo.GetSetMethod();
if (m != null)
{
return m.GetBaseDefinition();
}
return null;
}
public static bool IsPublic(PropertyInfo property)
{
if (property.GetGetMethod() != null && property.GetGetMethod().IsPublic)
{
return true;
}
if (property.GetSetMethod() != null && property.GetSetMethod().IsPublic)
{
return true;
}
return false;
}
public static Type GetObjectType(object v)
{
return (v != null) ? v.GetType() : null;
}
public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat, SerializationBinder binder)
{
string fullyQualifiedTypeName;
#if !(NET20 || NET35)
if (binder != null)
{
string assemblyName, typeName;
binder.BindToName(t, out assemblyName, out typeName);
fullyQualifiedTypeName = typeName + (assemblyName == null ? "" : ", " + assemblyName);
}
else
{
fullyQualifiedTypeName = t.AssemblyQualifiedName;
}
#else
fullyQualifiedTypeName = t.AssemblyQualifiedName;
#endif
switch (assemblyFormat)
{
case FormatterAssemblyStyle.Simple:
return RemoveAssemblyDetails(fullyQualifiedTypeName);
case FormatterAssemblyStyle.Full:
return fullyQualifiedTypeName;
default:
throw new ArgumentOutOfRangeException();
}
}
private static string RemoveAssemblyDetails(string fullyQualifiedTypeName)
{
StringBuilder builder = new StringBuilder();
// loop through the type name and filter out qualified assembly details from nested type names
bool writingAssemblyName = false;
bool skippingAssemblyDetails = false;
for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
{
char current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(current);
break;
case ']':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(current);
break;
case ',':
if (!writingAssemblyName)
{
writingAssemblyName = true;
builder.Append(current);
}
else
{
skippingAssemblyDetails = true;
}
break;
default:
if (!skippingAssemblyDetails)
{
builder.Append(current);
}
break;
}
}
return builder.ToString();
}
public static bool HasDefaultConstructor(Type t, bool nonPublic)
{
ValidationUtils.ArgumentNotNull(t, nameof(t));
if (t.IsValueType())
{
return true;
}
return (GetDefaultConstructor(t, nonPublic) != null);
}
public static ConstructorInfo GetDefaultConstructor(Type t)
{
return GetDefaultConstructor(t, false);
}
public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic)
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
if (nonPublic)
{
bindingFlags = bindingFlags | BindingFlags.NonPublic;
}
return t.GetConstructors(bindingFlags).SingleOrDefault(c => !c.GetParameters().Any());
}
public static bool IsNullable(Type t)
{
ValidationUtils.ArgumentNotNull(t, nameof(t));
if (t.IsValueType())
{
return IsNullableType(t);
}
return true;
}
public static bool IsNullableType(Type t)
{
ValidationUtils.ArgumentNotNull(t, nameof(t));
return (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
public static Type EnsureNotNullableType(Type t)
{
return (IsNullableType(t))
? Nullable.GetUnderlyingType(t)
: t;
}
public static bool IsGenericDefinition(Type type, Type genericInterfaceDefinition)
{
if (!type.IsGenericType())
{
return false;
}
Type t = type.GetGenericTypeDefinition();
return (t == genericInterfaceDefinition);
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition)
{
Type implementingType;
return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType);
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, nameof(genericInterfaceDefinition));
if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition())
{
throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition));
}
if (type.IsInterface())
{
if (type.IsGenericType())
{
Type interfaceDefinition = type.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = type;
return true;
}
}
}
foreach (Type i in type.GetInterfaces())
{
if (i.IsGenericType())
{
Type interfaceDefinition = i.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = i;
return true;
}
}
}
implementingType = null;
return false;
}
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition)
{
Type implementingType;
return InheritsGenericDefinition(type, genericClassDefinition, out implementingType);
}
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
ValidationUtils.ArgumentNotNull(genericClassDefinition, nameof(genericClassDefinition));
if (!genericClassDefinition.IsClass() || !genericClassDefinition.IsGenericTypeDefinition())
{
throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition));
}
return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType);
}
private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType)
{
if (currentType.IsGenericType())
{
Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition();
if (genericClassDefinition == currentGenericClassDefinition)
{
implementingType = currentType;
return true;
}
}
if (currentType.BaseType() == null)
{
implementingType = null;
return false;
}
return InheritsGenericDefinitionInternal(currentType.BaseType(), genericClassDefinition, out implementingType);
}
/// <summary>
/// Gets the type of the typed collection's items.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The type of the typed collection's items.</returns>
public static Type GetCollectionItemType(Type type)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
Type genericListType;
if (type.IsArray)
{
return type.GetElementType();
}
if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType))
{
if (genericListType.IsGenericTypeDefinition())
{
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
}
return genericListType.GetGenericArguments()[0];
}
if (typeof(IEnumerable).IsAssignableFrom(type))
{
return null;
}
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
}
public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType)
{
ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType));
Type genericDictionaryType;
if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType))
{
if (genericDictionaryType.IsGenericTypeDefinition())
{
throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
}
Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments();
keyType = dictionaryGenericArguments[0];
valueType = dictionaryGenericArguments[1];
return;
}
if (typeof(IDictionary).IsAssignableFrom(dictionaryType))
{
keyType = null;
valueType = null;
return;
}
throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
}
/// <summary>
/// Gets the member's underlying type.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>The underlying type of the member.</returns>
public static Type GetMemberUnderlyingType(MemberInfo member)
{
ValidationUtils.ArgumentNotNull(member, nameof(member));
switch (member.MemberType())
{
case MemberTypes.Field:
return ((FieldInfo)member).FieldType;
case MemberTypes.Property:
return ((PropertyInfo)member).PropertyType;
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
case MemberTypes.Method:
return ((MethodInfo)member).ReturnType;
default:
throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo, EventInfo or MethodInfo", nameof(member));
}
}
/// <summary>
/// Determines whether the member is an indexed property.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>
/// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(MemberInfo member)
{
ValidationUtils.ArgumentNotNull(member, nameof(member));
PropertyInfo propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
{
return IsIndexedProperty(propertyInfo);
}
else
{
return false;
}
}
/// <summary>
/// Determines whether the property is an indexed property.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>
/// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(PropertyInfo property)
{
ValidationUtils.ArgumentNotNull(property, nameof(property));
return (property.GetIndexParameters().Length > 0);
}
/// <summary>
/// Gets the member's value on the object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target object.</param>
/// <returns>The member's value on the object.</returns>
public static object GetMemberValue(MemberInfo member, object target)
{
ValidationUtils.ArgumentNotNull(member, nameof(member));
ValidationUtils.ArgumentNotNull(target, nameof(target));
switch (member.MemberType())
{
case MemberTypes.Field:
return ((FieldInfo)member).GetValue(target);
case MemberTypes.Property:
try
{
return ((PropertyInfo)member).GetValue(target, null);
}
catch (TargetParameterCountException e)
{
throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e);
}
default:
throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), nameof(member));
}
}
/// <summary>
/// Sets the member's value on the target object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target.</param>
/// <param name="value">The value.</param>
public static void SetMemberValue(MemberInfo member, object target, object value)
{
ValidationUtils.ArgumentNotNull(member, nameof(member));
ValidationUtils.ArgumentNotNull(target, nameof(target));
switch (member.MemberType())
{
case MemberTypes.Field:
((FieldInfo)member).SetValue(target, value);
break;
case MemberTypes.Property:
((PropertyInfo)member).SetValue(target, value, null);
break;
default:
throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), nameof(member));
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be read.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be read.</param>
/// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>.
/// </returns>
public static bool CanReadMemberValue(MemberInfo member, bool nonPublic)
{
switch (member.MemberType())
{
case MemberTypes.Field:
FieldInfo fieldInfo = (FieldInfo)member;
if (nonPublic)
{
return true;
}
else if (fieldInfo.IsPublic)
{
return true;
}
return false;
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo)member;
if (!propertyInfo.CanRead)
{
return false;
}
if (nonPublic)
{
return true;
}
return (propertyInfo.GetGetMethod(nonPublic) != null);
default:
return false;
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be set.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be set.</param>
/// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param>
/// <param name="canSetReadOnly">if set to <c>true</c> then allow the member to be set if read-only.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>.
/// </returns>
public static bool CanSetMemberValue(MemberInfo member, bool nonPublic, bool canSetReadOnly)
{
switch (member.MemberType())
{
case MemberTypes.Field:
FieldInfo fieldInfo = (FieldInfo)member;
if (fieldInfo.IsLiteral)
{
return false;
}
if (fieldInfo.IsInitOnly && !canSetReadOnly)
{
return false;
}
if (nonPublic)
{
return true;
}
if (fieldInfo.IsPublic)
{
return true;
}
return false;
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo)member;
if (!propertyInfo.CanWrite)
{
return false;
}
if (nonPublic)
{
return true;
}
return (propertyInfo.GetSetMethod(nonPublic) != null);
default:
return false;
}
}
public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr)
{
List<MemberInfo> targetMembers = new List<MemberInfo>();
targetMembers.AddRange(GetFields(type, bindingAttr));
targetMembers.AddRange(GetProperties(type, bindingAttr));
// for some reason .NET returns multiple members when overriding a generic member on a base class
// http://social.msdn.microsoft.com/Forums/en-US/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/reflection-overriden-abstract-generic-properties?forum=netfxbcl
// filter members to only return the override on the topmost class
// update: I think this is fixed in .NET 3.5 SP1 - leave this in for now...
List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count);
foreach (var groupedMember in targetMembers.GroupBy(m => m.Name))
{
int count = groupedMember.Count();
IList<MemberInfo> members = groupedMember.ToList();
if (count == 1)
{
distinctMembers.Add(members.First());
}
else
{
IList<MemberInfo> resolvedMembers = new List<MemberInfo>();
foreach (MemberInfo memberInfo in members)
{
// this is a bit hacky
// if the hiding property is hiding a base property and it is virtual
// then this ensures the derived property gets used
if (resolvedMembers.Count == 0)
{
resolvedMembers.Add(memberInfo);
}
else if (!IsOverridenGenericMember(memberInfo, bindingAttr) || memberInfo.Name == "Item")
{
resolvedMembers.Add(memberInfo);
}
}
distinctMembers.AddRange(resolvedMembers);
}
}
return distinctMembers;
}
private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr)
{
if (memberInfo.MemberType() != MemberTypes.Property)
{
return false;
}
PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
if (!IsVirtual(propertyInfo))
{
return false;
}
Type declaringType = propertyInfo.DeclaringType;
if (!declaringType.IsGenericType())
{
return false;
}
Type genericTypeDefinition = declaringType.GetGenericTypeDefinition();
if (genericTypeDefinition == null)
{
return false;
}
MemberInfo[] members = genericTypeDefinition.GetMember(propertyInfo.Name, bindingAttr);
if (members.Length == 0)
{
return false;
}
Type memberUnderlyingType = GetMemberUnderlyingType(members[0]);
if (!memberUnderlyingType.IsGenericParameter)
{
return false;
}
return true;
}
public static T GetAttribute<T>(object attributeProvider) where T : Attribute
{
return GetAttribute<T>(attributeProvider, true);
}
public static T GetAttribute<T>(object attributeProvider, bool inherit) where T : Attribute
{
T[] attributes = GetAttributes<T>(attributeProvider, inherit);
return (attributes != null) ? attributes.FirstOrDefault() : null;
}
#if !(DOTNET || PORTABLE)
public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute
{
Attribute[] a = GetAttributes(attributeProvider, typeof(T), inherit);
T[] attributes = a as T[];
if (attributes != null)
{
return attributes;
}
return a.Cast<T>().ToArray();
}
public static Attribute[] GetAttributes(object attributeProvider, Type attributeType, bool inherit)
{
ValidationUtils.ArgumentNotNull(attributeProvider, nameof(attributeProvider));
object provider = attributeProvider;
// http://hyperthink.net/blog/getcustomattributes-gotcha/
// ICustomAttributeProvider doesn't do inheritance
if (provider is Type)
{
Type t = (Type)provider;
object[] a = (attributeType != null) ? t.GetCustomAttributes(attributeType, inherit) : t.GetCustomAttributes(inherit);
Attribute[] attributes = a.Cast<Attribute>().ToArray();
#if (NET20 || NET35)
// ye olde .NET GetCustomAttributes doesn't respect the inherit argument
if (inherit && t.BaseType != null)
attributes = attributes.Union(GetAttributes(t.BaseType, attributeType, inherit)).ToArray();
#endif
return attributes;
}
if (provider is Assembly)
{
Assembly a = (Assembly)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(a, attributeType) : Attribute.GetCustomAttributes(a);
}
if (provider is MemberInfo)
{
MemberInfo m = (MemberInfo)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit);
}
#if !PORTABLE40
if (provider is Module)
{
Module m = (Module)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit);
}
#endif
if (provider is ParameterInfo)
{
ParameterInfo p = (ParameterInfo)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(p, attributeType, inherit) : Attribute.GetCustomAttributes(p, inherit);
}
#if !PORTABLE40
ICustomAttributeProvider customAttributeProvider = (ICustomAttributeProvider)attributeProvider;
object[] result = (attributeType != null) ? customAttributeProvider.GetCustomAttributes(attributeType, inherit) : customAttributeProvider.GetCustomAttributes(inherit);
return (Attribute[])result;
#else
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
#endif
}
#else
public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute
{
return GetAttributes(attributeProvider, typeof(T), inherit).Cast<T>().ToArray();
}
public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit)
{
if (provider is Type)
{
Type t = (Type)provider;
return (attributeType != null)
? t.GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray()
: t.GetTypeInfo().GetCustomAttributes(inherit).ToArray();
}
if (provider is Assembly)
{
Assembly a = (Assembly)provider;
return (attributeType != null) ? a.GetCustomAttributes(attributeType).ToArray() : a.GetCustomAttributes().ToArray();
}
if (provider is MemberInfo)
{
MemberInfo m = (MemberInfo)provider;
return (attributeType != null) ? m.GetCustomAttributes(attributeType, inherit).ToArray() : m.GetCustomAttributes(inherit).ToArray();
}
if (provider is Module)
{
Module m = (Module)provider;
return (attributeType != null) ? m.GetCustomAttributes(attributeType).ToArray() : m.GetCustomAttributes().ToArray();
}
if (provider is ParameterInfo)
{
ParameterInfo p = (ParameterInfo)provider;
return (attributeType != null) ? p.GetCustomAttributes(attributeType, inherit).ToArray() : p.GetCustomAttributes(inherit).ToArray();
}
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
}
#endif
public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName)
{
int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName);
if (assemblyDelimiterIndex != null)
{
typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.GetValueOrDefault()).Trim();
assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.GetValueOrDefault() + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.GetValueOrDefault() - 1).Trim();
}
else
{
typeName = fullyQualifiedTypeName;
assemblyName = null;
}
}
private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName)
{
// we need to get the first comma following all surrounded in brackets because of generic types
// e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
int scope = 0;
for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
{
char current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
scope++;
break;
case ']':
scope--;
break;
case ',':
if (scope == 0)
{
return i;
}
break;
}
}
return null;
}
public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo)
{
const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
switch (memberInfo.MemberType())
{
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
Type[] types = propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray();
return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null);
default:
return targetType.GetMember(memberInfo.Name, memberInfo.MemberType(), bindingAttr).SingleOrDefault();
}
}
public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr)
{
ValidationUtils.ArgumentNotNull(targetType, nameof(targetType));
List<MemberInfo> fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr));
#if !PORTABLE
// Type.GetFields doesn't return inherited private fields
// manually find private fields from base class
GetChildPrivateFields(fieldInfos, targetType, bindingAttr);
#endif
return fieldInfos.Cast<FieldInfo>();
}
#if !PORTABLE
private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr)
{
// fix weirdness with private FieldInfos only being returned for the current Type
// find base type fields and add them to result
if ((bindingAttr & BindingFlags.NonPublic) != 0)
{
// modify flags to not search for public fields
BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public);
while ((targetType = targetType.BaseType()) != null)
{
// filter out protected fields
IEnumerable<MemberInfo> childPrivateFields =
targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>();
initialFields.AddRange(childPrivateFields);
}
}
}
#endif
public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr)
{
ValidationUtils.ArgumentNotNull(targetType, nameof(targetType));
List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr));
// GetProperties on an interface doesn't return properties from its interfaces
if (targetType.IsInterface())
{
foreach (Type i in targetType.GetInterfaces())
{
propertyInfos.AddRange(i.GetProperties(bindingAttr));
}
}
GetChildPrivateProperties(propertyInfos, targetType, bindingAttr);
// a base class private getter/setter will be inaccessable unless the property was gotten from the base class
for (int i = 0; i < propertyInfos.Count; i++)
{
PropertyInfo member = propertyInfos[i];
if (member.DeclaringType != targetType)
{
PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member);
propertyInfos[i] = declaredMember;
}
}
return propertyInfos;
}
public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag)
{
return ((bindingAttr & flag) == flag)
? bindingAttr ^ flag
: bindingAttr;
}
private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr)
{
// fix weirdness with private PropertyInfos only being returned for the current Type
// find base type properties and add them to result
// also find base properties that have been hidden by subtype properties with the same name
while ((targetType = targetType.BaseType()) != null)
{
foreach (PropertyInfo propertyInfo in targetType.GetProperties(bindingAttr))
{
PropertyInfo subTypeProperty = propertyInfo;
if (!IsPublic(subTypeProperty))
{
// have to test on name rather than reference because instances are different
// depending on the type that GetProperties was called on
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name);
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
else
{
PropertyInfo childProperty = initialProperties[index];
// don't replace public child with private base
if (!IsPublic(childProperty))
{
// replace nonpublic properties for a child, but gotten from
// the parent with the one from the child
// the property gotten from the child will have access to private getter/setter
initialProperties[index] = subTypeProperty;
}
}
}
else
{
if (!subTypeProperty.IsVirtual())
{
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name
&& p.DeclaringType == subTypeProperty.DeclaringType);
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
}
else
{
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name
&& p.IsVirtual()
&& p.GetBaseDefinition() != null
&& p.GetBaseDefinition().DeclaringType.IsAssignableFrom(subTypeProperty.GetBaseDefinition().DeclaringType));
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
}
}
}
}
}
public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method)
{
bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Any(info =>
info.Name == method &&
// check that the method overrides the original on DynamicObjectProxy
info.DeclaringType != methodDeclaringType
&& info.GetBaseDefinition().DeclaringType == methodDeclaringType
);
return isMethodOverriden;
}
public static object GetDefaultValue(Type type)
{
if (!type.IsValueType())
{
return null;
}
switch (ConvertUtils.GetTypeCode(type))
{
case PrimitiveTypeCode.Boolean:
return false;
case PrimitiveTypeCode.Char:
case PrimitiveTypeCode.SByte:
case PrimitiveTypeCode.Byte:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.UInt32:
return 0;
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
return 0L;
case PrimitiveTypeCode.Single:
return 0f;
case PrimitiveTypeCode.Double:
return 0.0;
case PrimitiveTypeCode.Decimal:
return 0m;
case PrimitiveTypeCode.DateTime:
return new DateTime();
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
case PrimitiveTypeCode.BigInteger:
return new BigInteger();
#endif
case PrimitiveTypeCode.Guid:
return new Guid();
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
return new DateTimeOffset();
#endif
}
if (IsNullable(type))
{
return null;
}
// possibly use IL initobj for perf here?
return Activator.CreateInstance(type);
}
}
}
| |
// Copyright 2021 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.OsConfig.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedOsConfigZonalServiceClientTest
{
[xunit::FactAttribute]
public void GetOSPolicyAssignmentRequestObject()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment response = client.GetOSPolicyAssignment(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentRequestObjectAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment responseCallSettings = await client.GetOSPolicyAssignmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignment responseCancellationToken = await client.GetOSPolicyAssignmentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOSPolicyAssignment()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment response = client.GetOSPolicyAssignment(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment responseCallSettings = await client.GetOSPolicyAssignmentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignment responseCancellationToken = await client.GetOSPolicyAssignmentAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOSPolicyAssignmentResourceNames()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment response = client.GetOSPolicyAssignment(request.OSPolicyAssignmentName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentResourceNamesAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentRequest request = new GetOSPolicyAssignmentRequest
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
};
OSPolicyAssignment expectedResponse = new OSPolicyAssignment
{
OSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
Description = "description2cf9da67",
OsPolicies = { new OSPolicy(), },
InstanceFilter = new OSPolicyAssignment.Types.InstanceFilter(),
Rollout = new OSPolicyAssignment.Types.Rollout(),
RevisionId = "revision_id8d9ae05d",
RevisionCreateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
RolloutState = OSPolicyAssignment.Types.RolloutState.Cancelling,
Baseline = false,
Deleted = true,
Reconciling = false,
Uid = "uida2d37198",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignment responseCallSettings = await client.GetOSPolicyAssignmentAsync(request.OSPolicyAssignmentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignment responseCancellationToken = await client.GetOSPolicyAssignmentAsync(request.OSPolicyAssignmentName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOSPolicyAssignmentReportRequestObject()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport response = client.GetOSPolicyAssignmentReport(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentReportRequestObjectAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignmentReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport responseCallSettings = await client.GetOSPolicyAssignmentReportAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignmentReport responseCancellationToken = await client.GetOSPolicyAssignmentReportAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOSPolicyAssignmentReport()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport response = client.GetOSPolicyAssignmentReport(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentReportAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignmentReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport responseCallSettings = await client.GetOSPolicyAssignmentReportAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignmentReport responseCancellationToken = await client.GetOSPolicyAssignmentReportAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOSPolicyAssignmentReportResourceNames()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport response = client.GetOSPolicyAssignmentReport(request.OSPolicyAssignmentReportName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOSPolicyAssignmentReportResourceNamesAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetOSPolicyAssignmentReportRequest request = new GetOSPolicyAssignmentReportRequest
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
};
OSPolicyAssignmentReport expectedResponse = new OSPolicyAssignmentReport
{
OSPolicyAssignmentReportName = OSPolicyAssignmentReportName.FromProjectLocationInstanceAssignment("[PROJECT]", "[LOCATION]", "[INSTANCE]", "[ASSIGNMENT]"),
Instance = "instance99a62371",
OsPolicyAssignmentAsOSPolicyAssignmentName = OSPolicyAssignmentName.FromProjectLocationOsPolicyAssignment("[PROJECT]", "[LOCATION]", "[OS_POLICY_ASSIGNMENT]"),
OsPolicyCompliances =
{
new OSPolicyAssignmentReport.Types.OSPolicyCompliance(),
},
UpdateTime = new wkt::Timestamp(),
LastRunId = "last_run_ida47e4da8",
};
mockGrpcClient.Setup(x => x.GetOSPolicyAssignmentReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<OSPolicyAssignmentReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
OSPolicyAssignmentReport responseCallSettings = await client.GetOSPolicyAssignmentReportAsync(request.OSPolicyAssignmentReportName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
OSPolicyAssignmentReport responseCancellationToken = await client.GetOSPolicyAssignmentReportAsync(request.OSPolicyAssignmentReportName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInventoryRequestObject()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
View = InventoryView.Basic,
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventory(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory response = client.GetInventory(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInventoryRequestObjectAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
View = InventoryView.Basic,
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Inventory>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory responseCallSettings = await client.GetInventoryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Inventory responseCancellationToken = await client.GetInventoryAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInventory()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventory(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory response = client.GetInventory(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInventoryAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Inventory>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory responseCallSettings = await client.GetInventoryAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Inventory responseCancellationToken = await client.GetInventoryAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInventoryResourceNames()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventory(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory response = client.GetInventory(request.InventoryName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInventoryResourceNamesAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInventoryRequest request = new GetInventoryRequest
{
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
Inventory expectedResponse = new Inventory
{
OsInfo = new Inventory.Types.OsInfo(),
Items =
{
{
"key8a0b6e3c",
new Inventory.Types.Item()
},
},
InventoryName = InventoryName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetInventoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Inventory>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
Inventory responseCallSettings = await client.GetInventoryAsync(request.InventoryName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Inventory responseCancellationToken = await client.GetInventoryAsync(request.InventoryName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetVulnerabilityReportRequestObject()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport response = client.GetVulnerabilityReport(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetVulnerabilityReportRequestObjectAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport responseCallSettings = await client.GetVulnerabilityReportAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
VulnerabilityReport responseCancellationToken = await client.GetVulnerabilityReportAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetVulnerabilityReport()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport response = client.GetVulnerabilityReport(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetVulnerabilityReportAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport responseCallSettings = await client.GetVulnerabilityReportAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
VulnerabilityReport responseCancellationToken = await client.GetVulnerabilityReportAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetVulnerabilityReportResourceNames()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport response = client.GetVulnerabilityReport(request.VulnerabilityReportName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetVulnerabilityReportResourceNamesAsync()
{
moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient> mockGrpcClient = new moq::Mock<OsConfigZonalService.OsConfigZonalServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVulnerabilityReportRequest request = new GetVulnerabilityReportRequest
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
VulnerabilityReport expectedResponse = new VulnerabilityReport
{
VulnerabilityReportName = VulnerabilityReportName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
Vulnerabilities =
{
new VulnerabilityReport.Types.Vulnerability(),
},
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetVulnerabilityReportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityReport>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsConfigZonalServiceClient client = new OsConfigZonalServiceClientImpl(mockGrpcClient.Object, null);
VulnerabilityReport responseCallSettings = await client.GetVulnerabilityReportAsync(request.VulnerabilityReportName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
VulnerabilityReport responseCancellationToken = await client.GetVulnerabilityReportAsync(request.VulnerabilityReportName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace CodeGen.Test
{
[TestClass]
public class UnitTests
{
[TestMethod]
public void FormattingHelpers()
{
Assert.AreEqual(Formatter.StylizeWithCapitalLeadingLetter(null), null);
Assert.AreEqual(Formatter.StylizeWithCapitalLeadingLetter(""), "");
Assert.AreEqual(Formatter.StylizeWithCapitalLeadingLetter("a"), "A");
Assert.AreEqual(Formatter.StylizeWithCapitalLeadingLetter("A"), "A");
Assert.AreEqual(Formatter.StylizeWithCapitalLeadingLetter("_"), "_");
Assert.AreEqual(Formatter.StylizeWithCapitalLeadingLetter("cat"), "Cat");
Assert.AreEqual(Formatter.StylizeWithCapitalLeadingLetter("Cat"), "Cat");
Assert.AreEqual(Formatter.StylizeWithCapitalLeadingLetter("...cat"), "...cat");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators(null), null);
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators(""), "");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("d"), "D");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("D"), "D");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("_"), "");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("__"), "");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("a__"), "A");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("_a_"), "A");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("__a"), "A");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("a_b_c"), "ABC");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("CAT_DOG"), "CatDog");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("CATDOG"), "Catdog");
Assert.AreEqual(Formatter.StylizeNameFromUnderscoreSeparators("TYPE_1X1_suffix"), "Type1x1Suffix");
}
[TestMethod]
[DeploymentItem("../../../../winrt/lib/effects/generated", "codegen/effects/expected")]
[DeploymentItem("../../../../tools/codegen/exe/apiref/effects", "codegen/effects/in/apiref/effects")]
[DeploymentItem("Deployed Files/Settings.xml", "codegen/effects/in")]
[DeploymentItem("Deployed Files/D2DEffectAuthor.xml", "codegen/effects/in/apiref")]
[DeploymentItem("Deployed Files/D2DTypes.xml", "codegen/effects/in/apiref")]
[DeploymentItem("Deployed Files/D2DTypes2.xml", "codegen/effects/in/apiref")]
[DeploymentItem("Deployed Files/D2DTypes3.xml", "codegen/effects/in/apiref")]
public void OutputEffectsIsSync()
{
//
// This test sets codegen to generate its output to some temporary
// files, and then diffs the temporary files with what's checked in.
//
// This allows us to detect if the output files were manually
// edited, or someone changed codegen without re-running it.
//
// The tests are executed from a deployed directory that contains
// the test executable / dependent assemblies and the
// DeploymentItems listed above. The codegen outputs under this
// directory as well. The test runner cleans up the entire deploy
// directory on exit.
//
string inputDir = "codegen/effects/in";
string expectedDir = "codegen/effects/expected";
string actualDir = "codegen/effects/actual";
// Create directory for actual output
Directory.CreateDirectory(actualDir);
// Run codegen
CodeGen.Program.ProcessedInputFiles input = CodeGen.Program.ProcessInputFiles(inputDir);
CodeGen.Program.GenerateEffectsCode(inputDir, input.TypeDictionary, actualDir);
// Verify the output from the codegen matches what was expected
var expectedDirectoryInfo = new DirectoryInfo(expectedDir);
var actualDirectoryInfo = new DirectoryInfo(actualDir);
FileInfo[] expectedGeneratedFiles = expectedDirectoryInfo.GetFiles();
FileInfo[] actualGeneratedFiles = actualDirectoryInfo.GetFiles();
// Ensure the correct number of files was generated.
const int expectedEffectCount = 53;
Assert.AreEqual(expectedEffectCount * 3 + 1, expectedGeneratedFiles.Length);
Assert.AreEqual(expectedGeneratedFiles.Length, actualGeneratedFiles.Length);
// For each codegenned file in the tree, ensure it was output to the test folder.
CheckFilesMatch(expectedGeneratedFiles, actualDir);
}
[TestMethod]
[DeploymentItem("Deployed Files/Canvas.codegen.idl", "codegen/expected")]
[DeploymentItem("Deployed Files/D2DEffectAuthor.xml", "codegen/in/apiref")]
[DeploymentItem("Deployed Files/D2DTypes.xml", "codegen/in/apiref")]
[DeploymentItem("Deployed Files/D2DTypes2.xml", "codegen/in/apiref")]
[DeploymentItem("Deployed Files/D2DTypes3.xml", "codegen/in/apiref")]
[DeploymentItem("Deployed Files/Settings.xml", "codegen/in")]
public void OutputIsInSync()
{
//
// This test sets codegen to generate its output to some temporary
// files, and then diffs the temporary files with what's checked in.
//
// This allows us to detect if the output files were manually
// edited, or someone changed codegen without re-running it.
//
// The tests are executed from a deployed directory that contains
// the test executable / dependent assemblies and the
// DeploymentItems listed above. The codegen outputs under this
// directory as well. The test runner cleans up the entire deploy
// directory on exit.
//
string inputDir = "codegen/in";
string expectedDir = "codegen/expected";
string actualDir = "codegen/actual";
// Run the codegen
CodeGen.Program.ProcessedInputFiles input = CodeGen.Program.ProcessInputFiles(inputDir);
CodeGen.Program.GenerateCode(input, actualDir);
// Verify the output from the codegen matches what was expected
var expectedDirectoryInfo = new DirectoryInfo(expectedDir);
var actualDirectoryInfo = new DirectoryInfo(actualDir);
FileInfo[] expectedGeneratedFiles = expectedDirectoryInfo.GetFiles("*.codegen.*");
FileInfo[] actualGeneratedFiles = actualDirectoryInfo.GetFiles(); // Used for .Length only
// Ensure the correct number of files was generated.
Assert.AreEqual(1, expectedGeneratedFiles.Length);
Assert.AreEqual(expectedGeneratedFiles.Length, actualGeneratedFiles.Length);
// For each codegenned file in the tree, ensure it was output to the test folder.
CheckFilesMatch(expectedGeneratedFiles, actualDir);
}
private void CheckFilesMatch(FileInfo[] expectedGeneratedFiles, string actualDir)
{
foreach (FileInfo expectedFile in expectedGeneratedFiles)
{
FileInfo actualFile = new FileInfo(Path.Combine(actualDir, expectedFile.Name));
Assert.IsTrue(actualFile.Exists);
string expectedFileContent = File.ReadAllText(expectedFile.FullName);
string actualFileContent = File.ReadAllText(actualFile.FullName);
Assert.AreEqual(expectedFileContent, actualFileContent);
}
}
[TestMethod]
[DeploymentItem("Deployed Files/D2DEffectAuthor.xml", "codegen/in/apiref")]
[DeploymentItem("Deployed Files/D2DTypes.xml", "codegen/in/apiref")]
[DeploymentItem("Deployed Files/D2DTypes2.xml", "codegen/in/apiref")]
[DeploymentItem("Deployed Files/D2DTypes3.xml", "codegen/in/apiref")]
[DeploymentItem("Deployed Files/Settings.xml", "codegen/in")]
public void OverridesAreWellFormed()
{
List<string> files = CodeGen.Program.GetInputFileList();
string inputDir = "codegen/in";
Overrides.XmlBindings.Settings overridesXmlData = XmlBindings.Utilities.LoadXmlData<Overrides.XmlBindings.Settings>(inputDir, "Settings.xml");
Formatter.Prefix = overridesXmlData.Prefix.Value;
List<D2DTypes> typeDocuments = new List<D2DTypes>();
Dictionary<string, QualifiableType> typeDictionary = new Dictionary<string, QualifiableType>();
OutputDataTypes outputDataTypes = new OutputDataTypes();
foreach (string fileName in files)
{
XmlBindings.D2DTypes xmlDocument = XmlBindings.Utilities.LoadXmlData<XmlBindings.D2DTypes>(inputDir, fileName);
typeDocuments.Add(new D2DTypes(xmlDocument, overridesXmlData, typeDictionary, outputDataTypes));
}
foreach (Overrides.XmlBindings.Primitive overridePrimitive in overridesXmlData.Primitives)
{
Assert.IsTrue(typeDictionary.ContainsKey(overridePrimitive.Name), "Unexpected override primitive: " + overridePrimitive.Name);
}
foreach (Overrides.XmlBindings.Namespace overrideNamespace in overridesXmlData.Namespaces)
{
// Skip Effects namespace because it have different logic
if (overrideNamespace.Name == "Effects")
continue;
Assert.IsTrue(overrideNamespace.Name == "D2D" || overrideNamespace.Name == "D2D1", "Unexpected override namespace: " + overrideNamespace.Name);
foreach (Overrides.XmlBindings.Struct overrideStruct in overrideNamespace.Structs)
{
string nameKey = overrideNamespace.Name + "::" + overrideStruct.Name;
Assert.IsTrue(typeDictionary.ContainsKey(nameKey), "Unexpected override struct: " + overrideStruct.Name);
}
foreach (Overrides.XmlBindings.Enum overrideEnum in overrideNamespace.Enums)
{
string nameKey = overrideNamespace.Name + "::" + overrideEnum.Name;
Assert.IsTrue(typeDictionary.ContainsKey(nameKey), "Unexpected override enum: " + overrideEnum.Name);
CodeGen.Enum e = (CodeGen.Enum)(typeDictionary[nameKey]);
foreach (Overrides.XmlBindings.EnumValue overrideEnumValue in overrideEnum.Values)
{
CodeGen.EnumValue match = e.Values.Find(x => x.RawNameComponent == overrideEnumValue.Name);
Assert.IsNotNull(match, "Unexpected override enum value: " + overrideEnum + "::" + overrideEnumValue.Name);
}
}
}
}
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Security.Principal
{
//
// Identifier authorities
//
internal enum IdentifierAuthority : long
{
NullAuthority = 0,
WorldAuthority = 1,
LocalAuthority = 2,
CreatorAuthority = 3,
NonUniqueAuthority = 4,
NTAuthority = 5,
SiteServerAuthority = 6,
InternetSiteAuthority = 7,
ExchangeAuthority = 8,
ResourceManagerAuthority = 9,
}
//
// SID name usage
//
internal enum SidNameUse
{
User = 1,
Group = 2,
Domain = 3,
Alias = 4,
WellKnownGroup = 5,
DeletedAccount = 6,
Invalid = 7,
Unknown = 8,
Computer = 9,
}
//
// Well-known SID types
//
public enum WellKnownSidType
{
/// <summary>Indicates a null SID.</summary>
NullSid = 0,
/// <summary>Indicates a SID that matches everyone.</summary>
WorldSid = 1,
/// <summary>Indicates a local SID.</summary>
LocalSid = 2,
/// <summary>Indicates a SID that matches the owner or creator of an object.</summary>
CreatorOwnerSid = 3,
/// <summary>Indicates a SID that matches the creator group of an object.</summary>
CreatorGroupSid = 4,
/// <summary>Indicates a creator owner server SID.</summary>
CreatorOwnerServerSid = 5,
/// <summary>Indicates a creator group server SID.</summary>
CreatorGroupServerSid = 6,
/// <summary>Indicates a SID for the Windows NT authority account.</summary>
NTAuthoritySid = 7,
/// <summary>Indicates a SID for a dial-up account.</summary>
DialupSid = 8,
/// <summary>Indicates a SID for a network account. This SID is added to the process of a token when it logs on across a network.</summary>
NetworkSid = 9,
/// <summary>Indicates a SID for a batch process. This SID is added to the process of a token when it logs on as a batch job.</summary>
BatchSid = 10,
/// <summary>Indicates a SID for an interactive account. This SID is added to the process of a token when it logs on interactively.</summary>
InteractiveSid = 11,
/// <summary>Indicates a SID for a service. This SID is added to the process of a token when it logs on as a service.</summary>
ServiceSid = 12,
/// <summary>Indicates a SID for the anonymous account.</summary>
AnonymousSid = 13,
/// <summary>Indicates a proxy SID.</summary>
ProxySid = 14,
/// <summary>Indicates a SID for an enterprise controller.</summary>
EnterpriseControllersSid = 15,
/// <summary>Indicates a SID for self.</summary>
SelfSid = 16,
/// <summary>Indicates a SID that matches any authenticated user.</summary>
AuthenticatedUserSid = 17,
/// <summary>Indicates a SID for restricted code.</summary>
RestrictedCodeSid = 18,
/// <summary>Indicates a SID that matches a terminal server account.</summary>
TerminalServerSid = 19,
/// <summary>Indicates a SID that matches remote logons.</summary>
RemoteLogonIdSid = 20,
/// <summary>Indicates a SID that matches logon IDs.</summary>
LogonIdsSid = 21,
/// <summary>Indicates a SID that matches the local system.</summary>
LocalSystemSid = 22,
/// <summary>Indicates a SID that matches a local service.</summary>
LocalServiceSid = 23,
/// <summary>Indicates a SID that matches a network service.</summary>
NetworkServiceSid = 24,
/// <summary>Indicates a SID that matches the domain account.</summary>
BuiltinDomainSid = 25,
/// <summary>Indicates a SID that matches the administrator group.</summary>
BuiltinAdministratorsSid = 26,
/// <summary>Indicates a SID that matches built-in user accounts.</summary>
BuiltinUsersSid = 27,
/// <summary>Indicates a SID that matches the guest account.</summary>
BuiltinGuestsSid = 28,
/// <summary>Indicates a SID that matches the power users group.</summary>
BuiltinPowerUsersSid = 29,
/// <summary>Indicates a SID that matches the account operators account.</summary>
BuiltinAccountOperatorsSid = 30,
/// <summary>Indicates a SID that matches the system operators group.</summary>
BuiltinSystemOperatorsSid = 31,
/// <summary>Indicates a SID that matches the print operators group.</summary>
BuiltinPrintOperatorsSid = 32,
/// <summary>Indicates a SID that matches the backup operators group.</summary>
BuiltinBackupOperatorsSid = 33,
/// <summary>Indicates a SID that matches the replicator account.</summary>
BuiltinReplicatorSid = 34,
/// <summary>Indicates a SID that matches pre-Windows 2000 compatible accounts.</summary>
BuiltinPreWindows2000CompatibleAccessSid = 35,
/// <summary>Indicates a SID that matches remote desktop users.</summary>
BuiltinRemoteDesktopUsersSid = 36,
/// <summary>Indicates a SID that matches the network operators group.</summary>
BuiltinNetworkConfigurationOperatorsSid = 37,
/// <summary>Indicates a SID that matches the account administrator's account.</summary>
AccountAdministratorSid = 38,
/// <summary>Indicates a SID that matches the account guest group.</summary>
AccountGuestSid = 39,
/// <summary>Indicates a SID that matches account Kerberos target group.</summary>
AccountKrbtgtSid = 40,
/// <summary>Indicates a SID that matches the account domain administrator group.</summary>
AccountDomainAdminsSid = 41,
/// <summary>Indicates a SID that matches the account domain users group.</summary>
AccountDomainUsersSid = 42,
/// <summary>Indicates a SID that matches the account domain guests group.</summary>
AccountDomainGuestsSid = 43,
/// <summary>Indicates a SID that matches the account computer group.</summary>
AccountComputersSid = 44,
/// <summary>Indicates a SID that matches the account controller group.</summary>
AccountControllersSid = 45,
/// <summary>Indicates a SID that matches the certificate administrators group.</summary>
AccountCertAdminsSid = 46,
/// <summary>Indicates a SID that matches the schema administrators group.</summary>
AccountSchemaAdminsSid = 47,
/// <summary>Indicates a SID that matches the enterprise administrators group.</summary>
AccountEnterpriseAdminsSid = 48,
/// <summary>Indicates a SID that matches the policy administrators group.</summary>
AccountPolicyAdminsSid = 49,
/// <summary>Indicates a SID that matches the RAS and IAS server account.</summary>
AccountRasAndIasServersSid = 50,
/// <summary>Indicates a SID present when the Microsoft NTLM authentication package authenticated the client.</summary>
NtlmAuthenticationSid = 51,
/// <summary>Indicates a SID present when the Microsoft Digest authentication package authenticated the client.</summary>
DigestAuthenticationSid = 52,
/// <summary>Indicates a SID present when the Secure Channel (SSL/TLS) authentication package authenticated the client.</summary>
SChannelAuthenticationSid = 53,
/// <summary>Indicates a SID present when the user authenticated from within the forest or across a trust that does not have the selective authentication option enabled. If this SID is present, then <see cref="WinOtherOrganizationSid"/> cannot be present.</summary>
ThisOrganizationSid = 54,
/// <summary>Indicates a SID present when the user authenticated across a forest with the selective authentication option enabled. If this SID is present, then <see cref="WinThisOrganizationSid"/> cannot be present.</summary>
OtherOrganizationSid = 55,
/// <summary>Indicates a SID that allows a user to create incoming forest trusts. It is added to the token of users who are a member of the Incoming Forest Trust Builders built-in group in the root domain of the forest.</summary>
BuiltinIncomingForestTrustBuildersSid = 56,
/// <summary>Indicates a SID that matches the performance monitor user group.</summary>
BuiltinPerformanceMonitoringUsersSid = 57,
/// <summary>Indicates a SID that matches the performance log user group.</summary>
BuiltinPerformanceLoggingUsersSid = 58,
/// <summary>Indicates a SID that matches the Windows Authorization Access group.</summary>
BuiltinAuthorizationAccessSid = 59,
/// <summary>Indicates a SID is present in a server that can issue terminal server licenses.</summary>
WinBuiltinTerminalServerLicenseServersSid = 60,
[Obsolete("This member has been depcreated and is only maintained for backwards compatability. WellKnownSidType values greater than MaxDefined may be defined in future releases.")]
[EditorBrowsable(EditorBrowsableState.Never)]
MaxDefined = WinBuiltinTerminalServerLicenseServersSid,
/// <summary>Indicates a SID that matches the distributed COM user group.</summary>
WinBuiltinDCOMUsersSid = 61,
/// <summary>Indicates a SID that matches the Internet built-in user group.</summary>
WinBuiltinIUsersSid = 62,
/// <summary>Indicates a SID that matches the Internet user group.</summary>
WinIUserSid = 63,
/// <summary>Indicates a SID that allows a user to use cryptographic operations. It is added to the token of users who are a member of the CryptoOperators built-in group. </summary>
WinBuiltinCryptoOperatorsSid = 64,
/// <summary>Indicates a SID that matches an untrusted label.</summary>
WinUntrustedLabelSid = 65,
/// <summary>Indicates a SID that matches an low level of trust label.</summary>
WinLowLabelSid = 66,
/// <summary>Indicates a SID that matches an medium level of trust label.</summary>
WinMediumLabelSid = 67,
/// <summary>Indicates a SID that matches a high level of trust label.</summary>
WinHighLabelSid = 68,
/// <summary>Indicates a SID that matches a system label.</summary>
WinSystemLabelSid = 69,
/// <summary>Indicates a SID that matches a write restricted code group.</summary>
WinWriteRestrictedCodeSid = 70,
/// <summary>Indicates a SID that matches a creator and owner rights group.</summary>
WinCreatorOwnerRightsSid = 71,
/// <summary>Indicates a SID that matches a cacheable principals group.</summary>
WinCacheablePrincipalsGroupSid = 72,
/// <summary>Indicates a SID that matches a non-cacheable principals group.</summary>
WinNonCacheablePrincipalsGroupSid = 73,
/// <summary>Indicates a SID that matches an enterprise wide read-only controllers group.</summary>
WinEnterpriseReadonlyControllersSid = 74,
/// <summary>Indicates a SID that matches an account read-only controllers group.</summary>
WinAccountReadonlyControllersSid = 75,
/// <summary>Indicates a SID that matches an event log readers group.</summary>
WinBuiltinEventLogReadersGroup = 76,
/// <summary>Indicates a SID that matches a read-only enterprise domain controller.</summary>
WinNewEnterpriseReadonlyControllersSid = 77,
/// <summary>Indicates a SID that matches the built-in DCOM certification services access group.</summary>
WinBuiltinCertSvcDComAccessGroup = 78,
/// <summary>Indicates a SID that matches the medium plus integrity label.</summary>
WinMediumPlusLabelSid = 79,
/// <summary>Indicates a SID that matches a local logon group.</summary>
WinLocalLogonSid = 80,
/// <summary>Indicates a SID that matches a console logon group.</summary>
WinConsoleLogonSid = 81,
/// <summary>Indicates a SID that matches a certificate for the given organization.</summary>
WinThisOrganizationCertificateSid = 82,
/// <summary>Indicates a SID that matches the application package authority.</summary>
WinApplicationPackageAuthoritySid = 83,
/// <summary>Indicates a SID that applies to all app containers.</summary>
WinBuiltinAnyPackageSid = 84,
/// <summary>Indicates a SID of Internet client capability for app containers.</summary>
WinCapabilityInternetClientSid = 85,
/// <summary>Indicates a SID of Internet client and server capability for app containers.</summary>
WinCapabilityInternetClientServerSid = 86,
/// <summary>Indicates a SID of private network client and server capability for app containers.</summary>
WinCapabilityPrivateNetworkClientServerSid = 87,
/// <summary>Indicates a SID for pictures library capability for app containers.</summary>
WinCapabilityPicturesLibrarySid = 88,
/// <summary>Indicates a SID for videos library capability for app containers.</summary>
WinCapabilityVideosLibrarySid = 89,
/// <summary>Indicates a SID for music library capability for app containers.</summary>
WinCapabilityMusicLibrarySid = 90,
/// <summary>Indicates a SID for documents library capability for app containers.</summary>
WinCapabilityDocumentsLibrarySid = 91,
/// <summary>Indicates a SID for shared user certificates capability for app containers.</summary>
WinCapabilitySharedUserCertificatesSid = 92,
/// <summary>Indicates a SID for Windows credentials capability for app containers.</summary>
WinCapabilityEnterpriseAuthenticationSid = 93,
/// <summary>Indicates a SID for removable storage capability for app containers.</summary>
WinCapabilityRemovableStorageSid = 94
// Note: Adding additional values require changes everywhere where the value above is used as the maximum defined WellKnownSidType value.
// E.g. System.Security.Principal.SecurityIdentifier constructor
}
//
// This class implements revision 1 SIDs
// NOTE: The SecurityIdentifier class is immutable and must remain this way
//
public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier>
{
#region Public Constants
//
// Identifier authority must be at most six bytes long
//
internal static readonly long MaxIdentifierAuthority = 0xFFFFFFFFFFFF;
//
// Maximum number of subauthorities in a SID
//
internal static readonly byte MaxSubAuthorities = 15;
//
// Minimum length of a binary representation of a SID
//
public static readonly int MinBinaryLength = 1 + 1 + 6; // Revision (1) + subauth count (1) + identifier authority (6)
//
// Maximum length of a binary representation of a SID
//
public static readonly int MaxBinaryLength = 1 + 1 + 6 + MaxSubAuthorities * 4; // 4 bytes for each subauth
#endregion
#region Private Members
//
// Immutable properties of a SID
//
private IdentifierAuthority _identifierAuthority;
private int[] _subAuthorities;
private byte[] _binaryForm;
private SecurityIdentifier _accountDomainSid;
private bool _accountDomainSidInitialized = false;
//
// Computed attributes of a SID
//
private string _sddlForm = null;
#endregion
#region Constructors
//
// Shared constructor logic
// NOTE: subauthorities are really unsigned integers, but due to CLS
// lack of support for unsigned integers the caller must perform
// the typecast
//
private void CreateFromParts(IdentifierAuthority identifierAuthority, int[] subAuthorities)
{
if (subAuthorities == null)
{
throw new ArgumentNullException(nameof(subAuthorities));
}
//
// Check the number of subauthorities passed in
//
if (subAuthorities.Length > MaxSubAuthorities)
{
throw new ArgumentOutOfRangeException(
"subAuthorities.Length",
subAuthorities.Length,
SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities));
}
//
// Identifier authority is at most 6 bytes long
//
if (identifierAuthority < 0 ||
(long)identifierAuthority > MaxIdentifierAuthority)
{
throw new ArgumentOutOfRangeException(
nameof(identifierAuthority),
identifierAuthority,
SR.IdentityReference_IdentifierAuthorityTooLarge);
}
//
// Create a local copy of the data passed in
//
_identifierAuthority = identifierAuthority;
_subAuthorities = new int[subAuthorities.Length];
subAuthorities.CopyTo(_subAuthorities, 0);
//
// Compute and store the binary form
//
// typedef struct _SID {
// UCHAR Revision;
// UCHAR SubAuthorityCount;
// SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
// ULONG SubAuthority[ANYSIZE_ARRAY]
// } SID, *PISID;
//
byte i;
_binaryForm = new byte[1 + 1 + 6 + 4 * this.SubAuthorityCount];
//
// First two bytes contain revision and subauthority count
//
_binaryForm[0] = Revision;
_binaryForm[1] = (byte)this.SubAuthorityCount;
//
// Identifier authority takes up 6 bytes
//
for (i = 0; i < 6; i++)
{
_binaryForm[2 + i] = (byte)((((ulong)_identifierAuthority) >> ((5 - i) * 8)) & 0xFF);
}
//
// Subauthorities go last, preserving big-endian representation
//
for (i = 0; i < this.SubAuthorityCount; i++)
{
byte shift;
for (shift = 0; shift < 4; shift += 1)
{
_binaryForm[8 + 4 * i + shift] = unchecked((byte)(((ulong)_subAuthorities[i]) >> (shift * 8)));
}
}
}
private void CreateFromBinaryForm(byte[] binaryForm, int offset)
{
//
// Give us something to work with
//
if (binaryForm == null)
{
throw new ArgumentNullException(nameof(binaryForm));
}
//
// Negative offsets are not allowed
//
if (offset < 0)
{
throw new ArgumentOutOfRangeException(
nameof(offset),
offset,
SR.ArgumentOutOfRange_NeedNonNegNum);
}
//
// At least a minimum-size SID should fit in the buffer
//
if (binaryForm.Length - offset < SecurityIdentifier.MinBinaryLength)
{
throw new ArgumentOutOfRangeException(
nameof(binaryForm),
SR.ArgumentOutOfRange_ArrayTooSmall);
}
IdentifierAuthority Authority;
int[] SubAuthorities;
//
// Extract the elements of a SID
//
if (binaryForm[offset] != Revision)
{
//
// Revision is incorrect
//
throw new ArgumentException(
SR.IdentityReference_InvalidSidRevision,
nameof(binaryForm));
}
//
// Insist on the correct number of subauthorities
//
if (binaryForm[offset + 1] > MaxSubAuthorities)
{
throw new ArgumentException(
SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities),
nameof(binaryForm));
}
//
// Make sure the buffer is big enough
//
int Length = 1 + 1 + 6 + 4 * binaryForm[offset + 1];
if (binaryForm.Length - offset < Length)
{
throw new ArgumentException(
SR.ArgumentOutOfRange_ArrayTooSmall,
nameof(binaryForm));
}
Authority =
(IdentifierAuthority)(
(((long)binaryForm[offset + 2]) << 40) +
(((long)binaryForm[offset + 3]) << 32) +
(((long)binaryForm[offset + 4]) << 24) +
(((long)binaryForm[offset + 5]) << 16) +
(((long)binaryForm[offset + 6]) << 8) +
(((long)binaryForm[offset + 7])));
SubAuthorities = new int[binaryForm[offset + 1]];
//
// Subauthorities are represented in big-endian format
//
for (byte i = 0; i < binaryForm[offset + 1]; i++)
{
unchecked
{
SubAuthorities[i] =
(int)(
(((uint)binaryForm[offset + 8 + 4 * i + 0]) << 0) +
(((uint)binaryForm[offset + 8 + 4 * i + 1]) << 8) +
(((uint)binaryForm[offset + 8 + 4 * i + 2]) << 16) +
(((uint)binaryForm[offset + 8 + 4 * i + 3]) << 24));
}
}
CreateFromParts(Authority, SubAuthorities);
return;
}
//
// Constructs a SecurityIdentifier object from its string representation
// Returns 'null' if string passed in is not a valid SID
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier(string sddlForm)
{
byte[] resultSid;
//
// Give us something to work with
//
if (sddlForm == null)
{
throw new ArgumentNullException(nameof(sddlForm));
}
//
// Call into the underlying O/S conversion routine
//
int Error = Win32.CreateSidFromString(sddlForm, out resultSid);
if (Error == Interop.Errors.ERROR_INVALID_SID)
{
throw new ArgumentException(SR.Argument_InvalidValue, nameof(sddlForm));
}
else if (Error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (Error != Interop.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateSidFromString returned unrecognized error {0}", Error));
throw new Win32Exception(Error);
}
CreateFromBinaryForm(resultSid, 0);
}
//
// Constructs a SecurityIdentifier object from its binary representation
//
public SecurityIdentifier(byte[] binaryForm, int offset)
{
CreateFromBinaryForm(binaryForm, offset);
}
//
// Constructs a SecurityIdentifier object from an IntPtr
//
public SecurityIdentifier(IntPtr binaryForm)
: this(binaryForm, true)
{
}
internal SecurityIdentifier(IntPtr binaryForm, bool noDemand)
: this(Win32.ConvertIntPtrSidToByteArraySid(binaryForm), 0)
{
}
//
// Constructs a well-known SID
// The 'domainSid' parameter is optional and only used
// by the well-known types that require it
// NOTE: although there is a P/Invoke call involved in the implementation of this constructor,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
{
//
// sidType must not be equal to LogonIdsSid
//
if (sidType == WellKnownSidType.LogonIdsSid)
{
throw new ArgumentException(SR.IdentityReference_CannotCreateLogonIdsSid, nameof(sidType));
}
byte[] resultSid;
int Error;
//
// sidType should not exceed the max defined value
//
if ((sidType < WellKnownSidType.NullSid) || (sidType > WellKnownSidType.WinCapabilityRemovableStorageSid))
{
throw new ArgumentException(SR.Argument_InvalidValue, nameof(sidType));
}
//
// for sidType between 38 to 50, the domainSid parameter must be specified
//
if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid))
{
if (domainSid == null)
{
throw new ArgumentNullException(nameof(domainSid), SR.Format(SR.IdentityReference_DomainSidRequired, sidType));
}
//
// verify that the domain sid is a valid windows domain sid
// to do that we call GetAccountDomainSid and the return value should be the same as the domainSid
//
SecurityIdentifier resultDomainSid;
int ErrorCode;
ErrorCode = Win32.GetWindowsAccountDomainSid(domainSid, out resultDomainSid);
if (ErrorCode == Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
{
throw new OutOfMemoryException();
}
else if (ErrorCode == Interop.Errors.ERROR_NON_ACCOUNT_SID)
{
// this means that the domain sid is not valid
throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid));
}
else if (ErrorCode != Interop.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", ErrorCode));
throw new Win32Exception(ErrorCode);
}
//
// if domainSid is passed in as S-1-5-21-3-4-5-6, the above api will return S-1-5-21-3-4-5 as the domainSid
// Since these do not match S-1-5-21-3-4-5-6 is not a valid domainSid (wrong number of subauthorities)
//
if (resultDomainSid != domainSid)
{
throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid));
}
}
Error = Win32.CreateWellKnownSid(sidType, domainSid, out resultSid);
if (Error == Interop.Errors.ERROR_INVALID_PARAMETER)
{
throw new ArgumentException(new Win32Exception(Error).Message, "sidType/domainSid");
}
else if (Error != Interop.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateWellKnownSid returned unrecognized error {0}", Error));
throw new Win32Exception(Error);
}
CreateFromBinaryForm(resultSid, 0);
}
internal SecurityIdentifier(SecurityIdentifier domainSid, uint rid)
{
int i;
int[] SubAuthorities = new int[domainSid.SubAuthorityCount + 1];
for (i = 0; i < domainSid.SubAuthorityCount; i++)
{
SubAuthorities[i] = domainSid.GetSubAuthority(i);
}
SubAuthorities[i] = (int)rid;
CreateFromParts(domainSid.IdentifierAuthority, SubAuthorities);
}
internal SecurityIdentifier(IdentifierAuthority identifierAuthority, int[] subAuthorities)
{
CreateFromParts(identifierAuthority, subAuthorities);
}
#endregion
#region Static Properties
//
// Revision is always '1'
//
internal static byte Revision
{
get
{
return 1;
}
}
#endregion
#region Non-static Properties
//
// This is for internal consumption only, hence it is marked 'internal'
// Making this call public would require a deep copy of the data to
// prevent the caller from messing with the internal representation.
//
internal byte[] BinaryForm
{
get
{
return _binaryForm;
}
}
internal IdentifierAuthority IdentifierAuthority
{
get
{
return _identifierAuthority;
}
}
internal int SubAuthorityCount
{
get
{
return _subAuthorities.Length;
}
}
public int BinaryLength
{
get
{
return _binaryForm.Length;
}
}
//
// Returns the domain portion of a SID or null if the specified
// SID is not an account SID
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier AccountDomainSid
{
get
{
if (!_accountDomainSidInitialized)
{
_accountDomainSid = GetAccountDomainSid();
_accountDomainSidInitialized = true;
}
return _accountDomainSid;
}
}
#endregion
#region Inherited properties and methods
public override bool Equals(object o)
{
return (this == o as SecurityIdentifier); // invokes operator==
}
public bool Equals(SecurityIdentifier sid)
{
return (this == sid); // invokes operator==
}
public override int GetHashCode()
{
int hashCode = ((long)this.IdentifierAuthority).GetHashCode();
for (int i = 0; i < SubAuthorityCount; i++)
{
hashCode ^= this.GetSubAuthority(i);
}
return hashCode;
}
public override string ToString()
{
if (_sddlForm == null)
{
StringBuilder result = new StringBuilder();
//
// Typecasting of _IdentifierAuthority to a long below is important, since
// otherwise you would see this: "S-1-NTAuthority-32-544"
//
result.AppendFormat("S-1-{0}", (long)_identifierAuthority);
for (int i = 0; i < SubAuthorityCount; i++)
{
result.AppendFormat("-{0}", (uint)(_subAuthorities[i]));
}
_sddlForm = result.ToString();
}
return _sddlForm;
}
public override string Value
{
get
{
return ToString().ToUpperInvariant();
}
}
internal static bool IsValidTargetTypeStatic(Type targetType)
{
if (targetType == typeof(NTAccount))
{
return true;
}
else if (targetType == typeof(SecurityIdentifier))
{
return true;
}
else
{
return false;
}
}
public override bool IsValidTargetType(Type targetType)
{
return IsValidTargetTypeStatic(targetType);
}
internal SecurityIdentifier GetAccountDomainSid()
{
SecurityIdentifier ResultSid;
int Error;
Error = Win32.GetWindowsAccountDomainSid(this, out ResultSid);
if (Error == Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
{
throw new OutOfMemoryException();
}
else if (Error == Interop.Errors.ERROR_NON_ACCOUNT_SID)
{
ResultSid = null;
}
else if (Error != Interop.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", Error));
throw new Win32Exception(Error);
}
return ResultSid;
}
public bool IsAccountSid()
{
if (!_accountDomainSidInitialized)
{
_accountDomainSid = GetAccountDomainSid();
_accountDomainSidInitialized = true;
}
if (_accountDomainSid == null)
{
return false;
}
return true;
}
public override IdentityReference Translate(Type targetType)
{
if (targetType == null)
{
throw new ArgumentNullException(nameof(targetType));
}
if (targetType == typeof(SecurityIdentifier))
{
return this; // assumes SecurityIdentifier objects are immutable
}
else if (targetType == typeof(NTAccount))
{
IdentityReferenceCollection irSource = new IdentityReferenceCollection(1);
irSource.Add(this);
IdentityReferenceCollection irTarget;
irTarget = SecurityIdentifier.Translate(irSource, targetType, true);
return irTarget[0];
}
else
{
throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType));
}
}
#endregion
#region Operators
public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right)
{
object l = left;
object r = right;
if (l == r)
{
return true;
}
else if (l == null || r == null)
{
return false;
}
else
{
return (left.CompareTo(right) == 0);
}
}
public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right)
{
return !(left == right);
}
#endregion
#region IComparable implementation
public int CompareTo(SecurityIdentifier sid)
{
if (sid == null)
{
throw new ArgumentNullException(nameof(sid));
}
if (this.IdentifierAuthority < sid.IdentifierAuthority)
{
return -1;
}
if (this.IdentifierAuthority > sid.IdentifierAuthority)
{
return 1;
}
if (this.SubAuthorityCount < sid.SubAuthorityCount)
{
return -1;
}
if (this.SubAuthorityCount > sid.SubAuthorityCount)
{
return 1;
}
for (int i = 0; i < this.SubAuthorityCount; i++)
{
int diff = this.GetSubAuthority(i) - sid.GetSubAuthority(i);
if (diff != 0)
{
return diff;
}
}
return 0;
}
#endregion
#region Public Methods
internal int GetSubAuthority(int index)
{
return _subAuthorities[index];
}
//
// Determines whether this SID is a well-known SID of the specified type
//
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public bool IsWellKnown(WellKnownSidType type)
{
return Win32.IsWellKnownSid(this, type);
}
public void GetBinaryForm(byte[] binaryForm, int offset)
{
_binaryForm.CopyTo(binaryForm, offset);
}
//
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public bool IsEqualDomainSid(SecurityIdentifier sid)
{
return Win32.IsEqualDomainSid(this, sid);
}
private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed)
{
if (sourceSids == null)
{
throw new ArgumentNullException(nameof(sourceSids));
}
if (sourceSids.Count == 0)
{
throw new ArgumentException(SR.Arg_EmptyCollection, nameof(sourceSids));
}
IntPtr[] SidArrayPtr = new IntPtr[sourceSids.Count];
GCHandle[] HandleArray = new GCHandle[sourceSids.Count];
SafeLsaPolicyHandle LsaHandle = SafeLsaPolicyHandle.InvalidHandle;
SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle;
SafeLsaMemoryHandle NamesPtr = SafeLsaMemoryHandle.InvalidHandle;
try
{
//
// Pin all elements in the array of SIDs
//
int currentSid = 0;
foreach (IdentityReference id in sourceSids)
{
SecurityIdentifier sid = id as SecurityIdentifier;
if (sid == null)
{
throw new ArgumentException(SR.Argument_ImproperType, nameof(sourceSids));
}
HandleArray[currentSid] = GCHandle.Alloc(sid.BinaryForm, GCHandleType.Pinned);
SidArrayPtr[currentSid] = HandleArray[currentSid].AddrOfPinnedObject();
currentSid++;
}
//
// Open LSA policy (for lookup requires it)
//
LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
//
// Perform the actual lookup
//
someFailed = false;
uint ReturnCode;
ReturnCode = Interop.Advapi32.LsaLookupSids(LsaHandle, sourceSids.Count, SidArrayPtr, ref ReferencedDomainsPtr, ref NamesPtr);
//
// Make a decision regarding whether it makes sense to proceed
// based on the return code and the value of the forceSuccess argument
//
if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY ||
ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES)
{
throw new OutOfMemoryException();
}
else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED ||
ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
{
someFailed = true;
}
else if (ReturnCode != 0)
{
uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError(ReturnCode);
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupSids returned {0}", win32ErrorCode));
throw new Win32Exception(unchecked((int)win32ErrorCode));
}
NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_NAME>());
Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
//
// Interpret the results and generate NTAccount objects
//
IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceSids.Count);
if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
{
//
// Interpret the results and generate NT Account objects
//
Interop.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0);
string[] ReferencedDomains = new string[rdl.Entries];
for (int i = 0; i < rdl.Entries; i++)
{
Interop.LSA_TRUST_INFORMATION ti = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure<Interop.LSA_TRUST_INFORMATION>(new IntPtr((long)rdl.Domains + i * Marshal.SizeOf<Interop.LSA_TRUST_INFORMATION>()));
ReferencedDomains[i] = Marshal.PtrToStringUni(ti.Name.Buffer, ti.Name.Length / sizeof(char));
}
Interop.LSA_TRANSLATED_NAME[] translatedNames = new Interop.LSA_TRANSLATED_NAME[sourceSids.Count];
NamesPtr.ReadArray(0, translatedNames, 0, translatedNames.Length);
for (int i = 0; i < sourceSids.Count; i++)
{
Interop.LSA_TRANSLATED_NAME Ltn = translatedNames[i];
switch ((SidNameUse)Ltn.Use)
{
case SidNameUse.User:
case SidNameUse.Group:
case SidNameUse.Alias:
case SidNameUse.Computer:
case SidNameUse.WellKnownGroup:
string account = Marshal.PtrToStringUni(Ltn.Name.Buffer, Ltn.Name.Length / sizeof(char)); ;
string domain = ReferencedDomains[Ltn.DomainIndex];
Result.Add(new NTAccount(domain, account));
break;
default:
someFailed = true;
Result.Add(sourceSids[i]);
break;
}
}
}
else
{
for (int i = 0; i < sourceSids.Count; i++)
{
Result.Add(sourceSids[i]);
}
}
return Result;
}
finally
{
for (int i = 0; i < sourceSids.Count; i++)
{
if (HandleArray[i].IsAllocated)
{
HandleArray[i].Free();
}
}
LsaHandle.Dispose();
ReferencedDomainsPtr.Dispose();
NamesPtr.Dispose();
}
}
internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, bool forceSuccess)
{
bool SomeFailed = false;
IdentityReferenceCollection Result;
Result = Translate(sourceSids, targetType, out SomeFailed);
if (forceSuccess && SomeFailed)
{
IdentityReferenceCollection UnmappedIdentities = new IdentityReferenceCollection();
foreach (IdentityReference id in Result)
{
if (id.GetType() != targetType)
{
UnmappedIdentities.Add(id);
}
}
throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, UnmappedIdentities);
}
return Result;
}
internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, out bool someFailed)
{
if (sourceSids == null)
{
throw new ArgumentNullException(nameof(sourceSids));
}
if (targetType == typeof(NTAccount))
{
return TranslateToNTAccounts(sourceSids, out someFailed);
}
throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType));
}
#endregion
}
}
| |
// 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.
namespace Fixtures.MirrorPolymorphic
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Some cool documentation.
/// </summary>
public partial class PolymorphicAnimalStore : ServiceClient<PolymorphicAnimalStore>, IPolymorphicAnimalStore
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the PolymorphicAnimalStore class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public PolymorphicAnimalStore(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the PolymorphicAnimalStore class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public PolymorphicAnimalStore(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the PolymorphicAnimalStore class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public PolymorphicAnimalStore(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the PolymorphicAnimalStore class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public PolymorphicAnimalStore(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("https://management.azure.com/");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Animal>("dtype"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Animal>("dtype"));
}
/// <summary>
/// Product Types
/// </summary>
/// The Products endpoint returns information about the Uber products offered
/// at a given location. The response includes the display name and other
/// details about each product, and lists the products in the proper display
/// order.
/// <param name='animalCreateOrUpdateParameter'>
/// An Animal
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Animal>> CreateOrUpdatePolymorphicAnimalsWithHttpMessagesAsync(Animal animalCreateOrUpdateParameter = default(Animal), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("animalCreateOrUpdateParameter", animalCreateOrUpdateParameter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdatePolymorphicAnimals", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "getpolymorphicAnimals").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(animalCreateOrUpdateParameter, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Error2Exception(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error2 _errorBody = SafeJsonConvert.DeserializeObject<Error2>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Animal>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Animal>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.