context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) 2015 semdiffdotnet. Distributed under the MIT License.
// See LICENSE file or opensource.org/licenses/MIT.
using LibGit2Sharp;
using Newtonsoft.Json;
using SemDiff.Core.Exceptions;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SemDiff.Core
{
/// <summary>
/// Contains all the methods and classes necessary to use the GitHub api to pull down data about
/// pull requests. Additionally, contains the logic for authenticating
/// </summary>
public class Repo
{
private static readonly Regex _gitHubUrl = new Regex(@"(git@|https:\/\/)github\.com(:|\/)(.*)\/(.*)");
private static readonly ConcurrentDictionary<string, Repo> _repoLookup = new ConcurrentDictionary<string, Repo>();
private static readonly Regex cacheFolder = new Regex(@"^\.semdiff\/$");
private static readonly Regex nextLinkPattern = new Regex("<(http[^ ]*)>; *rel *= *\"next\"");
public Repo(string gitDir, string repoOwner, string repoName)
{
Owner = repoOwner;
RepoName = repoName;
LocalGitDirectory = gitDir;
EtagNoChanges = null;
Client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate })
{
BaseAddress = new Uri("https://api.github.com/")
};
Client.DefaultRequestHeaders.UserAgent.ParseAdd(nameof(SemDiff));
Client.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github.v3+json");
CacheDirectory = Path.Combine(LocalRepoDirectory, ".semdiff");
Directory.CreateDirectory(CacheDirectory);
UpdateGitIgnore();
GetConfiguration();
}
public string CacheDirectory { get; set; }
public string CachedLocalPullRequestListPath => Path.Combine(CacheDirectory, "LocalList.json");
public HttpClient Client { get; private set; }
public string ConfigFile => Path.Combine(CacheDirectory, "User_Config.json");
public string EtagNoChanges { get; set; }
public DateTime LastUpdate { get; internal set; } = DateTime.MinValue;
public LineEndingType LineEndings { get; set; }
public string LocalGitDirectory { get; }
public string LocalRepoDirectory => Path.GetDirectoryName(Path.GetDirectoryName(LocalGitDirectory));
public string Owner { get; set; }
public List<PullRequest> PullRequests { get; } = new List<PullRequest>();
public string RepoName { get; set; }
public int RequestsLimit { get; private set; }
public int RequestsRemaining { get; private set; }
/// <summary>
/// Looks for the git repo above the current file in the directory hierarchy. Null will be returned if no repo was found.
/// </summary>
/// <param name="filePath">Path to file in repo</param>
/// <returns>Representation of repo or null (to indicate not found)</returns>
public static Repo GetRepoFor(string filePath)
{
var repoDir = Repository.Discover(filePath);
if (repoDir == null)
{
return null;
}
return _repoLookup.GetOrAdd(repoDir, AddRepo);
}
/// <summary>
/// If the authentication file exists, it reads in the data.
/// If the authentication file doesn't exist, it creates a blank copy.
/// </summary>
public void GetConfiguration()
{
if (File.Exists(ConfigFile))
{
var json = File.ReadAllText(ConfigFile);
try
{
var auth = JsonConvert.DeserializeObject<Configuration>(json);
LineEndings = auth.LineEnding;
if (!string.IsNullOrWhiteSpace(auth.Username) && !string.IsNullOrWhiteSpace(auth.AuthToken))
{
UpdateAuthenticationHeader(auth.Username, auth.AuthToken);
}
}
catch (Exception ex)
{
//Directory.Delete(CacheDirectory); This may be a good idea with a few more checks
Logger.Error($"{ex.GetType().Name}: Couldn't deserialize {ConfigFile} because {ex.Message}");
}
}
else
{
var newAuth = new Configuration();
File.WriteAllText(ConfigFile, JsonConvert.SerializeObject(newAuth, Formatting.Indented));
}
}
//exposed for testing
internal void UpdateAuthenticationHeader(string authUsernam, string authToken)
{
AuthUsername = authUsernam;
AuthToken = authToken;
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{AuthUsername}:{AuthToken}")));
}
/// <summary>
/// Reads the pull requests from the persistent file
/// </summary>
public void GetCurrentSaved()
{
Debug.Assert(this != null);
try
{
if (!Directory.Exists(CacheDirectory))
return;
if (!File.Exists(CachedLocalPullRequestListPath))
return;
var json = File.ReadAllText(CachedLocalPullRequestListPath);
var list = JsonConvert.DeserializeObject<IEnumerable<PullRequest>>(json);
PullRequests.Clear();
foreach (var p in list)
{
//Restore Self-Referential Loops
p.ParentRepo = this;
foreach (var r in p.ValidFiles)
{
r.ParentPullRequst = p;
}
if (VerifyPullRequestCache(p))
{
PullRequests.Add(p);
foreach (var r in p.ValidFiles)
{
r.LoadFromCache();
}
}
else
{
if (Directory.Exists(p.CacheDirectory))
Directory.Delete(p.CacheDirectory, true);
}
}
UpdateLocalSavedList(); //In case some were deleted, write the file back
}
catch (Exception ex)
{
Logger.Error($"{ex.GetType().Name}: Couldn't load {CachedLocalPullRequestListPath} because {ex.Message}");
}
}
private static bool VerifyPullRequestCache(PullRequest p)
{
if (!Directory.Exists(p.CacheDirectory))
return false;
foreach (var f in p.ValidFiles)
{
if (!File.Exists(f.CachePathBase))
return false;
if (!File.Exists(f.CachePathHead))
return false;
}
return true;
}
/// <summary>
/// Gets each page of the pull request list from GitHub. Once the list is complete, get all
/// the pull request files for each pull request.
/// </summary>
/// <returns>List of pull request information.</returns>
public async Task<IList<PullRequest>> GetPullRequestsAsync()
{
var url = $"/repos/{Owner}/{RepoName}/pulls";
var etag = Ref.Create(EtagNoChanges);
var updated = await GetPaginatedListAsync<PullRequest>(url, etag);
var outdated = PullRequests;
EtagNoChanges = etag.Value;
if (updated == null)
{
return null;
}
if (outdated != null)
{
var prToRemove = outdated.Where(old => updated.All(newpr => newpr.Number != old.Number));
foreach (var pr in updated)
{
pr.ParentRepo = this;
var old = outdated.FirstOrDefault(o => o.Number == pr.Number);
if (old != null)
{
pr.LastWrite = old.LastWrite;
}
}
DeletePRsFromDisk(prToRemove);
}
await Task.WhenAll(updated.Select(async pr =>
{
var files = await GetPaginatedListAsync<RepoFile>($"/repos/{Owner}/{RepoName}/pulls/{pr.Number}/files");
foreach (var f in files)
{
f.ParentPullRequst = pr;
}
pr.Files = PullRequest.FilterFiles(files).ToList();
return pr;
}));
PullRequests.Clear();
PullRequests.AddRange(updated);
UpdateLocalSavedList();
return updated;
}
/// <summary>
/// Reads the .gitignore file. If ".semdiff/" is found in the file, nothing happens, otherwise it is added.
/// </summary>
public void UpdateGitIgnore()
{
var GitIgnore = Path.Combine(LocalRepoDirectory, ".gitignore");
var input = "";
if (File.Exists(GitIgnore))
{
input = File.ReadAllText(GitIgnore);
}
var UpdateGitIgnore = true;
var lines = input.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
var builder = new StringBuilder();
foreach (var line in lines)
{
if (cacheFolder.Match(line).Success)
{
UpdateGitIgnore = false;
}
}
if (UpdateGitIgnore)
{
builder.Append(input);
if (input != "")
{
builder.Append(Environment.NewLine);
}
string[] GitIgnoreAddition = { @"#The Semdiff cache folder", ".semdiff/" };
foreach (var line in GitIgnoreAddition)
{
builder.Append(line);
builder.Append(Environment.NewLine);
}
File.WriteAllText(GitIgnore, builder.ToString());
}
}
/// <summary>
/// Makes a request to GitHub to update RequestsRemaining and RequestsLimit
/// </summary>
public Task UpdateLimitAsync()
{
return HttpGetAsync("/rate_limit");
}
/// <summary>
/// Write the current internal list of pull requests to a file
/// </summary>
public void UpdateLocalSavedList()
{
Directory.CreateDirectory(CacheDirectory);
File.WriteAllText(CachedLocalPullRequestListPath, JsonConvert.SerializeObject(PullRequests, Formatting.Indented));
}
/// <summary>
/// Gets Pull Requests and the master branch if it has been modified, this method also insures that we don't update more than MaxUpdateInterval
/// </summary>
public async Task UpdateRemoteChangesAsync()
{
lock (this)
{
var elapsedSinceUpdate = (DateTime.Now - LastUpdate);
if (elapsedSinceUpdate <= MaxUpdateInterval)
{
return;
}
LastUpdate = DateTime.Now;
}
GetConfiguration();
var pulls = await GetPullRequestsAsync();
if (pulls == null)
{
return;
}
await Task.WhenAll(pulls.Select(p => p.GetFilesAsync()));
}
internal static void ClearCache()
{
_repoLookup.Clear();
}
#region Move to config object
public static TimeSpan MaxUpdateInterval { get; set; } = TimeSpan.FromMinutes(5);
public string AuthToken { get; set; }
public string AuthUsername { get; set; }
#endregion Move to config object
/// <summary>
/// Construct the absolute path of a file in a pull request
/// </summary>
/// <param name="repofolder">the path to the repo in the AppData folder</param>
/// <param name="prNum">number property of pull request</param>
/// <param name="path">the relative path of the file in the repo</param>
/// <param name="isAncestor">if true appends the additional orig extension</param>
/// <returns></returns>
internal static string GetPathInCache(string repofolder, int prNum, string path, bool isAncestor = false)
{
var dir = Path.Combine(repofolder, $"{prNum}", path.ToLocalPath());
if (isAncestor)
{
dir += ".orig";
}
return dir;
}
internal bool FileChangedLocally(string filePath)
{
using (var repo = new Repository(LocalGitDirectory))
{
var fileStatus = repo.RetrieveStatus(filePath);
switch (fileStatus)
{
case FileStatus.NewInIndex:
case FileStatus.ModifiedInIndex:
case FileStatus.RenamedInIndex:
case FileStatus.TypeChangeInIndex:
case FileStatus.NewInWorkdir:
case FileStatus.ModifiedInWorkdir:
case FileStatus.TypeChangeInWorkdir:
case FileStatus.RenamedInWorkdir:
case FileStatus.Conflicted:
return true;
//These are odd in that they shouldn't actually happen
case FileStatus.Nonexistent:
case FileStatus.DeletedFromIndex:
case FileStatus.DeletedFromWorkdir:
return true;
case FileStatus.Unreadable:
case FileStatus.Ignored:
case FileStatus.Unaltered:
return false;
default:
throw new NotImplementedException($"{fileStatus}");
}
}
}
internal async Task<IList<T>> GetPaginatedListAsync<T>(string url, Ref<string> etag = null)
{
var pagination = Ref.Create<string>(null);
var first = await HttpGetAsync<IList<T>>(url, etag, pagination);
if (first == null) //Etag
{
return null;
}
var list = new List<T>(first);
while (pagination.Value != null)
{
var next = await HttpGetAsync<IList<T>>(pagination.Value, pages: pagination);
list.AddRange(next);
}
return list;
}
/// <summary>
/// Make a request to GitHub with necessary checks, then parse the result into the specified type
/// </summary>
/// <param name="url">relative url to the requested resource</param>
/// <param name="etag">
/// An optional special object that contains a string that can be changed, if the parameter
/// is present and the string inside is not null it will be placed in the IfNotModified
/// HttpHeader otherwise if it is present but the string inside is null then any Etag found
/// on the response header will be set in the object
/// </param>
/// <param name="pages">
/// if not null and the response had a link to a next page the value inside will be set to
/// the url of the next page
/// </param>
/// <typeparam name="T">Type the request is expected to contain</typeparam>
/// <returns>
/// A Task that once awaited will result in the pages contents being deserialized into the
/// return object
/// </returns>
internal async Task<T> HttpGetAsync<T>(string url, Ref<string> etag = null, Ref<string> pages = null) where T : class
{
var content = await HttpGetAsync(url, etag, pages);
if (content == null)
return null;
return DeserializeWithErrorHandling<T>(content);
}
internal async Task<string> HttpGetAsync(string url, Ref<string> etag = null, Ref<string> pages = null)
{
//Request, but retry once waiting 5 minutes
Client.DefaultRequestHeaders.IfNoneMatch.Clear();
if (etag?.Value != null)
{
Client.DefaultRequestHeaders.IfNoneMatch.Add(EntityTagHeaderValue.Parse(etag.Value));
}
var response = await Client.GetAsync(url);
IEnumerable<string> headerVal;
if (response.Headers.TryGetValues("X-RateLimit-Limit", out headerVal))
{
RequestsLimit = int.Parse(headerVal.Single());
}
if (response.Headers.TryGetValues("X-RateLimit-Remaining", out headerVal))
{
RequestsRemaining = int.Parse(headerVal.Single());
}
if (!response.IsSuccessStatusCode)
{
switch (response.StatusCode)
{
case HttpStatusCode.Unauthorized:
var unauth = await response.Content.ReadAsStringAsync();
var unauthorizedError = DeserializeWithErrorHandling<GitHubError>(unauth, supress_error: true);
Logger.Error($"{nameof(GitHubAuthenticationFailureException)}: {unauthorizedError?.Message ?? unauth}");
throw new GitHubAuthenticationFailureException(unauthorizedError.Message);
case HttpStatusCode.Forbidden:
var forbid = await response.Content.ReadAsStringAsync();
var forbidError = DeserializeWithErrorHandling<GitHubError>(forbid, supress_error: true);
Logger.Error($"{nameof(GitHubRateLimitExceededException)}: {forbidError?.Message ?? forbid}");
throw new GitHubRateLimitExceededException(RequestsLimit, !string.IsNullOrWhiteSpace(AuthToken));
case HttpStatusCode.NotModified:
//Returns null because we have nothing to update if nothing was modified
return null;
default:
var str = await response.Content.ReadAsStringAsync();
if (str == "Not Found")
throw new GitHubUnknownErrorException("Not Found");
var error = DeserializeWithErrorHandling<GitHubError>(str, supress_error: true);
throw error?.ToException() ?? new GitHubUnknownErrorException(str);
}
}
if (etag != null && response.Headers.TryGetValues("ETag", out headerVal))
{
etag.Value = headerVal.Single();
}
if (pages != null)
{
pages.Value = response.Headers.TryGetValues("Link", out headerVal) ? ParseNextLink(headerVal) : null;
}
return await response.Content.ReadAsStringAsync();
}
private static Repo AddRepo(string repoDir)
{
using (var r = new Repository(repoDir))
{
var matchingUrls = r.Network.Remotes
.Select(remote => _gitHubUrl.Match(remote.Url))
.Where(m => m.Success);
var match = matchingUrls.FirstOrDefault();
if (match == null)
{
Logger.Error(nameof(GitHubUrlNotFoundException));
throw new GitHubUrlNotFoundException(path: repoDir);
}
var url = match.Value.Trim();
var owner = match.Groups[3].Value.Trim();
var name = match.Groups[4].Value.Trim();
if (name.EndsWith(".git"))
{
name = name.Substring(0, name.Length - 4);
}
Logger.Debug($"Repo: Owner='{owner}' Name='{name}' Url='{url}'");
var repo = new Repo(repoDir, owner, name);
repo.GetCurrentSaved();
return repo;
}
}
private static T DeserializeWithErrorHandling<T>(string content, bool supress_error = false)
{
try
{
return JsonConvert.DeserializeObject<T>(content);
}
catch (Exception ex)
{
Logger.Error($"{nameof(GitHubDeserializationException)}: {ex.Message}");
if (!supress_error)
throw new GitHubDeserializationException(ex);
else
return default(T);
}
}
private static string ParseNextLink(IEnumerable<string> links)
{
foreach (var l in links)
{
var match = nextLinkPattern.Match(l);
if (match.Success)
{
return match.Groups[1].Value;
}
}
return null;
}
private void DeletePRsFromDisk(IEnumerable<PullRequest> prs)
{
foreach (var pr in prs)
{
var dir = Path.Combine(CacheDirectory, $"{pr.Number}");
try
{
Directory.Delete(dir, true);
}
catch (Exception ex)
{
Logger.Error($"{ex.GetType().Name}: Couldn't delete {dir} because {ex.Message}");
}
}
}
/// <summary>
/// Object used for parsing that reflects the json of the response from GitHub in an error
/// </summary>
internal class GitHubError
{
[JsonProperty("documentation_url")]
public string DocumentationUrl { get; set; }
public string Message { get; set; }
internal Exception ToException()
{
Logger.Error($"{nameof(GitHubUnknownErrorException)}: {Message}");
return new GitHubUnknownErrorException(
string.IsNullOrWhiteSpace(DocumentationUrl)
? Message
: $"({Message})[{DocumentationUrl}]"
);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using IEnumerable = System.Collections.IEnumerable;
namespace System.Xml.Linq
{
/// <summary>
/// Defines the LINQ to XML extension methods.
/// </summary>
public static class Extensions
{
/// <summary>
/// Returns all of the <see cref="XAttribute"/>s for each <see cref="XElement"/> of
/// this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XAttribute"/> containing the XML
/// Attributes for every <see cref="XElement"/> in the target <see cref="IEnumerable"/>
/// of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XAttribute> Attributes(this IEnumerable<XElement> source)
{
if (source == null) throw new ArgumentNullException("source");
return GetAttributes(source, null);
}
/// <summary>
/// Returns the <see cref="XAttribute"/>s that have a matching <see cref="XName"/>. Each
/// <see cref="XElement"/>'s <see cref="XAttribute"/>s in the target <see cref="IEnumerable"/>
/// of <see cref="XElement"/> are scanned for a matching <see cref="XName"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XAttribute"/> containing the XML
/// Attributes with a matching <see cref="XName"/> for every <see cref="XElement"/> in
/// the target <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XAttribute> Attributes(this IEnumerable<XElement> source, XName name)
{
if (source == null) throw new ArgumentNullException("source");
return name != null ? GetAttributes(source, name) : XAttribute.EmptySequence;
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the ancestors (parent
/// and it's parent up to the root) of each of the <see cref="XElement"/>s in this
/// <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the ancestors (parent
/// and it's parent up to the root) of each of the <see cref="XElement"/>s in this
/// <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XElement> Ancestors<T>(this IEnumerable<T> source) where T : XNode
{
if (source == null) throw new ArgumentNullException("source");
return GetAncestors(source, null, false);
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the ancestors (parent
/// and it's parent up to the root) that have a matching <see cref="XName"/>. This is done for each
/// <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the ancestors (parent
/// and it's parent up to the root) that have a matching <see cref="XName"/>. This is done for each
/// <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XElement> Ancestors<T>(this IEnumerable<T> source, XName name) where T : XNode
{
if (source == null) throw new ArgumentNullException("source");
return name != null ? GetAncestors(source, name, false) : XElement.EmptySequence;
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// <see cref="XElement"/> and it's ancestors (parent and it's parent up to the root).
/// This is done for each <see cref="XElement"/> in this <see cref="IEnumerable"/> of
/// <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// <see cref="XElement"/> and it's ancestors (parent and it's parent up to the root).
/// This is done for each <see cref="XElement"/> in this <see cref="IEnumerable"/> of
/// <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XElement> AncestorsAndSelf(this IEnumerable<XElement> source)
{
if (source == null) throw new ArgumentNullException("source");
return GetAncestors(source, null, true);
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// <see cref="XElement"/> and it's ancestors (parent and it's parent up to the root)
/// that match the passed in <see cref="XName"/>. This is done for each
/// <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// <see cref="XElement"/> and it's ancestors (parent and it's parent up to the root)
/// that match the passed in <see cref="XName"/>. This is done for each
/// <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XElement> AncestorsAndSelf(this IEnumerable<XElement> source, XName name)
{
if (source == null) throw new ArgumentNullException("source");
return name != null ? GetAncestors(source, name, true) : XElement.EmptySequence;
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XNode"/> over the content of a set of nodes
/// </summary>
public static IEnumerable<XNode> Nodes<T>(this IEnumerable<T> source) where T : XContainer
{
if (source == null) throw new ArgumentNullException("source");
return NodesIterator(source);
}
private static IEnumerable<XNode> NodesIterator<T>(IEnumerable<T> source) where T : XContainer
{
foreach (XContainer root in source)
{
if (root != null)
{
XNode n = root.LastNode;
if (n != null)
{
do
{
n = n.next;
yield return n;
} while (n.parent == root && n != root.content);
}
}
}
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XNode"/> over the descendants of a set of nodes
/// </summary>
public static IEnumerable<XNode> DescendantNodes<T>(this IEnumerable<T> source) where T : XContainer
{
if (source == null) throw new ArgumentNullException("source");
return GetDescendantNodes(source, false);
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the descendants (children
/// and their children down to the leaf level). This is done for each <see cref="XElement"/> in
/// this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the descendants (children
/// and their children down to the leaf level). This is done for each <see cref="XElement"/> in
/// this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XElement> Descendants<T>(this IEnumerable<T> source) where T : XContainer
{
if (source == null) throw new ArgumentNullException("source");
return GetDescendants(source, null, false);
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the descendants (children
/// and their children down to the leaf level) that have a matching <see cref="XName"/>. This is done
/// for each <see cref="XElement"/> in the target <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the descendants (children
/// and their children down to the leaf level) that have a matching <see cref="XName"/>. This is done
/// for each <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XElement> Descendants<T>(this IEnumerable<T> source, XName name) where T : XContainer
{
if (source == null) throw new ArgumentNullException("source");
return name != null ? GetDescendants(source, name, false) : XElement.EmptySequence;
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// <see cref="XElement"/> and it's descendants
/// that match the passed in <see cref="XName"/>. This is done for each
/// <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// <see cref="XElement"/> and descendants.
/// This is done for each
/// <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XNode> DescendantNodesAndSelf(this IEnumerable<XElement> source)
{
if (source == null) throw new ArgumentNullException("source");
return GetDescendantNodes(source, true);
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// <see cref="XElement"/> and it's descendants (children and children's children down
/// to the leaf nodes). This is done for each <see cref="XElement"/> in this <see cref="IEnumerable"/>
/// of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// <see cref="XElement"/> and it's descendants (children and children's children down
/// to the leaf nodes). This is done for each <see cref="XElement"/> in this <see cref="IEnumerable"/>
/// of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XElement> DescendantsAndSelf(this IEnumerable<XElement> source)
{
if (source == null) throw new ArgumentNullException("source");
return GetDescendants(source, null, true);
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// <see cref="XElement"/> and it's descendants (children and children's children down
/// to the leaf nodes) that match the passed in <see cref="XName"/>. This is done for
/// each <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// <see cref="XElement"/> and it's descendants (children and children's children down
/// to the leaf nodes) that match the passed in <see cref="XName"/>. This is done for
/// each <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XElement> DescendantsAndSelf(this IEnumerable<XElement> source, XName name)
{
if (source == null) throw new ArgumentNullException("source");
return name != null ? GetDescendants(source, name, true) : XElement.EmptySequence;
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the child elements
/// for each <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the child elements
/// for each <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XElement> Elements<T>(this IEnumerable<T> source) where T : XContainer
{
if (source == null) throw new ArgumentNullException("source");
return GetElements(source, null);
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the child elements
/// with a matching for each <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the child elements
/// for each <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </returns>
public static IEnumerable<XElement> Elements<T>(this IEnumerable<T> source, XName name) where T : XContainer
{
if (source == null) throw new ArgumentNullException("source");
return name != null ? GetElements(source, name) : XElement.EmptySequence;
}
/// <summary>
/// Returns an <see cref="IEnumerable"/> of <see cref="XElement"/> containing the child elements
/// with a matching for each <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the child elements
/// for each <see cref="XElement"/> in this <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// in document order
/// </returns>
public static IEnumerable<T> InDocumentOrder<T>(this IEnumerable<T> source) where T : XNode
{
if (source == null) throw new ArgumentNullException("source");
return DocumentOrderIterator<T>(source);
}
private static IEnumerable<T> DocumentOrderIterator<T>(IEnumerable<T> source) where T : XNode
{
int count;
T[] items = EnumerableHelpers.ToArray(source, out count);
if (count > 0)
{
Array.Sort(items, 0, count, XNode.DocumentOrderComparer);
for (int i = 0; i != count; ++i) yield return items[i];
}
}
/// <summary>
/// Removes each <see cref="XAttribute"/> represented in this <see cref="IEnumerable"/> of
/// <see cref="XAttribute"/>. Note that this method uses snapshot semantics (copies the
/// attributes to an array before deleting each).
/// </summary>
public static void Remove(this IEnumerable<XAttribute> source)
{
if (source == null) throw new ArgumentNullException("source");
int count;
XAttribute[] attributes = EnumerableHelpers.ToArray(source, out count);
for (int i = 0; i < count; i++)
{
XAttribute a = attributes[i];
if (a != null) a.Remove();
}
}
/// <summary>
/// Removes each <see cref="XNode"/> represented in this <see cref="IEnumerable"/>
/// T which must be a derived from <see cref="XNode"/>. Note that this method uses snapshot semantics
/// (copies the <see cref="XNode"/>s to an array before deleting each).
/// </summary>
public static void Remove<T>(this IEnumerable<T> source) where T : XNode
{
if (source == null) throw new ArgumentNullException("source");
int count;
T[] nodes = EnumerableHelpers.ToArray(source, out count);
for (int i = 0; i < count; i++)
{
T node = nodes[i];
if (node != null) node.Remove();
}
}
static IEnumerable<XAttribute> GetAttributes(IEnumerable<XElement> source, XName name)
{
foreach (XElement e in source)
{
if (e != null)
{
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (name == null || a.name == name) yield return a;
} while (a.parent == e && a != e.lastAttr);
}
}
}
}
static IEnumerable<XElement> GetAncestors<T>(IEnumerable<T> source, XName name, bool self) where T : XNode
{
foreach (XNode node in source)
{
if (node != null)
{
XElement e = (self ? node : node.parent) as XElement;
while (e != null)
{
if (name == null || e.name == name) yield return e;
e = e.parent as XElement;
}
}
}
}
static IEnumerable<XNode> GetDescendantNodes<T>(IEnumerable<T> source, bool self) where T : XContainer
{
foreach (XContainer root in source)
{
if (root != null)
{
if (self) yield return root;
XNode n = root;
while (true)
{
XContainer c = n as XContainer;
XNode first;
if (c != null && (first = c.FirstNode) != null)
{
n = first;
}
else
{
while (n != null && n != root && n == n.parent.content) n = n.parent;
if (n == null || n == root) break;
n = n.next;
}
yield return n;
}
}
}
}
static IEnumerable<XElement> GetDescendants<T>(IEnumerable<T> source, XName name, bool self) where T : XContainer
{
foreach (XContainer root in source)
{
if (root != null)
{
if (self)
{
XElement e = (XElement)root;
if (name == null || e.name == name) yield return e;
}
XNode n = root;
XContainer c = root;
while (true)
{
if (c != null && c.content is XNode)
{
n = ((XNode)c.content).next;
}
else
{
while (n != null && n != root && n == n.parent.content) n = n.parent;
if (n == null || n == root) break;
n = n.next;
}
XElement e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
c = e;
}
}
}
}
static IEnumerable<XElement> GetElements<T>(IEnumerable<T> source, XName name) where T : XContainer
{
foreach (XContainer root in source)
{
if (root != null)
{
XNode n = root.content as XNode;
if (n != null)
{
do
{
n = n.next;
XElement e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
} while (n.parent == root && n != root.content);
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace System.Security.Claims
{
/// <summary>
/// Concrete IPrincipal supporting multiple claims-based identities
/// </summary>
public class ClaimsPrincipal : IPrincipal
{
private enum SerializationMask
{
None = 0,
HasIdentities = 1,
UserData = 2
}
private List<ClaimsIdentity> _identities = new List<ClaimsIdentity>();
private byte[] _userSerializationData;
private static Func<IEnumerable<ClaimsIdentity>, ClaimsIdentity> s_identitySelector = SelectPrimaryIdentity;
private static Func<ClaimsPrincipal> s_principalSelector = ClaimsPrincipalSelector;
/// <summary>
/// This method iterates through the collection of ClaimsIdentities and chooses an identity as the primary.
/// </summary>
static ClaimsIdentity SelectPrimaryIdentity(IEnumerable<ClaimsIdentity> identities)
{
if (identities == null)
{
throw new ArgumentNullException("identities");
}
foreach (ClaimsIdentity identity in identities)
{
if (identity != null)
{
return identity;
}
}
return null;
}
public static Func<IEnumerable<ClaimsIdentity>, ClaimsIdentity> PrimaryIdentitySelector
{
get
{
return s_identitySelector;
}
set
{
s_identitySelector = value;
}
}
public static Func<ClaimsPrincipal> ClaimsPrincipalSelector
{
get
{
return s_principalSelector;
}
set
{
s_principalSelector = value;
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>.
/// </summary>
public ClaimsPrincipal()
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>.
/// </summary>
/// <param name="identities"> <see cref="IEnumerable{ClaimsIdentity}"/> the subjects in the principal.</param>
/// <exception cref="ArgumentNullException">if 'identities' is null.</exception>
public ClaimsPrincipal(IEnumerable<ClaimsIdentity> identities)
{
if (identities == null)
{
throw new ArgumentNullException("identities");
}
Contract.EndContractBlock();
_identities.AddRange(identities);
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>
/// </summary>
/// <param name="identity"> <see cref="IIdentity"/> representing the subject in the principal. </param>
/// <exception cref="ArgumentNullException">if 'identity' is null.</exception>
public ClaimsPrincipal(IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
Contract.EndContractBlock();
ClaimsIdentity ci = identity as ClaimsIdentity;
if (ci != null)
{
_identities.Add(ci);
}
else
{
_identities.Add(new ClaimsIdentity(identity));
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>
/// </summary>
/// <param name="principal"><see cref="IPrincipal"/> used to form this instance.</param>
/// <exception cref="ArgumentNullException">if 'principal' is null.</exception>
public ClaimsPrincipal(IPrincipal principal)
{
if (null == principal)
{
throw new ArgumentNullException("principal");
}
Contract.EndContractBlock();
//
// If IPrincipal is a ClaimsPrincipal add all of the identities
// If IPrincipal is not a ClaimsPrincipal, create a new identity from IPrincipal.Identity
//
ClaimsPrincipal cp = principal as ClaimsPrincipal;
if (null == cp)
{
_identities.Add(new ClaimsIdentity(principal.Identity));
}
else
{
if (null != cp.Identities)
{
_identities.AddRange(cp.Identities);
}
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/> using a <see cref="BinaryReader"/>.
/// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsPrincipal"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
public ClaimsPrincipal(BinaryReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
Initialize(reader);
}
/// <summary>
/// Adds a single <see cref="ClaimsIdentity"/> to an internal list.
/// </summary>
/// <param name="identity">the <see cref="ClaimsIdentity"/>add.</param>
/// <exception cref="ArgumentNullException">if 'identity' is null.</exception>
public virtual void AddIdentity(ClaimsIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
Contract.EndContractBlock();
_identities.Add(identity);
}
/// <summary>
/// Adds a <see cref="IEnumerable{ClaimsIdentity}"/> to the internal list.
/// </summary>
/// <param name="identities">Enumeration of ClaimsIdentities to add.</param>
/// <exception cref="ArgumentNullException">if 'identities' is null.</exception>
public virtual void AddIdentities(IEnumerable<ClaimsIdentity> identities)
{
if (identities == null)
{
throw new ArgumentNullException("identities");
}
Contract.EndContractBlock();
_identities.AddRange(identities);
}
/// <summary>
/// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsPrincipal"/> by enumerating all <see cref="ClaimsIdentities"/>.
/// </summary>
public virtual IEnumerable<Claim> Claims
{
get
{
foreach (ClaimsIdentity identity in Identities)
{
foreach (Claim claim in identity.Claims)
{
yield return claim;
}
}
}
}
/// <summary>
/// Contains any additional data provided by derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>.</param>
/// </summary>
protected virtual byte[] CustomSerializationData
{
get
{
return _userSerializationData;
}
}
/// <summary>
/// Creates a new instance of <see cref="ClaimsPrincipal"/> with values copied from this object.
/// </summary>
public virtual ClaimsPrincipal Clone()
{
return new ClaimsPrincipal(this);
}
/// <summary>
/// Provides and extensibility point for derived types to create a custom <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="reader">the <see cref="BinaryReader"/>that points at the claim.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
/// <returns>a new <see cref="ClaimsIdentity"/>.</returns>
protected virtual ClaimsIdentity CreateClaimsIdentity(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
return new ClaimsIdentity(reader);
}
/// <summary>
/// Returns the Current Principal by calling a delegate. Users may specify the delegate.
/// </summary>
public static ClaimsPrincipal Current
{
// just accesses the current selected principal selector, doesn't set
get
{
if (s_principalSelector != null)
{
return s_principalSelector();
}
return null;
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <param name="match"/>.
/// </summary>
/// <param name="match">The predicate that performs the matching logic.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindAll"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
Contract.EndContractBlock();
foreach (ClaimsIdentity identity in Identities)
{
if (identity != null)
{
foreach (Claim claim in identity.FindAll(match))
{
yield return claim;
}
}
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindAll"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual IEnumerable<Claim> FindAll(string type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
foreach (ClaimsIdentity identity in Identities)
{
if (identity != null)
{
foreach (Claim claim in identity.FindAll(type))
{
yield return claim;
}
}
}
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> that is matched by <param name="match"/>.
/// </summary>
/// <param name="match">The predicate that performs the matching logic.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindFirst"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual Claim FindFirst(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
Contract.EndContractBlock();
Claim claim = null;
foreach (ClaimsIdentity identity in Identities)
{
if (identity != null)
{
claim = identity.FindFirst(match);
if (claim != null)
{
return claim;
}
}
}
return claim;
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> where the Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindFirst"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual Claim FindFirst(string type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
Claim claim = null;
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
claim = _identities[i].FindFirst(type);
if (claim != null)
{
return claim;
}
}
}
return claim;
}
/// <summary>
/// Determines if a claim is contained within all the ClaimsIdentities in this ClaimPrincipal.
/// </summary>
/// <param name="match">The predicate that performs the matching logic.</param>
/// <returns>true if a claim is found, false otherwise.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.HasClaim"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual bool HasClaim(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
Contract.EndContractBlock();
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
if (_identities[i].HasClaim(match))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Determines if a claim of claimType AND claimValue exists in any of the identities.
/// </summary>
/// <param name="type"> the type of the claim to match.</param>
/// <param name="value"> the value of the claim to match.</param>
/// <returns>true if a claim is matched, false otherwise.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.HasClaim"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception>
public virtual bool HasClaim(string type, string value)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
if (_identities[i].HasClaim(type, value))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Collection of <see cref="ClaimsIdentity" />
/// </summary>
public virtual IEnumerable<ClaimsIdentity> Identities
{
get
{
return _identities;
}
}
/// <summary>
/// Gets the identity of the current principal.
/// </summary>
public virtual System.Security.Principal.IIdentity Identity
{
get
{
if (s_identitySelector != null)
{
return s_identitySelector(_identities);
}
else
{
return SelectPrimaryIdentity(_identities);
}
}
}
/// <summary>
/// IsInRole answers the question: does an identity this principal possesses
/// contain a claim of type RoleClaimType where the value is '==' to the role.
/// </summary>
/// <param name="role">The role to check for.</param>
/// <returns>'True' if a claim is found. Otherwise 'False'.</returns>
/// <remarks>Each Identity has its own definition of the ClaimType that represents a role.</remarks>
public virtual bool IsInRole(string role)
{
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
if (_identities[i].HasClaim(_identities[i].RoleClaimType, role))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Initializes from a <see cref="BinaryReader"/>. Normally the reader is initialized with the results from <see cref="WriteTo(BinaryWriter)"/>
/// Normally the <see cref="BinaryReader"/> is initialized in the same way as the <see cref="BinaryWriter"/> passed to <see cref="WriteTo(BinaryWriter)"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsPrincipal"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
private void Initialize(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
SerializationMask mask = (SerializationMask)reader.ReadInt32();
int numPropertiesToRead = reader.ReadInt32();
int numPropertiesRead = 0;
if ((mask & SerializationMask.HasIdentities) == SerializationMask.HasIdentities)
{
numPropertiesRead++;
int numberOfIdentities = reader.ReadInt32();
for (int index = 0; index < numberOfIdentities; ++index)
{
// directly add to _identities as that is what we serialized from
_identities.Add(CreateClaimsIdentity(reader));
}
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
// TODO - brentschmaltz - maximum size ??
int cb = reader.ReadInt32();
_userSerializationData = reader.ReadBytes(cb);
numPropertiesRead++;
}
for (int i = numPropertiesRead; i < numPropertiesToRead; i++)
{
reader.ReadString();
}
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
public virtual void WriteTo(BinaryWriter writer)
{
WriteTo(writer, null);
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <param name="userData">additional data provided by derived type.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
protected virtual void WriteTo(BinaryWriter writer, byte[] userData)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
int numberOfPropertiesWritten = 0;
var mask = SerializationMask.None;
if (_identities.Count > 0)
{
mask |= SerializationMask.HasIdentities;
numberOfPropertiesWritten++;
}
if (userData != null && userData.Length > 0)
{
numberOfPropertiesWritten++;
mask |= SerializationMask.UserData;
}
writer.Write((Int32)mask);
writer.Write((Int32)numberOfPropertiesWritten);
if ((mask & SerializationMask.HasIdentities) == SerializationMask.HasIdentities)
{
writer.Write(_identities.Count);
foreach (var identity in _identities)
{
identity.WriteTo(writer);
}
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
writer.Write((Int32)userData.Length);
writer.Write(userData);
}
writer.Flush();
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Threading.Tasks.Dataflow.Tests
{
public class BroadcastBlockTests
{
[Fact]
public void TestCtor()
{
var blocks = new[] {
new BroadcastBlock<int>(i => i),
new BroadcastBlock<int>(null),
new BroadcastBlock<int>(i => i, new DataflowBlockOptions { MaxMessagesPerTask = 1 }),
new BroadcastBlock<int>(null, new DataflowBlockOptions { MaxMessagesPerTask = 1 }),
new BroadcastBlock<int>(i => i, new DataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = new CancellationToken(true) }),
new BroadcastBlock<int>(null, new DataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = new CancellationToken(true) })
};
foreach (var block in blocks)
{
Assert.NotNull(block.Completion);
int item;
Assert.False(block.TryReceive(out item));
}
}
[Fact]
public void TestArgumentExceptions()
{
Assert.Throws<ArgumentNullException>(() => new BroadcastBlock<int>(i => i, null));
AssertExtensions.Throws<ArgumentException>("messageHeader", () =>
((ITargetBlock<int>)new BroadcastBlock<int>(null)).OfferMessage(default(DataflowMessageHeader), 0, null, consumeToAccept: false));
AssertExtensions.Throws<ArgumentException>("consumeToAccept", () =>
((ITargetBlock<int>)new BroadcastBlock<int>(null)).OfferMessage(new DataflowMessageHeader(1), 0, null, consumeToAccept: true));
DataflowTestHelpers.TestArgumentsExceptions(new BroadcastBlock<int>(i => i));
}
[Fact]
public void TestToString()
{
DataflowTestHelpers.TestToString(
nameFormat => nameFormat != null ?
new BroadcastBlock<int>(i => i, new DataflowBlockOptions() { NameFormat = nameFormat }) :
new BroadcastBlock<int>(i => i));
}
[Fact]
public async Task TestPost()
{
var bb = new BroadcastBlock<int>(i => i);
Assert.True(bb.Post(1));
bb.Complete();
Assert.False(bb.Post(2));
await bb.Completion;
}
[Fact]
public async Task TestCompletionTask()
{
await DataflowTestHelpers.TestCompletionTask(() => new WriteOnceBlock<int>(i => i));
}
[Fact]
public async Task TestReceiveThenPost()
{
var bb = new BroadcastBlock<int>(null);
var ignored = Task.Run(() => bb.Post(42));
Assert.Equal(expected: 42, actual: await bb.ReceiveAsync()); // this should always pass, but due to race we may not test what we're hoping to
bb = new BroadcastBlock<int>(null);
Task<int> t = bb.ReceiveAsync();
Assert.False(t.IsCompleted);
bb.Post(16);
Assert.Equal(expected: 16, actual: await t);
}
[Fact]
public async Task TestBroadcasting()
{
var bb = new BroadcastBlock<int>(i => i + 1);
var targets = Enumerable.Range(0, 3).Select(_ => new TransformBlock<int, int>(i => i)).ToArray();
foreach (var target in targets)
{
bb.LinkTo(target);
}
const int Messages = 3;
bb.PostRange(0, Messages);
for (int i = 0; i < Messages; i++)
{
foreach (var target in targets)
{
Assert.Equal(expected: i + 1, actual: await target.ReceiveAsync());
}
}
}
[Fact]
public async Task TestRepeatedReceives()
{
var bb = new BroadcastBlock<int>(null);
bb.Post(42);
Assert.Equal(expected: 42, actual: await bb.ReceiveAsync());
for (int i = 0; i < 3; i++)
{
int item;
Assert.True(bb.TryReceive(out item));
Assert.Equal(expected: 42, actual: item);
Assert.False(bb.TryReceive(f => f == 41, out item));
Assert.True(bb.TryReceive(f => f == 42, out item));
Assert.Equal(expected: 42, actual: item);
}
}
[Fact]
public async Task TestLinkingAfterCompletion()
{
var b = new BroadcastBlock<int>(i => i * 2);
b.Post(1);
b.Complete();
await b.Completion;
using (b.LinkTo(new ActionBlock<int>(i => { })))
using (b.LinkTo(new ActionBlock<int>(i => { })))
{
Assert.False(b.Post(2));
}
}
[Fact]
public async Task TestLinkingToCompleted()
{
var b = new BroadcastBlock<int>(i => i * 2);
var ab = new ActionBlock<int>(i => { });
b.LinkTo(ab);
ab.Complete();
Assert.True(b.Post(1));
b.Complete();
await b.Completion;
}
[Fact]
public async Task TestCloning()
{
// Test cloning when a clone function is provided
{
int data = 42;
var bb = new BroadcastBlock<int>(x => -x);
Assert.True(bb.Post(data));
for (int i = 0; i < 3; i++)
{
Assert.Equal(expected: -data, actual: await bb.ReceiveAsync());
Assert.Equal(expected: -data, actual: bb.Receive());
Assert.Equal(expected: -data, actual: await bb.ReceiveAsync());
IList<int> items;
Assert.True(((IReceivableSourceBlock<int>)bb).TryReceiveAll(out items));
Assert.Equal(expected: 1, actual: items.Count);
Assert.Equal(expected: -data, actual: items[0]);
}
int result = 0;
var target = new ActionBlock<int>(i => {
Assert.Equal(expected: 0, actual: result);
result = i;
Assert.Equal(expected: -data, actual: i);
});
bb.LinkTo(target, new DataflowLinkOptions { PropagateCompletion = true });
bb.Complete();
await target.Completion;
}
// Test successful processing when no clone function exists
{
var data = new object();
var bb = new BroadcastBlock<object>(null);
Assert.True(bb.Post(data));
object result;
for (int i = 0; i < 3; i++)
{
Assert.Equal(expected: data, actual: await bb.ReceiveAsync());
Assert.Equal(expected: data, actual: bb.Receive());
Assert.Equal(expected: data, actual: await bb.ReceiveAsync());
IList<object> items;
Assert.True(((IReceivableSourceBlock<object>)bb).TryReceiveAll(out items));
Assert.Equal(expected: 1, actual: items.Count);
Assert.Equal(expected: data, actual: items[0]);
}
result = null;
var target = new ActionBlock<object>(o => {
Assert.Null(result);
result = o;
Assert.Equal(expected: data, actual: o);
});
bb.LinkTo(target, new DataflowLinkOptions { PropagateCompletion = true });
bb.Complete();
await target.Completion;
}
}
[Fact]
public async Task TestPrecancellation()
{
var b = new BroadcastBlock<int>(null, new DataflowBlockOptions { CancellationToken = new CancellationToken(canceled: true) });
Assert.NotNull(b.LinkTo(DataflowBlock.NullTarget<int>()));
Assert.False(b.Post(42));
Task<bool> t = b.SendAsync(42);
Assert.True(t.IsCompleted);
Assert.False(t.Result);
int ignoredValue;
IList<int> ignoredValues;
Assert.False(b.TryReceive(out ignoredValue));
Assert.False(((IReceivableSourceBlock<int>)b).TryReceiveAll(out ignoredValues));
Assert.NotNull(b.Completion);
b.Complete(); // verify doesn't throw
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => b.Completion);
}
[Fact]
public async Task TestReserveReleaseConsume()
{
var bb = new BroadcastBlock<int>(i => i * 2);
bb.Post(1);
await DataflowTestHelpers.TestReserveAndRelease(bb, reservationIsTargetSpecific: false);
bb = new BroadcastBlock<int>(i => i * 2);
bb.Post(2);
await DataflowTestHelpers.TestReserveAndConsume(bb, reservationIsTargetSpecific: false);
}
[Fact]
public async Task TestBounding()
{
var bb = new BroadcastBlock<int>(null, new DataflowBlockOptions { BoundedCapacity = 1 });
var ab = new ActionBlock<int>(i => { });
bb.LinkTo(ab, new DataflowLinkOptions { PropagateCompletion = true });
Task<bool>[] sends = Enumerable.Range(0, 40).Select(i => bb.SendAsync(i)).ToArray();
bb.Complete();
await Task.WhenAll(sends);
await ab.Completion;
}
[Fact]
public async Task TestFaultingAndCancellation()
{
foreach (bool fault in DataflowTestHelpers.BooleanValues)
{
var cts = new CancellationTokenSource();
var bb = new BroadcastBlock<int>(null, new GroupingDataflowBlockOptions { CancellationToken = cts.Token, BoundedCapacity = 2 });
Task<bool>[] sends = Enumerable.Range(0, 4).Select(i => bb.SendAsync(i)).ToArray();
if (fault)
{
Assert.Throws<ArgumentNullException>(() => ((IDataflowBlock)bb).Fault(null));
((IDataflowBlock)bb).Fault(new InvalidCastException());
await Assert.ThrowsAsync<InvalidCastException>(() => bb.Completion);
}
else
{
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.Completion);
}
await Task.WhenAll(sends);
}
}
[Fact]
public async Task TestFaultyScheduler()
{
var bb = new BroadcastBlock<int>(null, new DataflowBlockOptions {
BoundedCapacity = 1,
TaskScheduler = new DelegateTaskScheduler
{
QueueTaskDelegate = delegate { throw new FormatException(); }
}
});
Task<bool> t1 = bb.SendAsync(1);
Task<bool> t2 = bb.SendAsync(2);
bb.LinkTo(DataflowBlock.NullTarget<int>());
await Assert.ThrowsAsync<TaskSchedulerException>(() => bb.Completion);
Assert.True(await t1);
Assert.False(await t2);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Summary:
// Implements the exhaustive task cancel and wait scenarios.
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics; // for StopWatch
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace System.Threading.Tasks.Tests.CancelWait
{
/// <summary>
/// Test class
/// </summary>
public sealed class TaskCancelWaitTest
{
#region Private Fields
private API _api; // the API_CancelWait to be tested
private WaitBy _waitBy; // the format of Wait
private int _waitTimeout; // the timeout in ms to be waited
private TaskInfo _taskTree; // the _taskTree to track child task cancellation option
private static readonly int s_delatTimeOut = 100;
private bool _taskCompleted; // result to record the Wait(timeout) return value
private AggregateException _caughtException; // exception thrown during wait
private CountdownEvent _countdownEvent; // event to signal the main thread that the whole task tree has been created
#endregion
/// <summary>
/// .ctor
/// </summary>
public TaskCancelWaitTest(TestParameters parameters)
{
_api = parameters.API_CancelWait;
_waitBy = parameters.WaitBy_CancelWait;
_waitTimeout = parameters.WaitTime;
_taskTree = parameters.RootNode;
_countdownEvent = new CountdownEvent(CaluateLeafNodes(_taskTree));
}
#region Helper Methods
/// <summary>
/// The method that performs the tests
/// Depending on the inputs different test code paths will be exercised
/// </summary>
internal void RealRun()
{
TaskScheduler tm = TaskScheduler.Default;
CreateTask(tm, _taskTree);
// wait the whole task tree to be created
_countdownEvent.Wait();
Stopwatch sw = Stopwatch.StartNew();
try
{
switch (_api)
{
case API.Cancel:
_taskTree.CancellationTokenSource.Cancel();
break;
case API.Wait:
switch (_waitBy)
{
case WaitBy.None:
_taskTree.Task.Wait();
_taskCompleted = true;
break;
case WaitBy.Millisecond:
_taskCompleted = _taskTree.Task.Wait(_waitTimeout);
break;
case WaitBy.TimeSpan:
_taskCompleted = _taskTree.Task.Wait(new TimeSpan(0, 0, 0, 0, _waitTimeout));
break;
}
break;
}
}
catch (AggregateException exp)
{
_caughtException = exp.Flatten();
}
finally
{
sw.Stop();
}
if (_waitTimeout != -1)
{
long delta = sw.ElapsedMilliseconds - ((long)_waitTimeout + s_delatTimeOut);
if (delta > 0)
{
Debug.WriteLine("ElapsedMilliseconds way more than requested Timeout.");
Debug.WriteLine("WaitTime= {0} ms, ElapsedTime= {1} ms, Allowed Descrepancy = {2} ms", _waitTimeout, sw.ElapsedMilliseconds, s_delatTimeOut);
Debug.WriteLine("Delta= {0} ms", delta);
}
else
{
var delaytask = Task.Delay((int)Math.Abs(delta)); // give delay to allow Context being collected before verification
delaytask.Wait();
}
}
Verify();
_countdownEvent.Dispose();
}
/// <summary>
/// recursively walk the tree and attach the tasks to the nodes
/// </summary>
private void CreateTask(TaskScheduler tm, TaskInfo treeNode)
{
treeNode.Task = Task.Factory.StartNew(
delegate (object o)
{
TaskInfo current = (TaskInfo)o;
if (current.IsLeaf)
{
if (!_countdownEvent.IsSet)
_countdownEvent.Signal();
}
else
{
// create children tasks
foreach (TaskInfo child in current.Children)
{
if (child.IsRespectParentCancellation)
{
//
// if child to respect parent cancellation we need to wire a linked token
//
child.CancellationToken =
CancellationTokenSource.CreateLinkedTokenSource(treeNode.CancellationToken, child.CancellationToken).Token;
}
CreateTask(tm, child);
}
}
if (current.CancelChildren)
{
try
{
foreach (TaskInfo child in current.Children)
{
child.CancellationTokenSource.Cancel();
}
}
finally
{
// stop the tree creation and let the main thread proceed
if (!_countdownEvent.IsSet)
{
_countdownEvent.Signal(_countdownEvent.CurrentCount);
}
}
}
// run the workload
current.RunWorkload();
}, treeNode, treeNode.CancellationToken, treeNode.Option, tm);
}
/// <summary>
/// Walk the tree and calculates the tree nodes count
/// </summary>
/// <param name="tree"></param>
private int CaluateLeafNodes(TaskInfo tree)
{
if (tree.IsLeaf)
return 1;
int sum = 0;
foreach (TaskInfo child in tree.Children)
sum += CaluateLeafNodes(child);
return sum;
}
/// <summary>
/// Verification method
/// </summary>
private void Verify()
{
switch (_api)
{
//root task had the token source cancelled
case API.Cancel:
_taskTree.Traversal(current =>
{
if (current.Task == null)
return;
VerifyCancel(current);
VerifyResult(current);
});
break;
//root task was calling wait
case API.Wait:
//will be true if the root cancelled itself - through its workload
if (_taskTree.CancellationToken.IsCancellationRequested)
{
_taskTree.Traversal(current =>
{
if (current.Task == null)
return;
VerifyTaskCanceledException(current);
});
}
else
{
_taskTree.Traversal(current =>
{
if (current.Task == null)
return;
VerifyWait(current);
VerifyResult(current);
});
}
break;
default:
throw new ArgumentOutOfRangeException(string.Format("unknown API_CancelWait of", _api));
}
}
/// <summary>
/// Cancel Verification
/// </summary>
private void VerifyCancel(TaskInfo current)
{
TaskInfo ti = current;
if (current.Parent == null)
{
if (!ti.CancellationToken.IsCancellationRequested)
Assert.True(false, string.Format("Root task must be cancel-requested"));
else if (_countdownEvent.IsSet && ti.Task.IsCanceled)
Assert.True(false, string.Format("Root task should not be cancelled when the whole tree has been created"));
}
else if (current.Parent.CancelChildren)
{
// need to make sure the parent task at least called .Cancel() on the child
if (!ti.CancellationToken.IsCancellationRequested)
Assert.True(false, string.Format("Task which has been explictly cancel-requested either by parent must have CancellationRequested set as true"));
}
else if (ti.IsRespectParentCancellation)
{
if (ti.CancellationToken.IsCancellationRequested != current.Parent.CancellationToken.IsCancellationRequested)
Assert.True(false, string.Format("Task with RespectParentCancellationcontract is broken"));
}
else
{
if (ti.CancellationToken.IsCancellationRequested || ti.Task.IsCanceled)
Assert.True(false, string.Format("Inner non-directly canceled task which opts out RespectParentCancellationshould not be cancelled"));
}
// verify IsCanceled indicate successfully dequeued based on the observing that
// - Thread is recorded the first thing in the RunWorkload from user delegate
//if (ti.Task.IsCompleted && (ti.Thread == null) != ti.Task.IsCanceled)
// Assert.Fail("IsCanceled contract is broken -- completed task which has the delegate executed can't have IsCanceled return true")
}
/// <summary>
/// Verify the Wait code path
/// </summary>
private void VerifyWait(TaskInfo current)
{
TaskInfo ti = current;
TaskInfo parent = current.Parent;
if (_taskCompleted)
{
if (parent == null)
{
Assert.True(ti.Task.IsCompleted, "Root task must complete");
}
else if (parent != null && parent.Task.IsCompleted)
{
if ((ti.Option & TaskCreationOptions.AttachedToParent) != 0
&& !ti.Task.IsCompleted)
{
Assert.True(false, string.Format("Inner attached task must complete"));
}
}
}
}
private void VerifyTaskCanceledException(TaskInfo current)
{
bool expCaught;
TaskInfo ti = current;
//a task will get into cancelled state only if:
//1.Its token was cancelled before as its action to get invoked
//2.The token was cancelled before the task's action to finish, task observed the cancelled token and threw OCE(token)
if (ti.Task.Status == TaskStatus.Canceled)
{
expCaught = FindException((ex) =>
{
TaskCanceledException expectedExp = ex as TaskCanceledException;
return expectedExp != null && expectedExp.Task == ti.Task;
});
Assert.True(expCaught, "expected TaskCanceledException in Task.Name = Task " + current.Name + " NOT caught");
}
else
{
expCaught = FindException((ex) =>
{
TaskCanceledException expectedExp = ex as TaskCanceledException;
return expectedExp != null && expectedExp.Task == ti.Task;
});
Assert.False(expCaught, "NON-expected TaskCanceledException in Task.Name = Task " + current.Name + " caught");
}
}
private void VerifyResult(TaskInfo current)
{
TaskInfo ti = current;
WorkloadType workType = ti.WorkType;
if (workType == WorkloadType.Exceptional && _api != API.Cancel)
{
bool expCaught = FindException((ex) =>
{
TPLTestException expectedExp = ex as TPLTestException;
return expectedExp != null && expectedExp.FromTaskId == ti.Task.Id;
});
if (!expCaught)
Assert.True(false, string.Format("expected TPLTestException in Task.Name = Task{0} NOT caught", current.Name));
}
else
{
if (ti.Task.Exception != null && _api == API.Wait)
Assert.True(false, string.Format("UNEXPECTED exception in Task.Name = Task{0} caught. Exception: {1}", current.Name, ti.Task.Exception));
if (ti.Task.IsCanceled && ti.Result != -42)
{
//this means that the task was not scheduled - it was cancelled or it is still in the queue
//-42 = UNINITIALED_RESULT
Assert.True(false, string.Format("Result must remain uninitialized for unstarted task"));
}
else if (ti.Task.IsCompleted)
{
//Function point comparison cant be done by rounding off to nearest decimal points since
//1.64 could be represented as 1.63999999 or as 1.6499999999. To perform floating point comparisons,
//a range has to be defined and check to ensure that the result obtained is within the specified range
double minLimit = 1.63;
double maxLimit = 1.65;
if (ti.Result < minLimit || ti.Result > maxLimit)
Assert.True(ti.Task.IsCanceled || ti.Task.IsFaulted,
string.Format(
"Expected Result to lie between {0} and {1} for completed task. Actual Result {2}. Using n={3} IsCanceled={4}",
minLimit,
maxLimit,
ti.Result,
workType,
ti.Task.IsCanceled));
}
}
}
/// <summary>
/// Verify the _caughtException against a custom predicate
/// </summary>
private bool FindException(Predicate<Exception> exceptionPred)
{
if (_caughtException == null)
return false; // not caught any exceptions
foreach (Exception ex in _caughtException.InnerExceptions)
{
if (exceptionPred(ex))
return true;
}
return false;
}
#endregion
}
#region Helper Classes / Enums
public class TestParameters
{
public readonly int WaitTime;
public readonly WaitBy WaitBy_CancelWait;
public readonly TaskInfo RootNode;
public readonly API API_CancelWait;
public TestParameters(TaskInfo rootNode, API api_CancelWait, WaitBy waitBy_CancelWait, int waitTime)
{
WaitBy_CancelWait = waitBy_CancelWait;
WaitTime = waitTime;
RootNode = rootNode;
API_CancelWait = api_CancelWait;
}
}
/// <summary>
/// The Tree node Data type
///
/// While the tree is not restricted to this data type
/// the implemented tests are using the TaskInfo_CancelWait data type for their scenarios
/// </summary>
public class TaskInfo
{
private static TaskCreationOptions s_DEFAULT_OPTION = TaskCreationOptions.AttachedToParent;
private static double s_UNINITIALED_RESULT = -42;
public TaskInfo(TaskInfo parent, string TaskInfo_CancelWaitName, WorkloadType workType, string optionsString)
{
Children = new LinkedList<TaskInfo>();
Result = s_UNINITIALED_RESULT;
Option = s_DEFAULT_OPTION;
Name = TaskInfo_CancelWaitName;
WorkType = workType;
Parent = parent;
CancelChildren = false;
CancellationTokenSource = new CancellationTokenSource();
CancellationToken = CancellationTokenSource.Token;
if (string.IsNullOrEmpty(optionsString))
return;
//
// Parse Task CreationOptions, if RespectParentCancellation we would want to acknowledge that
// and passed the remaining options for creation
//
string[] options = optionsString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int index = -1;
for (int i = 0; i < options.Length; i++)
{
string o = options[i].Trim(); // remove any white spaces.
options[i] = o;
if (o.Equals("RespectParentCancellation", StringComparison.OrdinalIgnoreCase))
{
IsRespectParentCancellation = true;
index = i;
}
}
if (index != -1)
{
string[] temp = new string[options.Length - 1];
int excludeIndex = index + 1;
Array.Copy(options, 0, temp, 0, index);
int leftToCopy = options.Length - excludeIndex;
Array.Copy(options, excludeIndex, temp, index, leftToCopy);
options = temp;
}
if (options.Length > 0)
{
TaskCreationOptions parsedOptions;
string joinedOptions = string.Join(",", options);
bool parsed = Enum.TryParse<TaskCreationOptions>(joinedOptions, out parsedOptions);
if (!parsed)
throw new NotSupportedException("could not parse the options string: " + joinedOptions);
Option = parsedOptions;
}
}
public TaskInfo(TaskInfo parent, string TaskInfo_CancelWaitName, WorkloadType workType, string optionsString, bool cancelChildren)
: this(parent, TaskInfo_CancelWaitName, workType, optionsString)
{
CancelChildren = cancelChildren;
}
#region Properties
/// <summary>
/// The task associated with the current node
/// </summary>
public Task Task { get; set; }
/// <summary>
/// LinkedList representing the children of the current node
/// </summary>
public LinkedList<TaskInfo> Children { get; set; }
/// <summary>
/// Bool flag indicating is the current node is a leaf
/// </summary>
public bool IsLeaf
{
get { return Children.Count == 0; }
}
/// <summary>
/// Current node Parent
/// </summary>
public TaskInfo Parent { get; set; }
/// <summary>
/// Current node Name
/// </summary>
public string Name { get; set; }
/// <summary>
/// TaskCreation option of task associated with the current node
/// </summary>
public TaskCreationOptions Option { get; private set; }
/// <summary>
/// WorkloadType_CancelWait of task associated with the current node
/// </summary>
public WorkloadType WorkType { get; private set; }
/// <summary>
/// bool for indicating if the current tasks should initiate its children cancellation
/// </summary>
public bool CancelChildren { get; private set; }
/// <summary>
/// While a tasks is correct execute a result is produced
/// this is the result
/// </summary>
public double Result { get; private set; }
/// <summary>
/// The token associated with the current node's task
/// </summary>
public CancellationToken CancellationToken { get; set; }
/// <summary>
/// Every node has a cancellation source - its token participate in the task creation
/// </summary>
public CancellationTokenSource CancellationTokenSource { get; set; }
/// <summary>
/// bool indicating if the children respect parent cancellation
/// If true - the children cancellation token will be linkewd with the parent cancellation
/// so is the parent will get cancelled the children will get as well
/// </summary>
public bool IsRespectParentCancellation { get; private set; }
#endregion
#region Helper Methods
/// <summary>
/// Recursively traverse the tree and compare the current node usign the predicate
/// </summary>
/// <param name="predicate">the predicate</param>
/// <param name="report"></param>
/// <returns></returns>
public void Traversal(Action<TaskInfo> predicate)
{
// check current data. If it fails check, an exception is thrown and it stops checking.
// check children
foreach (TaskInfo child in Children)
{
predicate(child);
child.Traversal(predicate);
}
}
/// <summary>
/// The Task workload execution
/// </summary>
public void RunWorkload()
{
//Thread = Thread.CurrentThread;
if (WorkType == WorkloadType.Exceptional)
{
ThrowException();
}
else if (WorkType == WorkloadType.Cancelled)
{
CancelSelf(this.CancellationTokenSource, this.CancellationToken);
}
else
{
// run the workload
if (Result == s_UNINITIALED_RESULT)
{
Result = ZetaSequence((int)WorkType);
}
else // task re-entry, mark it failed
{
Result = s_UNINITIALED_RESULT;
}
}
}
public static double ZetaSequence(int n)
{
double result = 0;
for (int i = 1; i < n; i++)
{
result += 1.0 / ((double)i * (double)i);
}
return result;
}
/// <summary>
/// Cancel self workload. The CancellationToken has been wired such that the source passed to this method
/// is a source that can actually causes the Task CancellationToken to be canceled. The source could be the
/// Token's original source, or one of the sources in case of Linked Tokens
/// </summary>
/// <param name="cts"></param>
public static void CancelSelf(CancellationTokenSource cts, CancellationToken ct)
{
cts.Cancel();
throw new OperationCanceledException(ct);
}
public static void ThrowException()
{
throw new TPLTestException();
}
internal void AddChildren(TaskInfo[] children)
{
foreach (var child in children)
Children.AddLast(child);
}
#endregion
}
public enum API
{
Cancel,
Wait,
}
/// <summary>
/// Waiting type
/// </summary>
public enum WaitBy
{
None,
TimeSpan,
Millisecond,
}
/// <summary>
/// Every task has an workload associated
/// These are the workload types used in the task tree
/// The workload is not common for the whole tree - Every node can have its own workload
/// </summary>
public enum WorkloadType
{
Exceptional = -2,
Cancelled = -1,
VeryLight = 1000, // the number is the N input to the ZetaSequence workload
Light = 5000,
Medium = 100000,
Heavy = 500000,
VeryHeavy = 1000000,
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using YALV.Core.Domain;
namespace YALV.Core.Providers
{
public abstract class AbstractEntriesProviderBase : AbstractEntriesProvider
{
public override IEnumerable<LogItem> GetEntries(string dataSource, FilterParams filter)
{
IEnumerable<LogItem> enumerable = this.InternalGetEntries(dataSource, filter);
return enumerable.ToArray(); // avoid file locks
}
private IEnumerable<LogItem> InternalGetEntries(string dataSource, FilterParams filter)
{
using (IDbConnection connection = this.CreateConnection(dataSource))
{
connection.Open();
using (IDbTransaction transaction = connection.BeginTransaction())
{
using (IDbCommand command = connection.CreateCommand())
{
command.CommandText =
@"select caller, date, level, logger, thread, message, exception from log where date >= @date";
IDbDataParameter parameter = command.CreateParameter();
parameter.ParameterName = "@date";
parameter.Value = filter.Date.HasValue ? filter.Date.Value : MinDateTime;
command.Parameters.Add(parameter);
switch (filter.Level)
{
case 1:
AddLevelClause(command, "ERROR");
break;
case 2:
AddLevelClause(command, "INFO");
break;
case 3:
AddLevelClause(command, "DEBUG");
break;
case 4:
AddLevelClause(command, "WARN");
break;
case 5:
AddLevelClause(command, "FATAL");
break;
default:
break;
}
AddLoggerClause(command, filter.Logger);
AddThreadClause(command, filter.Thread);
AddMessageClause(command, filter.Message);
AddOrderByClause(command);
using (IDataReader reader = command.ExecuteReader())
{
int index = 0;
while (reader.Read())
{
string caller = reader.GetString(0);
string[] split = caller.Split(',');
const string machineKey = "{log4jmachinename=";
string item0 = Find(split, machineKey);
string machineName = GetValue(item0, machineKey);
const string hostKey = " log4net:HostName=";
string item1 = Find(split, hostKey);
string hostName = GetValue(item1, hostKey);
const string userKey = " log4net:UserName=";
string item2 = Find(split, userKey);
string userName = GetValue(item2, userKey);
const string appKey = " log4japp=";
string item3 = Find(split, appKey);
string app = GetValue(item3, appKey);
DateTime timeStamp = reader.GetDateTime(1);
string level = reader.GetString(2);
string logger = reader.GetString(3);
string thread = reader.GetString(4);
string message = reader.GetString(5);
string exception = reader.GetString(6);
LogItem entry = new LogItem
{
Id = ++index,
TimeStamp = timeStamp,
Level = level,
Thread = thread,
Logger = logger,
Message = message,
Throwable = exception,
MachineName = machineName,
HostName = hostName,
UserName = userName,
App = app,
};
// TODO: altri filtri
yield return entry;
}
}
}
transaction.Commit();
}
}
}
protected abstract IDbConnection CreateConnection(string dataSource);
private static void AddLevelClause(IDbCommand command, string level)
{
if (command == null)
throw new ArgumentNullException("command");
if (String.IsNullOrEmpty(level))
throw new ArgumentNullException("level");
command.CommandText += @" and level = @level";
IDbDataParameter parameter = command.CreateParameter();
parameter.ParameterName = "@level";
parameter.Value = level;
command.Parameters.Add(parameter);
}
private static void AddLoggerClause(IDbCommand command, string logger)
{
if (command == null)
throw new ArgumentNullException("command");
if (String.IsNullOrEmpty(logger))
return;
command.CommandText += @" and logger like @logger";
IDbDataParameter parameter = command.CreateParameter();
parameter.ParameterName = "@logger";
parameter.Value = String.Format("%{0}%", logger);
command.Parameters.Add(parameter);
}
private static void AddThreadClause(IDbCommand command, string thread)
{
if (command == null)
throw new ArgumentNullException("command");
if (String.IsNullOrEmpty(thread))
return;
command.CommandText += @" and thread like @thread";
IDbDataParameter parameter = command.CreateParameter();
parameter.ParameterName = "@thread";
parameter.Value = String.Format("%{0}%", thread);
command.Parameters.Add(parameter);
}
private static void AddMessageClause(IDbCommand command, string message)
{
if (command == null)
throw new ArgumentNullException("command");
if (String.IsNullOrEmpty(message))
return;
command.CommandText += @" and message like @message";
IDbDataParameter parameter = command.CreateParameter();
parameter.ParameterName = "@message";
parameter.Value = String.Format("%{0}%", message);
command.Parameters.Add(parameter);
}
private static void AddOrderByClause(IDbCommand command)
{
if (command == null)
throw new ArgumentNullException("command");
command.CommandText += @" order by date ";
}
private static string GetValue(string item, string key)
{
return String.IsNullOrEmpty(item) ? String.Empty : item.Remove(0, key.Length);
}
private static string Find(IEnumerable<string> items, string key)
{
return items.Where(i => i.StartsWith(key)).SingleOrDefault();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="OdbcUtils.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics; // Debug services
using System.Runtime.InteropServices;
using System.Text;
namespace System.Data.Odbc
{
sealed internal class CNativeBuffer : System.Data.ProviderBase.DbBuffer {
internal CNativeBuffer (int initialSize) : base(initialSize) {
}
internal short ShortLength {
get {
return checked((short)Length);
}
}
internal object MarshalToManaged(int offset, ODBC32.SQL_C sqlctype, int cb) {
object value;
switch(sqlctype)
{
case ODBC32.SQL_C.WCHAR:
//Note: We always bind as unicode
if(cb == ODBC32.SQL_NTS) {
value = PtrToStringUni(offset);
break;
}
Debug.Assert((cb > 0), "Character count negative ");
Debug.Assert((Length >= cb), "Native buffer too small ");
cb = Math.Min(cb/2, (Length-2)/2);
value= PtrToStringUni(offset, cb);
break;
case ODBC32.SQL_C.CHAR:
case ODBC32.SQL_C.BINARY:
Debug.Assert((cb > 0), "Character count negative ");
Debug.Assert((Length >= cb), "Native buffer too small ");
cb = Math.Min(cb, Length);
value = ReadBytes(offset, cb);
break;
case ODBC32.SQL_C.SSHORT:
value = ReadInt16(offset);
break;
case ODBC32.SQL_C.SLONG:
value = ReadInt32(offset);
break;
case ODBC32.SQL_C.SBIGINT:
value = ReadInt64(offset);
break;
case ODBC32.SQL_C.BIT:
Byte b = ReadByte(offset);
value = (b != 0x00);
break;
case ODBC32.SQL_C.REAL:
value = ReadSingle(offset);
break;
case ODBC32.SQL_C.DOUBLE:
value = ReadDouble(offset);
break;
case ODBC32.SQL_C.UTINYINT:
value = ReadByte(offset);
break;
case ODBC32.SQL_C.GUID:
value = ReadGuid(offset);
break;
case ODBC32.SQL_C.TYPE_TIMESTAMP:
//So we are mapping this ourselves.
//typedef struct tagTIMESTAMP_STRUCT
//{
// SQLSMALLINT year;
// SQLUSMALLINT month;
// SQLUSMALLINT day;
// SQLUSMALLINT hour;
// SQLUSMALLINT minute;
// SQLUSMALLINT second;
// SQLUINTEGER fraction; (billoniths of a second)
//}
value = ReadDateTime(offset);
break;
// Note: System does not provide a date-only type
case ODBC32.SQL_C.TYPE_DATE:
// typedef struct tagDATE_STRUCT
// {
// SQLSMALLINT year;
// SQLUSMALLINT month;
// SQLUSMALLINT day;
// } DATE_STRUCT;
value = ReadDate(offset);
break;
// Note: System does not provide a date-only type
case ODBC32.SQL_C.TYPE_TIME:
// typedef struct tagTIME_STRUCT
// {
// SQLUSMALLINT hour;
// SQLUSMALLINT minute;
// SQLUSMALLINT second;
// } TIME_STRUCT;
value = ReadTime(offset);
break;
case ODBC32.SQL_C.NUMERIC:
//Note: Unfortunatly the ODBC NUMERIC structure and the URT DECIMAL structure do not
//align, so we can't so do the typical "PtrToStructure" call (below) like other types
//We actually have to go through the pain of pulling our raw bytes and building the decimal
// Marshal.PtrToStructure(buffer, typeof(decimal));
//So we are mapping this ourselves
//typedef struct tagSQL_NUMERIC_STRUCT
//{
// SQLCHAR precision;
// SQLSCHAR scale;
// SQLCHAR sign; /* 1 if positive, 0 if negative */
// SQLCHAR val[SQL_MAX_NUMERIC_LEN];
//} SQL_NUMERIC_STRUCT;
value = ReadNumeric(offset);
break;
default:
Debug.Assert (false, "UnknownSQLCType");
value = null;
break;
};
return value;
}
// if sizeorprecision applies only for wchar and numeric values
// for wchar the a value of null means take the value's size
//
internal void MarshalToNative(int offset, object value, ODBC32.SQL_C sqlctype, int sizeorprecision, int valueOffset) {
switch(sqlctype) {
case ODBC32.SQL_C.WCHAR:
{
//Note: We always bind as unicode
//Note: StructureToPtr fails indicating string it a non-blittable type
//and there is no MarshalStringTo* that moves to an existing buffer,
//they all alloc and return a new one, not at all what we want...
//So we have to copy the raw bytes of the string ourself?!
Char[] rgChars;
int length;
Debug.Assert(value is string || value is char[],"Only string or char[] can be marshaled to WCHAR");
if (value is string) {
length = Math.Max(0, ((string)value).Length - valueOffset);
if ((sizeorprecision > 0) && (sizeorprecision < length)) {
length = sizeorprecision;
}
rgChars = ((string)value).ToCharArray(valueOffset, length);
Debug.Assert(rgChars.Length < (base.Length - valueOffset), "attempting to extend parameter buffer!");
WriteCharArray(offset, rgChars, 0, rgChars.Length);
WriteInt16(offset+(rgChars.Length * 2), 0); // Add the null terminator
}
else {
length = Math.Max(0, ((char[])value).Length - valueOffset);
if ((sizeorprecision > 0) && (sizeorprecision < length)) {
length = sizeorprecision;
}
rgChars = (char[])value;
Debug.Assert(rgChars.Length < (base.Length - valueOffset), "attempting to extend parameter buffer!");
WriteCharArray(offset, rgChars, valueOffset, length);
WriteInt16(offset+(rgChars.Length * 2), 0); // Add the null terminator
}
break;
}
case ODBC32.SQL_C.BINARY:
case ODBC32.SQL_C.CHAR:
{
Byte[] rgBytes = (Byte[])value;
int length = rgBytes.Length;
Debug.Assert ((valueOffset <= length), "Offset out of Range" );
// reduce length by the valueOffset
//
length -= valueOffset;
// reduce length to be no more than size (if size is given)
//
if ((sizeorprecision > 0) && (sizeorprecision < length)) {
length = sizeorprecision;
}
//AdjustSize(rgBytes.Length+1);
//buffer = DangerousAllocateAndGetHandle(); // Realloc may have changed buffer address
Debug.Assert(length < (base.Length - valueOffset), "attempting to extend parameter buffer!");
WriteBytes(offset, rgBytes, valueOffset, length);
break;
}
case ODBC32.SQL_C.UTINYINT:
WriteByte(offset, (Byte)value);
break;
case ODBC32.SQL_C.SSHORT: //Int16
WriteInt16(offset, (Int16)value);
break;
case ODBC32.SQL_C.SLONG: //Int32
WriteInt32(offset, (Int32)value);
break;
case ODBC32.SQL_C.REAL: //float
WriteSingle(offset, (Single)value);
break;
case ODBC32.SQL_C.SBIGINT: //Int64
WriteInt64(offset, (Int64)value);
break;
case ODBC32.SQL_C.DOUBLE: //Double
WriteDouble(offset, (Double)value);
break;
case ODBC32.SQL_C.GUID: //Guid
WriteGuid(offset, (Guid)value);
break;
case ODBC32.SQL_C.BIT:
WriteByte(offset, (Byte)(((bool)value) ? 1 : 0));
break;
case ODBC32.SQL_C.TYPE_TIMESTAMP:
{
//typedef struct tagTIMESTAMP_STRUCT
//{
// SQLSMALLINT year;
// SQLUSMALLINT month;
// SQLUSMALLINT day;
// SQLUSMALLINT hour;
// SQLUSMALLINT minute;
// SQLUSMALLINT second;
// SQLUINTEGER fraction; (billoniths of a second)
//}
//We have to map this ourselves, due to the different structures between
//ODBC TIMESTAMP and URT DateTime, (ie: can't use StructureToPtr)
WriteODBCDateTime(offset, (DateTime)value);
break;
}
// Note: System does not provide a date-only type
case ODBC32.SQL_C.TYPE_DATE:
{
// typedef struct tagDATE_STRUCT
// {
// SQLSMALLINT year;
// SQLUSMALLINT month;
// SQLUSMALLINT day;
// } DATE_STRUCT;
WriteDate(offset, (DateTime)value);
break;
}
// Note: System does not provide a date-only type
case ODBC32.SQL_C.TYPE_TIME:
{
// typedef struct tagTIME_STRUCT
// {
// SQLUSMALLINT hour;
// SQLUSMALLINT minute;
// SQLUSMALLINT second;
// } TIME_STRUCT;
WriteTime(offset, (TimeSpan)value);
break;
}
case ODBC32.SQL_C.NUMERIC:
{
WriteNumeric(offset, (Decimal)value, checked((byte)sizeorprecision));
break;
}
default:
Debug.Assert (false, "UnknownSQLCType");
break;
}
}
internal HandleRef PtrOffset(int offset, int length) {
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// NOTE: You must have called DangerousAddRef before calling this
// method, or you run the risk of allowing Handle Recycling
// to occur!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Validate(offset, length);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
return new HandleRef(this, ptr);
}
internal void WriteODBCDateTime(int offset, DateTime value) {
short[] buffer = new short[6] {
unchecked((short)value.Year),
unchecked((short)value.Month),
unchecked((short)value.Day),
unchecked((short)value.Hour),
unchecked((short)value.Minute),
unchecked((short)value.Second),
};
WriteInt16Array(offset, buffer, 0, 6);
WriteInt32(offset + 12, value.Millisecond*1000000); //fraction
}
}
sealed internal class CStringTokenizer {
readonly StringBuilder _token;
readonly string _sqlstatement;
readonly char _quote; // typically the semicolon '"'
readonly char _escape; // typically the same char as the quote
int _len = 0;
int _idx = 0;
internal CStringTokenizer(string text, char quote, char escape) {
_token = new StringBuilder();
_quote = quote;
_escape = escape;
_sqlstatement = text;
if (text != null) {
int iNul = text.IndexOf('\0');
_len = (0>iNul)?text.Length:iNul;
}
else {
_len = 0;
}
}
internal int CurrentPosition {
get{ return _idx; }
}
// Returns the next token in the statement, advancing the current index to
// the start of the token
internal String NextToken() {
if (_token.Length != 0) { // if we've read a token before
_idx += _token.Length; // proceed the internal marker (_idx) behind the token
_token.Remove(0, _token.Length); // and start over with a fresh token
}
while((_idx < _len) && Char.IsWhiteSpace(_sqlstatement[_idx])) {
// skip whitespace
_idx++;
}
if (_idx == _len) {
// return if string is empty
return String.Empty;
}
int curidx = _idx; // start with internal index at current index
bool endtoken = false; //
// process characters until we reache the end of the token or the end of the string
//
while (!endtoken && curidx < _len) {
if (IsValidNameChar(_sqlstatement[curidx])) {
while ((curidx < _len) && IsValidNameChar(_sqlstatement[curidx])) {
_token.Append(_sqlstatement[curidx]);
curidx++;
}
}
else {
char currentchar = _sqlstatement[curidx];
if (currentchar == '[') {
curidx = GetTokenFromBracket(curidx);
}
else if (' ' != _quote && currentchar == _quote) { // if the ODBC driver does not support quoted identifiers it returns a single blank character
curidx = GetTokenFromQuote(curidx);
}
else {
// Some other marker like , ; ( or )
// could also be * or ?
if (!Char.IsWhiteSpace(currentchar)) {
switch (currentchar) {
case ',':
// commas are not part of a token so we'll only append them if they are at the beginning
if (curidx == _idx)
_token.Append(currentchar);
break;
default:
_token.Append(currentchar);
break;
}
}
endtoken = true;
break;
}
}
}
return (_token.Length > 0) ? _token.ToString() : String.Empty ;
}
private int GetTokenFromBracket(int curidx) {
Debug.Assert((_sqlstatement[curidx] == '['), "GetTokenFromQuote: character at starting position must be same as quotechar");
while (curidx < _len) {
_token.Append(_sqlstatement[curidx]);
curidx++;
if (_sqlstatement[curidx-1] == ']')
break;
}
return curidx;
}
// attempts to complete an encapsulated token (e.g. "scott")
// double quotes are valid part of the token (e.g. "foo""bar")
//
private int GetTokenFromQuote(int curidx) {
Debug.Assert(_quote != ' ', "ODBC driver doesn't support quoted identifiers -- GetTokenFromQuote should not be used in this case");
Debug.Assert((_sqlstatement[curidx] == _quote), "GetTokenFromQuote: character at starting position must be same as quotechar");
int localidx = curidx; // start with local index at current index
while (localidx < _len) { // run to the end of the statement
_token.Append(_sqlstatement[localidx]); // append current character to token
if (_sqlstatement[localidx] == _quote) {
if(localidx > curidx) { // don't care for the first char
if (_sqlstatement[localidx-1] != _escape) { // if it's not escape we look at the following char
if (localidx+1 < _len) { // do not overrun the end of the string
if (_sqlstatement[localidx+1] != _quote) {
return localidx+1; // We've reached the end of the quoted text
}
}
}
}
}
localidx++;
}
return localidx;
}
private bool IsValidNameChar(char ch) {
return (Char.IsLetterOrDigit(ch) ||
(ch == '_') || (ch == '-') ||(ch == '.') ||
(ch == '$') || (ch == '#') || (ch == '@') ||
(ch == '~') || (ch == '`') || (ch == '%') ||
(ch == '^') || (ch == '&') || (ch == '|') ) ;
}
// Searches for the token given, starting from the current position
// If found, positions the currentindex at the
// beginning of the token if found.
internal int FindTokenIndex(String tokenString) {
String nextToken;
while (true) {
nextToken = NextToken();
if ((_idx == _len) || ADP.IsEmpty(nextToken)) { // fxcop
break;
}
if (String.Compare(tokenString, nextToken, StringComparison.OrdinalIgnoreCase) == 0) {
return _idx;
}
}
return -1;
}
// Skips the white space found in the beginning of the string.
internal bool StartsWith(String tokenString) {
int tempidx = 0;
while((tempidx < _len) && Char.IsWhiteSpace(_sqlstatement[tempidx])) {
tempidx++;
}
if ((_len - tempidx) < tokenString.Length) {
return false;
}
if (0 == String.Compare(_sqlstatement, tempidx, tokenString, 0, tokenString.Length, StringComparison.OrdinalIgnoreCase)) {
// Reset current position and token
_idx = 0;
NextToken();
return true;
}
return false;
}
}
}
| |
using System;
using System.Diagnostics;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
namespace Microsoft.Msagl.Routing.Visibility {
/// <summary>
/// calculates the pair of tangent line segments between two convex non-intersecting polygons H and Q
/// we suppose that polygons are clockwise oriented
/// </summary>
internal class TangentPair {
//left tangent means that the polygon lies to the left of the tangent
//right tangent means that the polygon lies to the right of the tangent
//the first element of a couple referse to P and the second to Q
//the left at P and left at Q tangent
Polygon P;
Polygon Q;
internal Tuple<int, int> leftPLeftQ;
//the left at P and right at Q tangent
internal Tuple<int, int> leftPRightQ;
bool lowerBranchOnQ;
//the right at P and left at Q tangent
internal Tuple<int, int> rightPLeftQ;
//the right at P and right at Q tangent
internal Tuple<int, int> rightPRightQ;
bool upperBranchOnP;
internal TangentPair(Polygon polygonP, Polygon polygonQ) {
PPolygon = polygonP;
QPolygon = polygonQ;
}
/*
bool debug {
get { return false; }
}
*/
internal Polygon PPolygon {
// get { return P; }
set { P = value; }
}
internal Polygon QPolygon {
// get { return Q; }
set { Q = value; }
}
bool LeftFromLineOnP(int vertexIndex, Point lineStart, Point lineEnd) {
Point p = P.Pnt(vertexIndex);
if (upperBranchOnP)
return Point.PointToTheLeftOfLineOrOnLine(lineEnd, p, lineStart);
return Point.PointToTheRightOfLineOrOnLine(lineEnd, p, lineStart);
}
bool LeftFromLineOnQ(int vertexIndex, Point lineStart, Point lineEnd) {
Point point = Q.Pnt(vertexIndex);
if (lowerBranchOnQ)
return Point.PointToTheLeftOfLineOrOnLine(lineEnd, point, lineStart);
return Point.PointToTheRightOfLineOrOnLine(lineEnd, point, lineStart);
}
int PrevOnP(int i) {
if (upperBranchOnP)
return P.Prev(i);
return P.Next(i);
}
int PrevOnQ(int i) {
if (lowerBranchOnQ)
return Q.Prev(i);
return Q.Next(i);
}
int NextOnP(int i) {
if (upperBranchOnP)
return P.Next(i);
return P.Prev(i);
}
int NextOnQ(int i) {
if (lowerBranchOnQ)
return Q.Next(i);
return Q.Prev(i);
}
int MedianOnP(int i, int j) {
if (upperBranchOnP)
return P.Median(i, j);
return P.Median(j, i);
}
int MedianOnQ(int i, int j) {
if (lowerBranchOnQ)
return Q.Median(i, j);
return Q.Median(j, i);
}
//internal LineSegment ls(Tuple<int, int> tangent) {
// return new LineSegment(P.Pnt(tangent.First), Q.Pnt(tangent.Second));
//}
//internal LineSegment ls(int a, int b) {
// return new LineSegment(P.Pnt(a), Q.Pnt(b));
//}
int ModuleP(int p0, int p1) {
if (upperBranchOnP)
return P.Module(p1 - p0);
return P.Module(p0 - p1);
}
int ModuleQ(int q0, int q1) {
if (lowerBranchOnQ)
return Q.Module(q1 - q0);
return Q.Module(q0 - q1);
}
/// <summary>
/// we pretend here that the branches go clockwise from p0 to p1, and from q0 to q1
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="q0"></param>
/// <param name="q1"></param>
/// <returns></returns>
Tuple<int, int> TangentBetweenBranches(int p0, int p1, int q0, int q1) {
while (p1 != p0 || q1 != q0) {
int mp = p1 != p0 ? MedianOnP(p0, p1) : p0;
int mq = q1 != q0 ? MedianOnQ(q0, q1) : q0;
Point mpp = P.Pnt(mp);
Point mqp = Q.Pnt(mq);
//SugiyamaLayoutSettings.Show(P.Polyline, ls(mp, mq), ls(p1,q0), ls(p0,q1), Q.Polyline);
bool moveOnP = true;
if (ModuleP(p0, p1) > 1) {
if (LeftFromLineOnP(NextOnP(mp), mpp, mqp)) //try to move p0 clockwise
p0 = mp;
else if (LeftFromLineOnP(PrevOnP(mp), mpp, mqp)) //try to move p1 counterclockwise
p1 = mp;
else
moveOnP = false;
} else if (p1 != p0) {
//we have only two point in the branch
//try to move p0 clockwise
if (LeftFromLineOnP(p1, P.Pnt(p0), mqp))
p0 = p1;
else if (LeftFromLineOnP(p0, P.Pnt(p1), mqp)) //try to move p1 counterclockwise
p1 = p0;
else
moveOnP = false;
} else
moveOnP = false;
bool moveOnQ = true;
if (ModuleQ(q0, q1) > 1) {
if (LeftFromLineOnQ(NextOnQ(mq), mqp, mpp)) //try to move q0 clockwise
q0 = mq;
else if (LeftFromLineOnQ(PrevOnQ(mq), mqp, mpp)) //try to move q1 counterclockwise
q1 = mq;
else
moveOnQ = false;
} else if (q1 != q0) {
//we have only two points in the branch
if (LeftFromLineOnQ(q1, Q.Pnt(q0), mpp)) //try to move q0 clockwise
q0 = q1;
else if (LeftFromLineOnQ(q0, Q.Pnt(q1), mpp)) //try to move q1 counterclockwise
q1 = q0;
else
moveOnQ = false;
} else
moveOnQ = false;
if (!moveOnP && !moveOnQ) {
p1 = p0 = mp;
q1 = q0 = mq;
}
}
return new Tuple<int, int>(p0, q1);
}
/// <summary>
/// following the paper of Edelsbrunner
/// </summary>
/// <param name="bisectorPivot"></param>
/// <param name="bisectorRay"></param>
/// <param name="p1">the closest feature start</param>
/// <param name="p2">the closest feature end</param>
/// <param name="q1">the closest feature end</param>
/// <param name="q2">the closest feature start</param>
internal void FindDividingBisector(out Point bisectorPivot, out Point bisectorRay,
out int p1, out int p2, out int q1, out int q2) {
Point pClosest;
Point qClosest;
FindClosestFeatures(out p1, out p2, out q1, out q2, out pClosest, out qClosest);
bisectorPivot = (pClosest + qClosest)/2;
bisectorRay = (pClosest - qClosest).Rotate(Math.PI/2);
// int p=P.FindTheFurthestVertexFromBisector(
#if TEST_MSAGL
//if (!ApproximateComparer.Close(pClosest, qClosest))
// SugiyamaLayoutSettings.Show(this.P.Polyline, this.Q.Polyline, new LineSegment(pClosest, qClosest));
#endif
}
internal void FindClosestPoints(out Point pClosest, out Point qClosest) {
int p1, p2, q1, q2;
FindClosestFeatures(out p1, out p2, out q1, out q2, out pClosest, out qClosest);
}
void FindClosestFeatures(out int p1, out int p2, out int q1, out int q2, out Point pClosest, out Point qClosest) {
P.GetTangentPoints(out p2, out p1, Q[0].Point);
// LayoutAlgorithmSettings.ShowDebugCurves(new DebugCurve(P.Polyline), new DebugCurve(Q.Polyline), new DebugCurve("red",Ls(p2, 0)), new DebugCurve("blue",Ls(p1, 0)));
if (p2 == p1)
p2 += P.Count;
Q.GetTangentPoints(out q1, out q2, P[0].Point);
//LayoutAlgorithmSettings.Show(P.Polyline, Q.Polyline, Ls(0, q1), Ls(0, q2));
if (q2 == q1)
q1 += Q.Count;
// LayoutAlgorithmSettings.ShowDebugCurves(new DebugCurve(100,0.1,"black",P.Polyline),new DebugCurve(100,0.1,"black",Q.Polyline),new DebugCurve(100,0.1,"red",new LineSegment(P [p1].Point,Q [q1].Point)),new DebugCurve(100,0.1,"blue",new LineSegment(P [p2].Point,Q [q2].Point)));
FindClosestPoints(ref p1, ref p2, ref q2, ref q1, out pClosest, out qClosest);
}
/*
ICurve Ls(int p0, int p1) {
return new LineSegment(P[p0].Point, Q[p1].Point);
}
*/
//chunks go clockwise from p1 to p2 and from q2 to q1
void FindClosestPoints(ref int p1, ref int p2, ref int q2, ref int q1, out Point pClosest, out Point qClosest) {
while (ChunksAreLong(p2, p1, q2, q1))
ShrinkChunks(ref p2, ref p1, ref q2, ref q1);
if (p1 == p2) {
pClosest = P[p2].Point;
if (q1 == q2)
qClosest = Q[q1].Point;
else {
// if(debug) LayoutAlgorithmSettings.Show(new LineSegment(P.Pnt(p2), Q.Pnt(q2)), new LineSegment(P.Pnt(p1), Q.Pnt(q1)), P.Polyline, Q.Polyline);
qClosest = Point.ClosestPointAtLineSegment(pClosest, Q[q1].Point, Q[q2].Point);
if (ApproximateComparer.Close(qClosest, Q.Pnt(q1)))
q2 = q1;
else if (ApproximateComparer.Close(qClosest, Q.Pnt(q2)))
q1 = q2;
}
} else {
Debug.Assert(q1 == q2);
qClosest = Q[q1].Point;
pClosest = Point.ClosestPointAtLineSegment(qClosest, P[p1].Point, P[p2].Point);
if (ApproximateComparer.Close(pClosest, P.Pnt(p1)))
p2 = p1;
else if (ApproximateComparer.Close(qClosest, P.Pnt(p2)))
p1 = p2;
}
}
bool ChunksAreLong(int p2, int p1, int q2, int q1) {
int pLength = P.Module(p2 - p1) + 1;
if (pLength > 2)
return true;
int qLength = Q.Module(q1 - q2) + 1;
if (qLength > 2)
return true;
if (pLength == 2 && qLength == 2)
return true;
return false;
}
void ShrinkChunks(ref int p2, ref int p1, ref int q2, ref int q1) {
int mp = p1 == p2 ? p1 : P.Median(p1, p2);
int mq = q1 == q2 ? q1 : Q.Median(q2, q1);
Point mP = P[mp].Point;
Point mQ = Q[mq].Point;
double a1;
double a2;
double b1;
double b2;
GetAnglesAtTheMedian(mp, mq, ref mP, ref mQ, out a1, out a2, out b1, out b2);
// Core.Layout.LayoutAlgorithmSettings.Show(new LineSegment(P.Pnt(p2), Q.Pnt(q2)), new LineSegment(P.Pnt(p1), Q.Pnt(q1)), new LineSegment(P.Pnt(mp),Q.Pnt( mq)), P.Polyline, Q.Polyline);
//if (MovingAlongHiddenSide(ref p1, ref p2, ref q1, ref q2, mp, mq, a1, a2, b1, b2)) {
// // SugiyamaLayoutSettings.Show(ls(p2, q2), ls(p1, q1), ls(mp, mq), P.Polyline, Q.Polyline);
// return;
//}
if (InternalCut(ref p1, ref p2, ref q1, ref q2, mp, mq, a1, a2, b1, b2)) {
// if(debug) LayoutAlgorithmSettings.Show(P.Polyline, Q.Polyline, Ls(p1, q1), Ls(p2,q2));
return;
}
//case 1
if (OneOfChunksContainsOnlyOneVertex(ref p2, ref p1, ref q2, ref q1, mp, mq, a1, b1))
return;
//case 2
if (OnlyOneChunkContainsExactlyTwoVertices(ref p2, ref p1, ref q2, ref q1, mp, mq, a1, b1, a2, b2))
return;
// the case where we have exactly two vertices in each chunk
if (p2 == P.Next(p1) && q1 == Q.Next(q2)) {
double psol, qsol;
LineSegment.MinDistBetweenLineSegments(P.Pnt(p1), P.Pnt(p2), Q.Pnt(q1), Q.Pnt(q2), out psol,
out qsol);
//System.Diagnostics.Debug.Assert(res);
if (psol == 0)
p2 = p1;
else if (psol == 1)
p1 = p2;
else if (qsol == 0)
q2 = q1;
else if (qsol == 1)
q1 = q2;
Debug.Assert(p1 == p2 || q1 == q2);
return;
////we have trapeze {p1,p2,q2,q1} here
////let p1,p2 be the low base of the trapes
////where is the closest vertex , on the left side or on the rigth side?
//if (Point.Angle(P.Pnt(p2), P.Pnt(p1), Q.Pnt(q1)) + Point.Angle(P.Pnt(p1), Q.Pnt(q1), Q.Pnt(q2)) >= Math.PI)
// ProcessLeftSideOfTrapez(ref p1, ref p2, ref q2, ref q1);
//else {
// SwapPQ();
// ProcessLeftSideOfTrapez(ref q2, ref q1, ref p1, ref p2);
// SwapPQ();
//}
//return;
}
//case 3
if (a1 <= Math.PI && a2 <= Math.PI && b1 <= Math.PI && b2 <= Math.PI) {
if (a1 + b1 > Math.PI) {
if (a1 >= Math.PI/2)
p1 = mp;
else
q1 = mq;
} else {
Debug.Assert(a2 + b2 >= Math.PI-ApproximateComparer.Tolerance);
if (a2 >= Math.PI/2)
p2 = mp;
else
q2 = mq;
}
} else {
if (a1 > Math.PI)
p1 = mp;
else if (a2 > Math.PI)
p2 = mp;
else if (b1 > Math.PI)
q1 = mq;
else {
Debug.Assert(b2 > Math.PI);
q2 = mq;
}
}
}
bool InternalCut(ref int p1, ref int p2, ref int q1, ref int q2, int mp, int mq, double a1, double a2, double b1,
double b2) {
bool ret = false;
if (a1 >= Math.PI && a2 >= Math.PI) {
//Find out who is on the same side from [mq,mp] as Q[0], the next or the prev. Remember that we found the first chunk from Q[0]
//System.Diagnostics.Debug.WriteLine("cutting P");
// if(debug) LayoutAlgorithmSettings.Show(P.Polyline, Q.Polyline, Ls(p1, q1), Ls(p2, q2), Ls(mp, mq));
Point mpp = P[mp].Point;
Point mqp = Q[mq].Point;
Point mpnp = P[P.Next(mp)].Point;
TriangleOrientation orientation = Point.GetTriangleOrientation(mpp, mqp, Q[0].Point);
TriangleOrientation nextOrientation = Point.GetTriangleOrientation(mpp, mqp, mpnp);
if (orientation == nextOrientation)
p1 = P.Next(mp);
else
p2 = P.Prev(mp);
ret = true;
}
if (b1 >= Math.PI && b2 >= Math.PI) {
//Find out who is on the same side from [mq,mp] as P[0], the next or the prev. Remember that we found the first chunk from P[0]
//System.Diagnostics.Debug.WriteLine("cutting Q");
// if (debug) LayoutAlgorithmSettings.Show(P.Polyline, Q.Polyline, Ls(p1, q1), Ls(p2, q2), Ls(mp, mq));
Point mpp = P[mp].Point;
Point mqp = Q[mq].Point;
Point mqnp = Q[Q.Next(mq)].Point;
TriangleOrientation orientation = Point.GetTriangleOrientation(mpp, mqp, P[0].Point);
TriangleOrientation nextOrientation = Point.GetTriangleOrientation(mpp, mqp, mqnp);
if (orientation == nextOrientation)
q2 = Q.Next(mq);
else
q1 = Q.Prev(mq);
ret = true;
}
return ret;
}
//private void ProcessLeftSideOfTrapez(ref int p1, ref int p2, ref int q2, ref int q1) {
// //the closest vertex is on the left side
// Point pn1 = P.Pnt(p1); Point pn2 = P.Pnt(p2);
// Point qn1 = Q.Pnt(q1); Point qn2 = Q.Pnt(q2);
// //SugiyamaLayoutSettings.Show(new LineSegment(pn1, pn2), new LineSegment(pn2, qn2), new LineSegment(qn2, qn1), new LineSegment(qn1, pn1));
// double ap1 = Point.Angle(pn2, pn1, qn1);
// double aq1 = Point.Angle(pn1, qn1, qn2);
// System.Diagnostics.Debug.Assert(ap1 + aq1 >= Math.PI);
// //the point is on the left side
// if (ap1 >= Math.PI / 2 && aq1 >= Math.PI / 2) {
// q2 = q1; //the vertices of the left side gives the solution
// p2 = p1;
// } else if (ap1 < Math.PI / 2) {
// q2 = q1;
// if (!Point.CanProject(qn1, pn1, pn2))
// p1 = p2;
// } else { //aq1<Pi/2
// p2 = p1;
// if (!Point.CanProject(pn1, qn1, qn2))
// q1 = q2;
// }
//}
void GetAnglesAtTheMedian(int mp, int mq, ref Point mP, ref Point mQ, out double a1, out double a2,
out double b1, out double b2) {
a1 = Point.Angle(mQ, mP, P.Pnt(P.Prev(mp)));
a2 = Point.Angle(P.Pnt(P.Next(mp)), mP, mQ);
b1 = Point.Angle(Q.Pnt(Q.Next(mq)), mQ, mP);
b2 = Point.Angle(mP, mQ, Q.Pnt(Q.Prev(mq)));
}
/// <summary>
/// we know here that p1!=p2 and q1!=q2
/// </summary>
/// <param name="p2"></param>
/// <param name="p1"></param>
/// <param name="q2"></param>
/// <param name="q1"></param>
/// <param name="mp"></param>
/// <param name="mq"></param>
/// <param name="a1"></param>
/// <param name="b1"></param>
/// <param name="a2"></param>
/// <param name="b2"></param>
/// <returns></returns>
bool OnlyOneChunkContainsExactlyTwoVertices(ref int p2, ref int p1, ref int q2, ref int q1,
int mp, int mq, double a1, double b1, double a2, double b2) {
bool pSideIsShort = p2 == P.Next(p1);
bool qSideIsShort = q1 == Q.Next(q2);
if (pSideIsShort && !qSideIsShort) {
ProcessShortSide(ref p2, ref p1, ref q2, ref q1, mp, mq, a1, b1, a2, b2);
return true;
}
if (qSideIsShort && !pSideIsShort) {
SwapEverything(ref p2, ref p1, ref q2, ref q1, ref mp, ref mq, ref a1, ref b1, ref a2, ref b2);
ProcessShortSide(ref p2, ref p1, ref q2, ref q1, mp, mq, a1, b1, a2, b2);
SwapEverything(ref p2, ref p1, ref q2, ref q1, ref mp, ref mq, ref a1, ref b1, ref a2, ref b2);
return true;
}
return false;
}
void SwapEverything(ref int p2, ref int p1, ref int q2, ref int q1, ref int mp, ref int mq, ref double a1,
ref double b1, ref double a2, ref double b2) {
SwapPq();
Swap(ref q1, ref p2);
Swap(ref q2, ref p1);
Swap(ref mp, ref mq);
Swap(ref b1, ref a2);
Swap(ref a1, ref b2);
}
static void Swap(ref double a1, ref double a2) {
double t = a1;
a1 = a2;
a2 = t;
}
static void Swap(ref int a1, ref int a2) {
int t = a1;
a1 = a2;
a2 = t;
}
void ProcessShortSide(ref int p2, ref int p1, ref int q2, ref int q1, int mp, int mq, double a1, double b1,
double a2, double b2) {
//case 2.1
if (mp == p2)
ProcessSide(ref p2, ref p1, ref q2, ref q1, mq, a1, b1, b2);
else {
if (a2 <= Math.PI) {
if (a2 + b2 >= Math.PI) {
if (a2 >= Math.PI / 2) p2 = p1;
else q2 = mq;
} else {
if (b1 >= Math.PI / 2) q1 = mq;
else if (a2 < b2) {
//SugiyamaLayoutSettings.Show(new LineSegment(P.Pnt(p2), Q.Pnt(q2)), new LineSegment(P.Pnt(p1), Q.Pnt(q1)), new LineSegment(P.Pnt(p1), Q.Pnt(mq)), P.Polyline, Q.Polyline);
if (Point.CanProject(Q.Pnt(mq), P[p1].Point, P[p2].Point)) q1 = mq;
else p1 = p2;
}
}
} else {
//a2>Pi , case 2.2
if (a1 + b1 <= Math.PI)
p1 = p2;
else
p2 = p1;
}
}
}
void SwapPq() {
Polygon t = P;
P = Q;
Q = t;
}
void ProcessSide(ref int p2, ref int p1, ref int q2, ref int q1, int mq, double a1, double b1, double b2) {
//SugiyamaLayoutSettings.Show(new LineSegment(P.Pnt(p2), Q.Pnt(q2)), new LineSegment(P.Pnt(p1), Q.Pnt(q1)),new LineSegment(P.Pnt(p1), Q.Pnt(mq)), P.Polyline, Q.Polyline);
Point mQ = Q.Pnt(mq);
if (a1 <= Math.PI) {
if (a1 + b1 >= Math.PI) {
if (a1 >= Math.PI/2) p1 = p2;
else q1 = mq;
} else if (b2 >= Math.PI/2) q2 = mq;
else if (a1 < b2) {
if (Point.CanProject(mQ, P[p1].Point, P[p2].Point)) q2 = mq;
else p2 = p1;
}
} else {
//a1>Pi , case 2.2
p2 = p1;
if (b1 >= Math.PI)
q1 = mq;
else if (b2 >= Math.PI)
q2 = mq;
}
}
static bool OneOfChunksContainsOnlyOneVertex(ref int p2, ref int p1, ref int q2, ref int q1, int mp, int mq,
double a1, double b1) {
if (p1 == p2) {
if (b1 >= Math.PI/2)
q1 = mq;
else
q2 = mq;
return true;
}
if (q1 == q2) {
if (a1 >= Math.PI/2)
p1 = mp;
else
p2 = mp;
return true;
}
return false;
}
internal void CalculateLeftTangents() {
Point bisectorPivot;
Point bisectorRay;
int p1;
int p2;
int q1;
int q2;
FindDividingBisector(out bisectorPivot, out bisectorRay,
out p1, out p2, out q1, out q2);
int pFurthest = P.FindTheFurthestVertexFromBisector(p1, p2, bisectorPivot, bisectorRay);
int qFurthest = Q.FindTheFurthestVertexFromBisector(q2, q1, bisectorPivot, bisectorRay);
upperBranchOnP = false;
lowerBranchOnQ = true;
leftPLeftQ = TangentBetweenBranches(pFurthest, p1, qFurthest, q1); //we need to take maximally wide branches
lowerBranchOnQ = false;
leftPRightQ = TangentBetweenBranches(pFurthest, p1, qFurthest, q2);
}
//private bool QContains(int x ,int y) {
// foreach (Point p in Q.Polyline) {
// if (p.X == x && p.Y == y)
// return true;
// }
// return false;
//}
//bool PContains(int x, int y) {
// foreach (Point p in P.Polyline) {
// if (p.X == x && p.Y == y)
// return true;
// }
// return false;
//}
internal void CalculateRightTangents() {
Point bisectorPivot;
Point bisectorRay;
int p1;
int p2;
int q1;
int q2;
FindDividingBisector(out bisectorPivot, out bisectorRay, out p1, out p2, out q1, out q2);
int pFurthest = P.FindTheFurthestVertexFromBisector(p1, p2, bisectorPivot, bisectorRay);
int qFurthest = Q.FindTheFurthestVertexFromBisector(q2, q1, bisectorPivot, bisectorRay);
//SugiyamaLayoutSettings.Show(ls(p1, q1), ls(p2, q2), ls(pFurthest, qFurthest), P.Polyline, Q.Polyline);
upperBranchOnP = true;
lowerBranchOnQ = true;
rightPLeftQ = TangentBetweenBranches(pFurthest, p2, qFurthest, q1);
lowerBranchOnQ = false;
rightPRightQ = TangentBetweenBranches(pFurthest, p2, qFurthest, q2);
}
}
}
| |
// Python Tools for Visual Studio
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.PythonTools {
[Export(typeof(ITaggerProvider)), ContentType(PythonCoreConstants.ContentType)]
[TagType(typeof(IOutliningRegionTag))]
class OutliningTaggerProvider : ITaggerProvider {
private readonly PythonToolsService _pyService;
[ImportingConstructor]
public OutliningTaggerProvider([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) {
_pyService = serviceProvider.GetPythonToolsService();
}
#region ITaggerProvider Members
public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag {
return (ITagger<T>)(buffer.GetOutliningTagger() ?? new OutliningTagger(_pyService, buffer));
}
#endregion
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "Object is owned by VS and cannot be disposed")]
internal class OutliningTagger : ITagger<IOutliningRegionTag> {
private readonly ITextBuffer _buffer;
private readonly PythonToolsService _pyService;
private TagSpan[] _tags = Array.Empty<TagSpan>();
private CancellationTokenSource _processing;
private bool _enabled;
private static readonly Regex _openingRegionRegex = new Regex(@"^\s*#\s*region($|\s+.*$)");
private static readonly Regex _closingRegionRegex = new Regex(@"^\s*#\s*endregion($|\s+.*$)");
public OutliningTagger(PythonToolsService pyService, ITextBuffer buffer) {
_pyService = pyService;
_buffer = buffer;
_buffer.Properties[typeof(OutliningTagger)] = this;
_buffer.RegisterForParseTree(OnNewParseTree);
_enabled = _pyService.AdvancedOptions.EnterOutliningModeOnOpen;
}
public bool Enabled {
get {
return _enabled;
}
}
public void Enable() {
_enabled = true;
var snapshot = _buffer.CurrentSnapshot;
var tagsChanged = TagsChanged;
if (tagsChanged != null) {
tagsChanged(this, new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, new Span(0, snapshot.Length))));
}
}
public void Disable() {
_enabled = false;
var snapshot = _buffer.CurrentSnapshot;
var tagsChanged = TagsChanged;
if (tagsChanged != null) {
tagsChanged(this, new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, new Span(0, snapshot.Length))));
}
}
#region ITagger<IOutliningRegionTag> Members
public IEnumerable<ITagSpan<IOutliningRegionTag>> GetTags(NormalizedSnapshotSpanCollection spans) {
return _tags;
}
private async void OnNewParseTree(AnalysisEntry entry) {
var snapshot = _buffer.CurrentSnapshot;
Interlocked.Exchange(ref _processing, null)?.Cancel();
var tags = await entry.Analyzer.GetOutliningTagsAsync(snapshot);
if (tags != null) {
var cts = new CancellationTokenSource();
Interlocked.Exchange(ref _processing, cts)?.Cancel();
try {
_tags = await System.Threading.Tasks.Task.Run(() => tags
.Concat(ProcessRegionTags(snapshot, cts.Token))
.Concat(ProcessCellTags(snapshot, cts.Token))
.ToArray(),
cts.Token
);
} catch (OperationCanceledException) {
return;
}
} else if (_tags != null) {
_tags = Array.Empty<TagSpan>();
} else {
return;
}
TagsChanged?.Invoke(
this,
new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, 0, snapshot.Length))
);
}
internal static IEnumerable<TagSpan> ProcessRegionTags(ITextSnapshot snapshot, CancellationToken cancel) {
Stack<ITextSnapshotLine> regions = new Stack<ITextSnapshotLine>();
// Walk lines and attempt to find '#region'/'#endregion' tags
foreach (var line in snapshot.Lines) {
cancel.ThrowIfCancellationRequested();
var lineText = line.GetText();
if (_openingRegionRegex.IsMatch(lineText)) {
regions.Push(line);
} else if (_closingRegionRegex.IsMatch(lineText) && regions.Count > 0) {
var openLine = regions.Pop();
var outline = GetTagSpan(snapshot, openLine.Start, line.End);
yield return outline;
}
}
}
internal static IEnumerable<TagSpan> ProcessCellTags(ITextSnapshot snapshot, CancellationToken cancel) {
if (snapshot.LineCount == 0) {
yield break;
}
// Walk lines and attempt to find code cell tags
var line = snapshot.GetLineFromLineNumber(0);
int previousCellStart = -1;
while (line != null) {
cancel.ThrowIfCancellationRequested();
var cellStart = CodeCellAnalysis.FindStartOfCell(line);
if (cellStart == null || cellStart.LineNumber == previousCellStart) {
if (line.LineNumber + 1 < snapshot.LineCount) {
line = snapshot.GetLineFromLineNumber(line.LineNumber + 1);
} else {
break;
}
} else {
var cellEnd = CodeCellAnalysis.FindEndOfCell(cellStart, line);
if (cellEnd.LineNumber > cellStart.LineNumber) {
previousCellStart = cellStart.LineNumber;
yield return GetTagSpan(snapshot, cellStart.Start, cellEnd.End);
}
if (cellEnd.LineNumber + 1 < snapshot.LineCount) {
line = snapshot.GetLineFromLineNumber(cellEnd.LineNumber + 1);
} else {
break;
}
}
}
}
internal static TagSpan GetTagSpan(ITextSnapshot snapshot, int start, int end, int headerIndex = -1) {
TagSpan tagSpan = null;
try {
// if the user provided a -1, we should figure out the end of the first line
if (headerIndex < 0) {
headerIndex = snapshot.GetLineFromPosition(start).End.Position;
}
if (start != -1 && end != -1) {
int length = end - headerIndex;
if (length > 0) {
Debug.Assert(start + length <= snapshot.Length, String.Format("{0} + {1} <= {2} end was {3}", start, length, snapshot.Length, end));
var span = GetFinalSpan(
snapshot,
headerIndex,
length
);
tagSpan = new TagSpan(
new SnapshotSpan(snapshot, span),
new OutliningTag(snapshot, span)
);
}
}
} catch (ArgumentException) {
// sometimes Python's parser gives us bad spans, ignore those and fix the parser
Debug.Assert(false, "bad argument when making span/tag");
}
Debug.Assert(tagSpan != null, "failed to create tag span with start={0} and end={0}".FormatUI(start, end));
return tagSpan;
}
private static Span GetFinalSpan(ITextSnapshot snapshot, int start, int length) {
int cnt = 0;
var text = snapshot.GetText(start, length);
// remove up to 2 \r\n's if we just end with these, this will leave a space between the methods
while (length > 0 && ((Char.IsWhiteSpace(text[length - 1])) || ((text[length - 1] == '\r' || text[length - 1] == '\n') && cnt++ < 4))) {
length--;
}
return new Span(start, length);
}
private SnapshotSpan? ShouldInclude(Statement statement, NormalizedSnapshotSpanCollection spans) {
if (spans.Count == 1 && spans[0].Length == spans[0].Snapshot.Length) {
// we're processing the entire snapshot
return spans[0];
}
for (int i = 0; i < spans.Count; i++) {
if (spans[i].IntersectsWith(Span.FromBounds(statement.StartIndex, statement.EndIndex))) {
return spans[i];
}
}
return null;
}
public event EventHandler<SnapshotSpanEventArgs> TagsChanged;
#endregion
}
internal class TagSpan : ITagSpan<IOutliningRegionTag> {
private readonly SnapshotSpan _span;
private readonly OutliningTag _tag;
public TagSpan(SnapshotSpan span, OutliningTag tag) {
_span = span;
_tag = tag;
}
#region ITagSpan<IOutliningRegionTag> Members
public SnapshotSpan Span {
get { return _span; }
}
public IOutliningRegionTag Tag {
get { return _tag; }
}
#endregion
}
internal class OutliningTag : IOutliningRegionTag {
private readonly ITextSnapshot _snapshot;
private readonly Span _span;
public OutliningTag(ITextSnapshot iTextSnapshot, Span span) {
_snapshot = iTextSnapshot;
_span = span;
}
#region IOutliningRegionTag Members
public object CollapsedForm {
get { return "..."; }
}
public object CollapsedHintForm {
get {
string collapsedHint = _snapshot.GetText(_span);
string[] lines = collapsedHint.Split(new string[] { "\r\n" }, StringSplitOptions.None);
// remove any leading white space for the preview
if (lines.Length > 0) {
int smallestWhiteSpace = Int32.MaxValue;
for (int i = 0; i < lines.Length; i++) {
string curLine = lines[i];
for (int j = 0; j < curLine.Length; j++) {
if (curLine[j] != ' ') {
smallestWhiteSpace = Math.Min(j, smallestWhiteSpace);
}
}
}
for (int i = 0; i < lines.Length; i++) {
if (lines[i].Length >= smallestWhiteSpace) {
lines[i] = lines[i].Substring(smallestWhiteSpace);
}
}
return String.Join("\r\n", lines);
}
return collapsedHint;
}
}
public bool IsDefaultCollapsed {
get { return false; }
}
public bool IsImplementation {
get { return true; }
}
#endregion
}
}
static class OutliningTaggerProviderExtensions {
public static OutliningTaggerProvider.OutliningTagger GetOutliningTagger(this ITextView self) {
return self.TextBuffer.GetOutliningTagger();
}
public static OutliningTaggerProvider.OutliningTagger GetOutliningTagger(this ITextBuffer self) {
OutliningTaggerProvider.OutliningTagger res;
if (self.Properties.TryGetProperty<OutliningTaggerProvider.OutliningTagger>(typeof(OutliningTaggerProvider.OutliningTagger), out res)) {
return res;
}
return null;
}
}
}
| |
//
// 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.
//
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security;
namespace NLog.UnitTests
{
using System;
using NLog.Common;
using System.IO;
using System.Text;
using System.Globalization;
using NLog.Layouts;
using NLog.Config;
using NLog.Targets;
using Xunit;
using System.Xml.Linq;
using System.Xml;
using System.IO.Compression;
using System.Security.Permissions;
#if (NET3_5 || NET4_0 || NET4_5) && !NETSTANDARD
using Ionic.Zip;
#endif
public abstract class NLogTestBase
{
protected NLogTestBase()
{
//reset before every test
if (LogManager.Configuration != null)
{
//flush all events if needed.
LogManager.Configuration.Close();
}
if (LogManager.LogFactory != null)
{
LogManager.LogFactory.ResetCandidateConfigFilePath();
}
LogManager.Configuration = null;
InternalLogger.Reset();
LogManager.ThrowExceptions = false;
LogManager.ThrowConfigExceptions = null;
System.Diagnostics.Trace.Listeners.Clear();
#if !NETSTANDARD
System.Diagnostics.Debug.Listeners.Clear();
#endif
}
protected void AssertDebugCounter(string targetName, int val)
{
Assert.Equal(val, GetDebugTarget(targetName).Counter);
}
protected void AssertDebugLastMessage(string targetName, string msg)
{
Assert.Equal(msg, GetDebugLastMessage(targetName));
}
protected void AssertDebugLastMessageContains(string targetName, string msg)
{
string debugLastMessage = GetDebugLastMessage(targetName);
Assert.True(debugLastMessage.Contains(msg),
$"Expected to find '{msg}' in last message value on '{targetName}', but found '{debugLastMessage}'");
}
protected string GetDebugLastMessage(string targetName)
{
return GetDebugLastMessage(targetName, LogManager.Configuration);
}
protected string GetDebugLastMessage(string targetName, LoggingConfiguration configuration)
{
return GetDebugTarget(targetName, configuration).LastMessage;
}
public NLog.Targets.DebugTarget GetDebugTarget(string targetName)
{
return GetDebugTarget(targetName, LogManager.Configuration);
}
protected NLog.Targets.DebugTarget GetDebugTarget(string targetName, LoggingConfiguration configuration)
{
var debugTarget = (NLog.Targets.DebugTarget)configuration.FindTargetByName(targetName);
Assert.NotNull(debugTarget);
return debugTarget;
}
protected void AssertFileContentsStartsWith(string fileName, string contents, Encoding encoding)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
byte[] buf = File.ReadAllBytes(fileName);
Assert.True(encodedBuf.Length <= buf.Length,
$"File:{fileName} encodedBytes:{encodedBuf.Length} does not match file.content:{buf.Length}, file.length = {fi.Length}");
for (int i = 0; i < encodedBuf.Length; ++i)
{
if (encodedBuf[i] != buf[i])
Assert.True(encodedBuf[i] == buf[i],
$"File:{fileName} content mismatch {(int) encodedBuf[i]} <> {(int) buf[i]} at index {i}");
}
}
protected void AssertFileContentsEndsWith(string fileName, string contents, Encoding encoding)
{
if (!File.Exists(fileName))
Assert.True(false, "File '" + fileName + "' doesn't exist.");
string fileText = File.ReadAllText(fileName, encoding);
Assert.True(fileText.Length >= contents.Length);
Assert.Equal(contents, fileText.Substring(fileText.Length - contents.Length));
}
protected class CustomFileCompressor : IFileCompressor
{
public void CompressFile(string fileName, string archiveFileName)
{
#if (NET3_5 || NET4_0 || NET4_5) && !NETSTANDARD
using (var zip = new Ionic.Zip.ZipFile())
{
zip.AddFile(fileName);
zip.Save(archiveFileName);
}
#endif
}
}
#if NET3_5 || NET4_0
protected void AssertZipFileContents(string fileName, string contents, Encoding encoding)
{
if (!File.Exists(fileName))
Assert.True(false, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
using (var zip = new Ionic.Zip.ZipFile(fileName))
{
Assert.Equal(1, zip.Count);
Assert.Equal(encodedBuf.Length, zip[0].UncompressedSize);
byte[] buf = new byte[zip[0].UncompressedSize];
using (var fs = zip[0].OpenReader())
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
}
#elif NET4_5
protected void AssertZipFileContents(string fileName, string contents, Encoding encoding)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var zip = new ZipArchive(stream, ZipArchiveMode.Read))
{
Assert.Single(zip.Entries);
Assert.Equal(encodedBuf.Length, zip.Entries[0].Length);
byte[] buf = new byte[(int)zip.Entries[0].Length];
using (var fs = zip.Entries[0].Open())
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
}
#else
protected void AssertZipFileContents(string fileName, string contents, Encoding encoding)
{
Assert.True(false);
}
#endif
protected void AssertFileContents(string fileName, string contents, Encoding encoding)
{
AssertFileContents(fileName, contents, encoding, false);
}
protected void AssertFileContents(string fileName, string contents, Encoding encoding, bool addBom)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
//add bom if needed
if (addBom)
{
var preamble = encoding.GetPreamble();
if (preamble.Length > 0)
{
//insert before
encodedBuf = preamble.Concat(encodedBuf).ToArray();
}
}
byte[] buf = File.ReadAllBytes(fileName);
Assert.True(encodedBuf.Length == buf.Length,
$"File:{fileName} encodedBytes:{encodedBuf.Length} does not match file.content:{buf.Length}, file.length = {fi.Length}");
for (int i = 0; i < buf.Length; ++i)
{
if (encodedBuf[i] != buf[i])
Assert.True(encodedBuf[i] == buf[i],
$"File:{fileName} content mismatch {(int) encodedBuf[i]} <> {(int) buf[i]} at index {i}");
}
}
protected void AssertFileContains(string fileName, string contentToCheck, Encoding encoding)
{
if (contentToCheck.Contains(Environment.NewLine))
Assert.True(false, "Please use only single line string to check.");
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
using (TextReader fs = new StreamReader(fileName, encoding))
{
string line;
while ((line = fs.ReadLine()) != null)
{
if (line.Contains(contentToCheck))
return;
}
}
Assert.True(false, "File doesn't contains '" + contentToCheck + "'");
}
protected void AssertFileNotContains(string fileName, string contentToCheck, Encoding encoding)
{
if (contentToCheck.Contains(Environment.NewLine))
Assert.True(false, "Please use only single line string to check.");
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
using (TextReader fs = new StreamReader(fileName, encoding))
{
string line;
while ((line = fs.ReadLine()) != null)
{
if (line.Contains(contentToCheck))
Assert.False(true, "File contains '" + contentToCheck + "'");
}
}
return;
}
protected string StringRepeat(int times, string s)
{
StringBuilder sb = new StringBuilder(s.Length * times);
for (int i = 0; i < times; ++i)
sb.Append(s);
return sb.ToString();
}
/// <summary>
/// Render layout <paramref name="layout"/> with dummy <see cref="LogEventInfo" />and compare result with <paramref name="expected"/>.
/// </summary>
protected static void AssertLayoutRendererOutput(Layout layout, string expected)
{
var logEventInfo = LogEventInfo.Create(LogLevel.Info, "loggername", "message");
AssertLayoutRendererOutput(layout, logEventInfo, expected);
}
/// <summary>
/// Render layout <paramref name="layout"/> with <paramref name="logEventInfo"/> and compare result with <paramref name="expected"/>.
/// </summary>
protected static void AssertLayoutRendererOutput(Layout layout, LogEventInfo logEventInfo, string expected)
{
layout.Initialize(null);
string actual = layout.Render(logEventInfo);
layout.Close();
Assert.Equal(expected, actual);
}
#if NET4_5
/// <summary>
/// Get line number of previous line.
/// </summary>
protected int GetPrevLineNumber([CallerLineNumber] int callingFileLineNumber = 0)
{
return callingFileLineNumber - 1;
}
#else
/// <summary>
/// Get line number of previous line.
/// </summary>
protected int GetPrevLineNumber()
{
//fixed value set with #line 100000
return 100001;
}
#endif
public static XmlLoggingConfiguration CreateConfigurationFromString(string configXml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(configXml);
string currentDirectory = null;
try
{
currentDirectory = Environment.CurrentDirectory;
}
catch (SecurityException)
{
//ignore
}
return new XmlLoggingConfiguration(doc.DocumentElement, currentDirectory);
}
protected string RunAndCaptureInternalLog(SyncAction action, LogLevel internalLogLevel)
{
var stringWriter = new Logger();
InternalLogger.LogWriter = stringWriter;
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.IncludeTimestamp = false;
action();
return stringWriter.ToString();
}
/// <summary>
/// This class has to be used when outputting from the InternalLogger.LogWriter.
/// Just creating a string writer will cause issues, since string writer is not thread safe.
/// This can cause issues when calling the ToString() on the text writer, since the underlying stringbuilder
/// of the textwriter, has char arrays that gets fucked up by the multiple threads.
/// this is a simple wrapper that just locks access to the writer so only one thread can access
/// it at a time.
/// </summary>
private class Logger : TextWriter
{
private readonly StringWriter writer = new StringWriter();
public override Encoding Encoding
{
get
{
return this.writer.Encoding;
}
}
public override void Write(string value)
{
lock (this.writer)
{
this.writer.Write(value);
}
}
public override void WriteLine(string value)
{
lock (this.writer)
{
this.writer.WriteLine(value);
}
}
public override string ToString()
{
lock (this.writer)
{
return this.writer.ToString();
}
}
}
/// <summary>
/// Creates <see cref="CultureInfo"/> instance for test purposes
/// </summary>
/// <param name="cultureName">Culture name to create</param>
/// <remarks>
/// Creates <see cref="CultureInfo"/> instance with non-userOverride
/// flag to provide expected results when running tests in different
/// system cultures(with overriden culture options)
/// </remarks>
protected static CultureInfo GetCultureInfo(string cultureName)
{
return new CultureInfo(cultureName, false);
}
/// <summary>
/// Are we running on Travis?
/// </summary>
/// <returns></returns>
protected static bool IsTravis()
{
var val = Environment.GetEnvironmentVariable("TRAVIS");
return val != null && val.Equals("true", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Are we running on AppVeyor?
/// </summary>
/// <returns></returns>
protected static bool IsAppVeyor()
{
var val = Environment.GetEnvironmentVariable("APPVEYOR");
return val != null && val.Equals("true", StringComparison.OrdinalIgnoreCase);
}
public delegate void SyncAction();
public class InternalLoggerScope : IDisposable
{
private readonly TextWriter oldConsoleOutputWriter;
public StringWriter ConsoleOutputWriter { get; private set; }
private readonly TextWriter oldConsoleErrorWriter;
public StringWriter ConsoleErrorWriter { get; private set; }
private readonly LogLevel globalThreshold;
private readonly bool throwExceptions;
private readonly bool? throwConfigExceptions;
public InternalLoggerScope(bool redirectConsole = false)
{
if (redirectConsole)
{
ConsoleOutputWriter = new StringWriter() { NewLine = "\n" };
ConsoleErrorWriter = new StringWriter() { NewLine = "\n" };
this.oldConsoleOutputWriter = Console.Out;
this.oldConsoleErrorWriter = Console.Error;
Console.SetOut(ConsoleOutputWriter);
Console.SetError(ConsoleErrorWriter);
}
this.globalThreshold = LogManager.GlobalThreshold;
this.throwExceptions = LogManager.ThrowExceptions;
this.throwConfigExceptions = LogManager.ThrowConfigExceptions;
}
public void SetConsoleError(StringWriter consoleErrorWriter)
{
if (ConsoleOutputWriter == null || consoleErrorWriter == null)
throw new InvalidOperationException("Initialize with redirectConsole=true");
ConsoleErrorWriter = consoleErrorWriter;
Console.SetError(consoleErrorWriter);
}
public void SetConsoleOutput(StringWriter consoleOutputWriter)
{
if (ConsoleOutputWriter == null || consoleOutputWriter == null)
throw new InvalidOperationException("Initialize with redirectConsole=true");
ConsoleOutputWriter = consoleOutputWriter;
Console.SetOut(consoleOutputWriter);
}
public void Dispose()
{
InternalLogger.Reset();
if (ConsoleOutputWriter != null)
Console.SetOut(oldConsoleOutputWriter);
if (ConsoleErrorWriter != null)
Console.SetError(oldConsoleErrorWriter);
if (File.Exists(InternalLogger.LogFile))
File.Delete(InternalLogger.LogFile);
//restore logmanager
LogManager.GlobalThreshold = this.globalThreshold;
LogManager.ThrowExceptions = this.throwExceptions;
LogManager.ThrowConfigExceptions = this.throwConfigExceptions;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Input.Bindings;
using osu.Framework.Lists;
using osu.Framework.Threading;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Configuration;
using osu.Game.Extensions;
using osu.Game.Input.Bindings;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Timing;
using osu.Game.Rulesets.UI.Scrolling.Algorithms;
namespace osu.Game.Rulesets.UI.Scrolling
{
/// <summary>
/// A type of <see cref="DrawableRuleset{TObject}"/> that supports a <see cref="ScrollingPlayfield"/>.
/// <see cref="HitObject"/>s inside this <see cref="DrawableRuleset{TObject}"/> will scroll within the playfield.
/// </summary>
public abstract class DrawableScrollingRuleset<TObject> : DrawableRuleset<TObject>, IKeyBindingHandler<GlobalAction>
where TObject : HitObject
{
/// <summary>
/// The default span of time visible by the length of the scrolling axes.
/// This is clamped between <see cref="time_span_min"/> and <see cref="time_span_max"/>.
/// </summary>
private const double time_span_default = 1500;
/// <summary>
/// The minimum span of time that may be visible by the length of the scrolling axes.
/// </summary>
private const double time_span_min = 50;
/// <summary>
/// The maximum span of time that may be visible by the length of the scrolling axes.
/// </summary>
private const double time_span_max = 10000;
/// <summary>
/// The step increase/decrease of the span of time visible by the length of the scrolling axes.
/// </summary>
private const double time_span_step = 200;
protected readonly Bindable<ScrollingDirection> Direction = new Bindable<ScrollingDirection>();
/// <summary>
/// The span of time that is visible by the length of the scrolling axes.
/// For example, only hit objects with start time less than or equal to 1000 will be visible with <see cref="TimeRange"/> = 1000.
/// </summary>
protected readonly BindableDouble TimeRange = new BindableDouble(time_span_default)
{
Default = time_span_default,
MinValue = time_span_min,
MaxValue = time_span_max
};
protected virtual ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Sequential;
/// <summary>
/// Whether the player can change <see cref="TimeRange"/>.
/// </summary>
protected virtual bool UserScrollSpeedAdjustment => true;
/// <summary>
/// Whether <see cref="TimingControlPoint"/> beat lengths should scale relative to the most common beat length in the <see cref="Beatmap"/>.
/// </summary>
protected virtual bool RelativeScaleBeatLengths => false;
/// <summary>
/// The <see cref="MultiplierControlPoint"/>s that adjust the scrolling rate of <see cref="HitObject"/>s inside this <see cref="DrawableRuleset{TObject}"/>.
/// </summary>
protected readonly SortedList<MultiplierControlPoint> ControlPoints = new SortedList<MultiplierControlPoint>(Comparer<MultiplierControlPoint>.Default);
protected IScrollingInfo ScrollingInfo => scrollingInfo;
[Cached(Type = typeof(IScrollingInfo))]
private readonly LocalScrollingInfo scrollingInfo;
protected DrawableScrollingRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
: base(ruleset, beatmap, mods)
{
scrollingInfo = new LocalScrollingInfo();
scrollingInfo.Direction.BindTo(Direction);
scrollingInfo.TimeRange.BindTo(TimeRange);
}
[BackgroundDependencyLoader]
private void load()
{
switch (VisualisationMethod)
{
case ScrollVisualisationMethod.Sequential:
scrollingInfo.Algorithm = new SequentialScrollAlgorithm(ControlPoints);
break;
case ScrollVisualisationMethod.Overlapping:
scrollingInfo.Algorithm = new OverlappingScrollAlgorithm(ControlPoints);
break;
case ScrollVisualisationMethod.Constant:
scrollingInfo.Algorithm = new ConstantScrollAlgorithm();
break;
}
double lastObjectTime = Objects.LastOrDefault()?.GetEndTime() ?? double.MaxValue;
double baseBeatLength = TimingControlPoint.DEFAULT_BEAT_LENGTH;
if (RelativeScaleBeatLengths)
{
IReadOnlyList<TimingControlPoint> timingPoints = Beatmap.ControlPointInfo.TimingPoints;
double maxDuration = 0;
for (int i = 0; i < timingPoints.Count; i++)
{
if (timingPoints[i].Time > lastObjectTime)
break;
double endTime = i < timingPoints.Count - 1 ? timingPoints[i + 1].Time : lastObjectTime;
double duration = endTime - timingPoints[i].Time;
if (duration > maxDuration)
{
maxDuration = duration;
// The slider multiplier is post-multiplied to determine the final velocity, but for relative scale beat lengths
// the multiplier should not affect the effective timing point (the longest in the beatmap), so it is factored out here
baseBeatLength = timingPoints[i].BeatLength / Beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier;
}
}
}
// Merge sequences of timing and difficulty control points to create the aggregate "multiplier" control point
var lastTimingPoint = new TimingControlPoint();
var lastDifficultyPoint = new DifficultyControlPoint();
var allPoints = new SortedList<ControlPoint>(Comparer<ControlPoint>.Default);
allPoints.AddRange(Beatmap.ControlPointInfo.TimingPoints);
allPoints.AddRange(Beatmap.ControlPointInfo.DifficultyPoints);
// Generate the timing points, making non-timing changes use the previous timing change and vice-versa
var timingChanges = allPoints.Select(c =>
{
if (c is TimingControlPoint timingPoint)
lastTimingPoint = timingPoint;
else if (c is DifficultyControlPoint difficultyPoint)
lastDifficultyPoint = difficultyPoint;
return new MultiplierControlPoint(c.Time)
{
Velocity = Beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier,
BaseBeatLength = baseBeatLength,
TimingPoint = lastTimingPoint,
DifficultyPoint = lastDifficultyPoint
};
});
// Trim unwanted sequences of timing changes
timingChanges = timingChanges
// Collapse sections after the last hit object
.Where(s => s.StartTime <= lastObjectTime)
// Collapse sections with the same start time
.GroupBy(s => s.StartTime).Select(g => g.Last()).OrderBy(s => s.StartTime);
ControlPoints.AddRange(timingChanges);
if (ControlPoints.Count == 0)
ControlPoints.Add(new MultiplierControlPoint { Velocity = Beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier });
}
protected override void LoadComplete()
{
base.LoadComplete();
if (!(Playfield is ScrollingPlayfield))
throw new ArgumentException($"{nameof(Playfield)} must be a {nameof(ScrollingPlayfield)} when using {nameof(DrawableScrollingRuleset<TObject>)}.");
}
/// <summary>
/// Adjusts the scroll speed of <see cref="HitObject"/>s.
/// </summary>
/// <param name="amount">The amount to adjust by. Greater than 0 if the scroll speed should be increased, less than 0 if it should be decreased.</param>
protected virtual void AdjustScrollSpeed(int amount) => this.TransformBindableTo(TimeRange, TimeRange.Value - amount * time_span_step, 200, Easing.OutQuint);
public bool OnPressed(GlobalAction action)
{
if (!UserScrollSpeedAdjustment)
return false;
switch (action)
{
case GlobalAction.IncreaseScrollSpeed:
scheduleScrollSpeedAdjustment(1);
return true;
case GlobalAction.DecreaseScrollSpeed:
scheduleScrollSpeedAdjustment(-1);
return true;
}
return false;
}
private ScheduledDelegate scheduledScrollSpeedAdjustment;
public void OnReleased(GlobalAction action)
{
scheduledScrollSpeedAdjustment?.Cancel();
scheduledScrollSpeedAdjustment = null;
}
private void scheduleScrollSpeedAdjustment(int amount)
{
scheduledScrollSpeedAdjustment?.Cancel();
scheduledScrollSpeedAdjustment = this.BeginKeyRepeat(Scheduler, () => AdjustScrollSpeed(amount));
}
private class LocalScrollingInfo : IScrollingInfo
{
public IBindable<ScrollingDirection> Direction { get; } = new Bindable<ScrollingDirection>();
public IBindable<double> TimeRange { get; } = new BindableDouble();
public IScrollAlgorithm Algorithm { get; set; }
}
}
}
| |
using System;
using System.Data;
using System.Linq;
using NUnit.Framework;
using StructureMap.Graph;
using StructureMap.Pipeline;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget3;
namespace StructureMap.Testing.Graph
{
[TestFixture]
public class PluginFamilyTester
{
public class TheGateway : IGateway
{
#region IGateway Members
public string WhoAmI
{
get { throw new NotImplementedException(); }
}
public void DoSomething()
{
throw new NotImplementedException();
}
#endregion
}
public class DataTableProvider : IServiceProvider
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
[Test]
public void throw_exception_if_instance_is_not_compatible_with_PluginType_in_AddInstance()
{
var family = new PluginFamily(typeof(IGateway));
Exception<ArgumentOutOfRangeException>.ShouldBeThrownBy(() =>
{
family.AddInstance(new SmartInstance<ColorRule>());
});
}
[Test]
public void If_PluginFamily_only_has_one_instance_make_that_the_default()
{
var family = new PluginFamily(typeof (IGateway));
var theInstanceKey = "the default";
var instance = new ConfiguredInstance(typeof (TheGateway)).Named(theInstanceKey);
family.AddInstance(instance);
family.GetDefaultInstance().ShouldBeTheSameAs(instance);
}
public class LoggingFamilyAttribute : FamilyAttribute
{
public static bool Called { get; set; }
public override void Alter(PluginFamily family)
{
Called = true;
}
}
[LoggingFamily]
public class FamilyGateway
{
}
[LoggingFamily]
public interface IFamilyInterface
{
}
[Test]
public void PluginFamily_uses_family_attribute_when_present_on_class()
{
LoggingFamilyAttribute.Called = false;
var testFamily = typeof (FamilyGateway);
var family = new PluginFamily(testFamily);
LoggingFamilyAttribute.Called.ShouldBeTrue();
}
[Test]
public void PluginFamily_uses_family_attribute_when_present_on_interface()
{
LoggingFamilyAttribute.Called = false;
var testFamily = typeof (IFamilyInterface);
var family = new PluginFamily(testFamily);
LoggingFamilyAttribute.Called.ShouldBeTrue();
}
[Test]
public void set_the_lifecycle_to_Singleton()
{
var family = new PluginFamily(typeof (IServiceProvider));
family.SetLifecycleTo(Lifecycles.Singleton);
family.Lifecycle.ShouldBeOfType<SingletonLifecycle>();
}
[Test]
public void set_the_lifecycle_to_ThreadLocal()
{
var family = new PluginFamily(typeof (IServiceProvider));
family.SetLifecycleTo(Lifecycles.ThreadLocal);
family.Lifecycle.ShouldBeOfType<ThreadLocalStorageLifecycle>();
}
[Test]
public void add_instance_fills_and_is_idempotent()
{
var instance = new ConstructorInstance(GetType());
var family = new PluginFamily(GetType());
family.AddInstance(instance);
family.SetDefault(instance);
family.AddInstance(instance);
family.SetDefault(instance);
family.Instances.Single().ShouldBeTheSameAs(instance);
}
[Test]
public void add_type_by_name()
{
var family = new PluginFamily(typeof (IServiceProvider));
family.AddType(typeof (DataTableProvider), "table");
family.Instances.Single()
.ShouldBeOfType<ConstructorInstance>()
.PluggedType.ShouldEqual(typeof (DataTableProvider));
}
[Test]
public void add_type_does_not_add_if_the_concrete_type_can_not_be_cast_to_plugintype()
{
var family = new PluginFamily(typeof (IServiceProvider));
family.AddType(GetType());
family.Instances.Any().ShouldBeFalse();
}
[Test]
public void add_type_works_if_the_concrete_type_can_be_cast_to_plugintype()
{
var family = new PluginFamily(typeof (IServiceProvider));
family.AddType(typeof (DataTableProvider));
family.Instances.Single()
.ShouldBeOfType<ConstructorInstance>()
.PluggedType.ShouldEqual(typeof (DataTableProvider));
family.AddType(typeof (DataTable));
family.Instances.Count().ShouldEqual(1);
}
[Test]
public void remove_all_clears_the_defaul_and_removes_all_plugins_instances()
{
var family = new PluginFamily(typeof (IServiceProvider));
var instance = new SmartInstance<DataSet>();
family.Fallback = new SmartInstance<DataSet>();
family.SetDefault(instance);
family.AddInstance(new SmartInstance<FakeServiceProvider>());
family.AddType(typeof (DataSet));
family.RemoveAll();
family.GetDefaultInstance().ShouldBeNull();
family.Instances.Count().ShouldEqual(0);
}
public class FakeServiceProvider : IServiceProvider
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
[Test]
public void remove_all_clears_the_default()
{
var instance = new ConstructorInstance(GetType());
var family = new PluginFamily(GetType());
family.SetDefault(instance);
family.SetDefault(new ConstructorInstance(GetType()));
family.SetDefault(new ConstructorInstance(GetType()));
family.RemoveAll();
family.Instances.Any().ShouldBeFalse();
family.GetDefaultInstance().ShouldNotBeTheSameAs(instance);
}
[Test]
public void removing_the_default_will_change_the_default()
{
var instance = new ConstructorInstance(GetType());
var family = new PluginFamily(GetType());
family.SetDefault(instance);
family.RemoveInstance(instance);
family.Instances.Any().ShouldBeFalse();
family.GetDefaultInstance().ShouldNotBeTheSameAs(instance);
}
[Test]
public void set_default()
{
var family = new PluginFamily(typeof (IServiceProvider));
var instance = new SmartInstance<DataSet>();
family.SetDefault(instance);
family.GetDefaultInstance().ShouldBeTheSameAs(instance);
}
}
/// <summary>
/// Specifying the default instance is "Default" and marking the PluginFamily
/// as an injected Singleton
/// </summary>
//[PluginFamily("Default", IsSingleton = true)]
public interface ISingletonRepository
{
}
//[Pluggable("Default")]
public class SingletonRepositoryWithAttribute : ISingletonRepository
{
private readonly Guid _id = Guid.NewGuid();
public Guid Id
{
get { return _id; }
}
}
public class SingletonRepositoryWithoutPluginAttribute : ISingletonRepository
{
}
public class RandomClass
{
}
//[PluginFamily(IsSingleton = false)]
public interface IDevice
{
}
public class GenericType<T>
{
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace _2STBV.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
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);
}
}
}
}
| |
/* ****************************************************************************
*
* 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.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using MSAst = System.Linq.Expressions;
#else
using MSAst = Microsoft.Scripting.Ast;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
/*
* The name binding:
*
* The name binding happens in 2 passes.
* In the first pass (full recursive walk of the AST) we resolve locals.
* The second pass uses the "processed" list of all context statements (functions and class
* bodies) and has each context statement resolve its free variables to determine whether
* they are globals or references to lexically enclosing scopes.
*
* The second pass happens in post-order (the context statement is added into the "processed"
* list after processing its nested functions/statements). This way, when the function is
* processing its free variables, it also knows already which of its locals are being lifted
* to the closure and can report error if such closure variable is being deleted.
*
* This is illegal in Python:
*
* def f():
* x = 10
* if (cond): del x # illegal because x is a closure variable
* def g():
* print x
*/
namespace IronPython.Compiler.Ast {
using Ast = MSAst.Expression;
class DefineBinder : PythonWalkerNonRecursive {
private PythonNameBinder _binder;
public DefineBinder(PythonNameBinder binder) {
_binder = binder;
}
public override bool Walk(NameExpression node) {
_binder.DefineName(node.Name);
return false;
}
public override bool Walk(ParenthesisExpression node) {
return true;
}
public override bool Walk(TupleExpression node) {
return true;
}
public override bool Walk(ListExpression node) {
return true;
}
}
class ParameterBinder : PythonWalkerNonRecursive {
private PythonNameBinder _binder;
public ParameterBinder(PythonNameBinder binder) {
_binder = binder;
}
public override bool Walk(Parameter node) {
node.Parent = _binder._currentScope;
node.PythonVariable = _binder.DefineParameter(node.Name);
return false;
}
private void WalkTuple(TupleExpression tuple) {
tuple.Parent = _binder._currentScope;
foreach (Expression innerNode in tuple.Items) {
NameExpression name = innerNode as NameExpression;
if (name != null) {
_binder.DefineName(name.Name);
name.Parent = _binder._currentScope;
name.Reference = _binder.Reference(name.Name);
} else {
WalkTuple((TupleExpression)innerNode);
}
}
}
public override bool Walk(TupleExpression node) {
node.Parent = _binder._currentScope;
return true;
}
}
class DeleteBinder : PythonWalkerNonRecursive {
private PythonNameBinder _binder;
public DeleteBinder(PythonNameBinder binder) {
_binder = binder;
}
public override bool Walk(NameExpression node) {
_binder.DefineDeleted(node.Name);
return false;
}
}
class PythonNameBinder : PythonWalker {
private PythonAst _globalScope;
internal ScopeStatement _currentScope;
private List<ScopeStatement> _scopes = new List<ScopeStatement>();
private List<ILoopStatement> _loops = new List<ILoopStatement>();
private List<int> _finallyCount = new List<int>();
#region Recursive binders
private DefineBinder _define;
private DeleteBinder _delete;
private ParameterBinder _parameter;
#endregion
private readonly CompilerContext _context;
public CompilerContext Context {
get {
return _context;
}
}
private PythonNameBinder(CompilerContext context) {
_define = new DefineBinder(this);
_delete = new DeleteBinder(this);
_parameter = new ParameterBinder(this);
_context = context;
}
#region Public surface
internal static void BindAst(PythonAst ast, CompilerContext context) {
Assert.NotNull(ast, context);
PythonNameBinder binder = new PythonNameBinder(context);
binder.Bind(ast);
}
#endregion
private void Bind(PythonAst unboundAst) {
Assert.NotNull(unboundAst);
_currentScope = _globalScope = unboundAst;
_finallyCount.Add(0);
// Find all scopes and variables
unboundAst.Walk(this);
// Bind
foreach (ScopeStatement scope in _scopes) {
scope.Bind(this);
}
// Finish the globals
unboundAst.Bind(this);
// Finish Binding w/ outer most scopes first.
for (int i = _scopes.Count - 1; i >= 0; i--) {
_scopes[i].FinishBind(this);
}
// Finish the globals
unboundAst.FinishBind(this);
// Run flow checker
foreach (ScopeStatement scope in _scopes) {
FlowChecker.Check(scope);
}
}
private void PushScope(ScopeStatement node) {
node.Parent = _currentScope;
_currentScope = node;
_finallyCount.Add(0);
}
private void PopScope() {
_scopes.Add(_currentScope);
_currentScope = _currentScope.Parent;
_finallyCount.RemoveAt(_finallyCount.Count - 1);
}
internal PythonReference Reference(string name) {
return _currentScope.Reference(name);
}
internal PythonVariable DefineName(string name) {
return _currentScope.EnsureVariable(name);
}
internal PythonVariable DefineParameter(string name) {
return _currentScope.DefineParameter(name);
}
internal PythonVariable DefineDeleted(string name) {
PythonVariable variable = _currentScope.EnsureVariable(name);
variable.Deleted = true;
return variable;
}
internal void ReportSyntaxWarning(string message, Node node) {
_context.Errors.Add(_context.SourceUnit, message, node.Span, -1, Severity.Warning);
}
internal void ReportSyntaxError(string message, Node node) {
// TODO: Change the error code (-1)
_context.Errors.Add(_context.SourceUnit, message, node.Span, -1, Severity.FatalError);
throw PythonOps.SyntaxError(message, _context.SourceUnit, node.Span, -1);
}
#region AstBinder Overrides
// AssignmentStatement
public override bool Walk(AssignmentStatement node) {
node.Parent = _currentScope;
foreach (Expression e in node.Left) {
e.Walk(_define);
}
return true;
}
public override bool Walk(AugmentedAssignStatement node) {
node.Parent = _currentScope;
node.Left.Walk(_define);
return true;
}
public override void PostWalk(CallExpression node) {
if (node.NeedsLocalsDictionary()) {
_currentScope.NeedsLocalsDictionary = true;
}
}
// ClassDefinition
public override bool Walk(ClassDefinition node) {
node.PythonVariable = DefineName(node.Name);
// Base references are in the outer context
foreach (Expression b in node.Bases) b.Walk(this);
// process the decorators in the outer context
if (node.Decorators != null) {
foreach (Expression dec in node.Decorators) {
dec.Walk(this);
}
}
PushScope(node);
node.ModuleNameVariable = _globalScope.EnsureGlobalVariable("__name__");
// define the __doc__ and the __module__
if (node.Body.Documentation != null) {
node.DocVariable = DefineName("__doc__");
}
node.ModVariable = DefineName("__module__");
// Walk the body
node.Body.Walk(this);
return false;
}
// ClassDefinition
public override void PostWalk(ClassDefinition node) {
Debug.Assert(node == _currentScope);
PopScope();
}
// DelStatement
public override bool Walk(DelStatement node) {
node.Parent = _currentScope;
foreach (Expression e in node.Expressions) {
e.Walk(_delete);
}
return true;
}
public override bool Walk(ListComprehension node) {
node.Parent = _currentScope;
PushScope(node.Scope);
return base.Walk(node);
}
public override void PostWalk(ListComprehension node) {
base.PostWalk(node);
PopScope();
if (node.Scope.NeedsLocalsDictionary) {
_currentScope.NeedsLocalsDictionary = true;
}
}
public override bool Walk(SetComprehension node) {
node.Parent = _currentScope;
PushScope(node.Scope);
return base.Walk(node);
}
public override void PostWalk(SetComprehension node) {
base.PostWalk(node);
PopScope();
if (node.Scope.NeedsLocalsDictionary) {
_currentScope.NeedsLocalsDictionary = true;
}
}
public override bool Walk(DictionaryComprehension node) {
node.Parent = _currentScope;
PushScope(node.Scope);
return base.Walk(node);
}
public override void PostWalk(DictionaryComprehension node) {
base.PostWalk(node);
PopScope();
if (node.Scope.NeedsLocalsDictionary) {
_currentScope.NeedsLocalsDictionary = true;
}
}
public override void PostWalk(ConditionalExpression node) {
node.Parent = _currentScope;
base.PostWalk(node);
}
// This is generated by the scripts\generate_walker.py script.
// That will scan all types that derive from the IronPython AST nodes that aren't interesting for scopes
// and inject into here.
#region Generated Python Name Binder Propagate Current Scope
// *** BEGIN GENERATED CODE ***
// generated by function: gen_python_name_binder from: generate_walker.py
// AndExpression
public override bool Walk(AndExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// Arg
public override bool Walk(Arg node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// AssertStatement
public override bool Walk(AssertStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// BinaryExpression
public override bool Walk(BinaryExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// CallExpression
public override bool Walk(CallExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ComprehensionIf
public override bool Walk(ComprehensionIf node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ConditionalExpression
public override bool Walk(ConditionalExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ConstantExpression
public override bool Walk(ConstantExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// DictionaryExpression
public override bool Walk(DictionaryExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// DottedName
public override bool Walk(DottedName node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// EmptyStatement
public override bool Walk(EmptyStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ErrorExpression
public override bool Walk(ErrorExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ExpressionStatement
public override bool Walk(ExpressionStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// GeneratorExpression
public override bool Walk(GeneratorExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// IfStatement
public override bool Walk(IfStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// IfStatementTest
public override bool Walk(IfStatementTest node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// IndexExpression
public override bool Walk(IndexExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// LambdaExpression
public override bool Walk(LambdaExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ListExpression
public override bool Walk(ListExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// MemberExpression
public override bool Walk(MemberExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ModuleName
public override bool Walk(ModuleName node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// OrExpression
public override bool Walk(OrExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// Parameter
public override bool Walk(Parameter node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ParenthesisExpression
public override bool Walk(ParenthesisExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// RelativeModuleName
public override bool Walk(RelativeModuleName node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// SetExpression
public override bool Walk(SetExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// SliceExpression
public override bool Walk(SliceExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// SuiteStatement
public override bool Walk(SuiteStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// TryStatementHandler
public override bool Walk(TryStatementHandler node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// TupleExpression
public override bool Walk(TupleExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// UnaryExpression
public override bool Walk(UnaryExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// YieldExpression
public override bool Walk(YieldExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// *** END GENERATED CODE ***
#endregion
public override bool Walk(RaiseStatement node) {
node.Parent = _currentScope;
node.InFinally = _finallyCount[_finallyCount.Count - 1] != 0;
return base.Walk(node);
}
// ForEachStatement
public override bool Walk(ForStatement node) {
node.Parent = _currentScope;
if (_currentScope is FunctionDefinition) {
_currentScope.ShouldInterpret = false;
}
// we only push the loop for the body of the loop
// so we need to walk the for statement ourselves
node.Left.Walk(_define);
if (node.Left != null) {
node.Left.Walk(this);
}
if (node.List != null) {
node.List.Walk(this);
}
PushLoop(node);
if (node.Body != null) {
node.Body.Walk(this);
}
PopLoop();
if (node.Else != null) {
node.Else.Walk(this);
}
return false;
}
#if DEBUG
private static int _labelId;
#endif
private void PushLoop(ILoopStatement node) {
#if DEBUG
node.BreakLabel = Ast.Label("break" + _labelId++);
node.ContinueLabel = Ast.Label("continue" + _labelId++);
#else
node.BreakLabel = Ast.Label("break");
node.ContinueLabel = Ast.Label("continue");
#endif
_loops.Add(node);
}
private void PopLoop() {
_loops.RemoveAt(_loops.Count - 1);
}
public override bool Walk(WhileStatement node) {
node.Parent = _currentScope;
// we only push the loop for the body of the loop
// so we need to walk the while statement ourselves
if (node.Test != null) {
node.Test.Walk(this);
}
PushLoop(node);
if (node.Body != null) {
node.Body.Walk(this);
}
PopLoop();
if (node.ElseStatement != null) {
node.ElseStatement.Walk(this);
}
return false;
}
public override bool Walk(BreakStatement node) {
node.Parent = _currentScope;
node.LoopStatement = _loops[_loops.Count - 1];
return base.Walk(node);
}
public override bool Walk(ContinueStatement node) {
node.Parent = _currentScope;
node.LoopStatement = _loops[_loops.Count - 1];
return base.Walk(node);
}
public override bool Walk(ReturnStatement node) {
node.Parent = _currentScope;
FunctionDefinition funcDef = _currentScope as FunctionDefinition;
if (funcDef != null) {
funcDef._hasReturn = true;
}
return base.Walk(node);
}
// WithStatement
public override bool Walk(WithStatement node) {
node.Parent = _currentScope;
_currentScope.ContainsExceptionHandling = true;
if (node.Variable != null) {
node.Variable.Walk(_define);
}
return true;
}
// FromImportStatement
public override bool Walk(FromImportStatement node) {
node.Parent = _currentScope;
if (node.Names != FromImportStatement.Star) {
PythonVariable[] variables = new PythonVariable[node.Names.Count];
node.Root.Parent = _currentScope;
for (int i = 0; i < node.Names.Count; i++) {
string name = node.AsNames[i] != null ? node.AsNames[i] : node.Names[i];
variables[i] = DefineName(name);
}
node.Variables = variables;
} else {
Debug.Assert(_currentScope != null);
_currentScope.ContainsImportStar = true;
_currentScope.NeedsLocalsDictionary = true;
_currentScope.HasLateBoundVariableSets = true;
}
return true;
}
// FunctionDefinition
public override bool Walk(FunctionDefinition node) {
node._nameVariable = _globalScope.EnsureGlobalVariable("__name__");
// Name is defined in the enclosing context
if (!node.IsLambda) {
node.PythonVariable = DefineName(node.Name);
}
// process the default arg values in the outer context
foreach (Parameter p in node.Parameters) {
if (p.DefaultValue != null) {
p.DefaultValue.Walk(this);
}
}
// process the decorators in the outer context
if (node.Decorators != null) {
foreach (Expression dec in node.Decorators) {
dec.Walk(this);
}
}
PushScope(node);
foreach (Parameter p in node.Parameters) {
p.Walk(_parameter);
}
node.Body.Walk(this);
return false;
}
// FunctionDefinition
public override void PostWalk(FunctionDefinition node) {
Debug.Assert(_currentScope == node);
PopScope();
}
// GlobalStatement
public override bool Walk(GlobalStatement node) {
node.Parent = _currentScope;
foreach (string n in node.Names) {
PythonVariable conflict;
// Check current scope for conflicting variable
bool assignedGlobal = false;
if (_currentScope.TryGetVariable(n, out conflict)) {
// conflict?
switch (conflict.Kind) {
case VariableKind.Global:
case VariableKind.Local:
assignedGlobal = true;
ReportSyntaxWarning(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"name '{0}' is assigned to before global declaration",
n
),
node
);
break;
case VariableKind.Parameter:
ReportSyntaxError(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"Name '{0}' is a function parameter and declared global",
n),
node);
break;
}
}
// Check for the name being referenced previously. If it has been, issue warning.
if (_currentScope.IsReferenced(n) && !assignedGlobal) {
ReportSyntaxWarning(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"name '{0}' is used prior to global declaration",
n),
node);
}
// Create the variable in the global context and mark it as global
PythonVariable variable = _globalScope.EnsureGlobalVariable(n);
variable.Kind = VariableKind.Global;
if (conflict == null) {
// no previously definied variables, add it to the current scope
_currentScope.AddGlobalVariable(variable);
}
}
return true;
}
public override bool Walk(NameExpression node) {
node.Parent = _currentScope;
node.Reference = Reference(node.Name);
return true;
}
// PythonAst
public override bool Walk(PythonAst node) {
if (node.Module) {
node.NameVariable = DefineName("__name__");
node.FileVariable = DefineName("__file__");
node.DocVariable = DefineName("__doc__");
// commonly used module variables that we want defined for optimization purposes
DefineName("__path__");
DefineName("__builtins__");
DefineName("__package__");
}
return true;
}
// PythonAst
public override void PostWalk(PythonAst node) {
// Do not add the global suite to the list of processed nodes,
// the publishing must be done after the class local binding.
Debug.Assert(_currentScope == node);
_currentScope = _currentScope.Parent;
_finallyCount.RemoveAt(_finallyCount.Count - 1);
}
// ImportStatement
public override bool Walk(ImportStatement node) {
node.Parent = _currentScope;
PythonVariable[] variables = new PythonVariable[node.Names.Count];
for (int i = 0; i < node.Names.Count; i++) {
string name = node.AsNames[i] != null ? node.AsNames[i] : node.Names[i].Names[0];
variables[i] = DefineName(name);
node.Names[i].Parent = _currentScope;
}
node.Variables = variables;
return true;
}
// TryStatement
public override bool Walk(TryStatement node) {
// we manually walk the TryStatement so we can track finally blocks.
node.Parent = _currentScope;
_currentScope.ContainsExceptionHandling = true;
node.Body.Walk(this);
if (node.Handlers != null) {
foreach (TryStatementHandler tsh in node.Handlers) {
if (tsh.Target != null) {
tsh.Target.Walk(_define);
}
tsh.Parent = _currentScope;
tsh.Walk(this);
}
}
if (node.Else != null) {
node.Else.Walk(this);
}
if (node.Finally != null) {
_finallyCount[_finallyCount.Count - 1]++;
node.Finally.Walk(this);
_finallyCount[_finallyCount.Count - 1]--;
}
return false;
}
// ListComprehensionFor
public override bool Walk(ComprehensionFor node) {
node.Parent = _currentScope;
node.Left.Walk(_define);
return true;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//-----------------------------------------------------------------------------
using System.Diagnostics.Contracts;
namespace Microsoft.Cci.WriterUtilities {
public sealed class BinaryWriter {
public BinaryWriter(MemoryStream output) {
Contract.Requires(output != null);
this.baseStream = output;
}
public BinaryWriter(MemoryStream output, bool unicode) {
Contract.Requires(output != null);
this.baseStream = output;
this.UTF8 = !unicode;
}
[ContractInvariantMethod]
private void ObjectInvariant() {
Contract.Invariant(this.baseStream != null);
}
public MemoryStream BaseStream {
get {
Contract.Ensures(Contract.Result<MemoryStream>() != null);
return this.baseStream;
}
}
MemoryStream baseStream;
private bool UTF8 = true;
public void Align(uint alignment) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
while (i % alignment > 0) {
m.Buffer[i++] = 0;
m.Position = i;
}
}
public void WriteBool(bool value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position = i+1;
m.Buffer[i] = (byte)(value ? 1 : 0);
}
public void WriteByte(byte value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position = i+1;
m.Buffer[i] = value;
}
public void WriteSbyte(sbyte value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position = i+1;
m.Buffer[i] = (byte)value;
}
public void WriteBytes(byte[] buffer) {
if (buffer == null) return;
this.BaseStream.Write(buffer, 0, (uint)buffer.Length);
}
//public void WriteChar(char ch) {
// MemoryStream m = this.BaseStream;
// uint i = m.Position;
// if (this.UTF8) {
// if (ch < 0x80) {
// m.Position = i+1;
// m.Buffer[i] = (byte)ch;
// } else
// this.WriteChars(new char[] { ch });
// } else {
// m.Position = i+2;
// byte[] buffer = m.Buffer;
// buffer[i++] = (byte)ch;
// buffer[i] = (byte)(ch >> 8);
// }
//}
public void WriteChars(char[] chars) {
if (chars == null) return;
MemoryStream m = this.BaseStream;
uint n = (uint)chars.Length;
uint i = m.Position;
if (this.UTF8) {
m.Position = i+n;
byte[] buffer = m.Buffer;
for (int j = 0; j < n; j++) {
char ch = chars[j];
if ((ch & 0x80) != 0) goto writeUTF8;
buffer[i++] = (byte)ch;
}
return;
writeUTF8:
int ch32 = 0;
for (uint j = n-(m.Position-i); j < n; j++) {
char ch = chars[j];
if (ch < 0x80) {
m.Position = i+1;
buffer = m.Buffer;
buffer[i++] = (byte)ch;
} else if (ch < 0x800) {
m.Position = i+2;
buffer = m.Buffer;
buffer[i++] = (byte)(((ch>>6) & 0x1F) | 0xC0);
buffer[i] = (byte)((ch & 0x3F) | 0x80);
} else if (0xD800 <= ch && ch <= 0xDBFF) {
ch32 = (ch & 0x3FF) << 10;
} else if (0xDC00 <= ch && ch <= 0xDFFF) {
ch32 |= ch & 0x3FF;
m.Position = i+4;
buffer = m.Buffer;
buffer[i++] = (byte)(((ch32>>18) & 0x7) | 0xF0);
buffer[i++] = (byte)(((ch32>>12) & 0x3F) | 0x80);
buffer[i++] = (byte)(((ch32>>6) & 0x3F) | 0x80);
buffer[i] = (byte)((ch32 & 0x3F) | 0x80);
} else {
m.Position = i+3;
buffer = m.Buffer;
buffer[i++] = (byte)(((ch>>12) & 0xF) | 0xE0);
buffer[i++] = (byte)(((ch>>6) & 0x3F) | 0x80);
buffer[i] = (byte)((ch & 0x3F) | 0x80);
}
}
} else {
m.Position = i+n*2;
byte[] buffer = m.Buffer;
for (int j = 0; j < n; j++) {
char ch = chars[j];
buffer[i++] = (byte)ch;
buffer[i++] = (byte)(ch >> 8);
}
}
}
public unsafe void WriteDouble(double value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position=i+8;
byte[] buffer = m.Buffer;
byte* d = (byte*)&value;
for (uint j = 0; j < 8; j++)
buffer[i+j] = *(d + j);
}
public void WriteShort(short value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position=i+2;
byte[] buffer = m.Buffer;
buffer[i++] = (byte)value;
buffer[i] = (byte)(value >> 8);
}
public unsafe void WriteUshort(ushort value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position=i+2;
byte[] buffer = m.Buffer;
buffer[i++] = (byte)value;
buffer[i] = (byte)(value >> 8);
}
public void WriteInt(int value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position=i+4;
byte[] buffer = m.Buffer;
buffer[i++] = (byte)value;
buffer[i++] = (byte)(value >> 8);
buffer[i++] = (byte)(value >> 16);
buffer[i] = (byte)(value >> 24);
}
public void WriteUint(uint value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position=i+4;
byte[] buffer = m.Buffer;
buffer[i++] = (byte)value;
buffer[i++] = (byte)(value >> 8);
buffer[i++] = (byte)(value >> 16);
buffer[i] = (byte)(value >> 24);
}
public void WriteLong(long value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position=i+8;
byte[] buffer = m.Buffer;
uint lo = (uint)value;
uint hi = (uint)(value >> 32);
buffer[i++] = (byte)lo;
buffer[i++] = (byte)(lo >> 8);
buffer[i++] = (byte)(lo >> 16);
buffer[i++] = (byte)(lo >> 24);
buffer[i++] = (byte)hi;
buffer[i++] = (byte)(hi >> 8);
buffer[i++] = (byte)(hi >> 16);
buffer[i] = (byte)(hi >> 24);
}
public void WriteUlong(ulong value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position=i+8;
byte[] buffer = m.Buffer;
uint lo = (uint)value;
uint hi = (uint)(value >> 32);
buffer[i++] = (byte)lo;
buffer[i++] = (byte)(lo >> 8);
buffer[i++] = (byte)(lo >> 16);
buffer[i++] = (byte)(lo >> 24);
buffer[i++] = (byte)hi;
buffer[i++] = (byte)(hi >> 8);
buffer[i++] = (byte)(hi >> 16);
buffer[i] = (byte)(hi >> 24);
}
public unsafe void WriteFloat(float value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position=i+4;
byte[] buffer = m.Buffer;
byte* f = (byte*)&value;
for (uint j = 0; j < 4; j++)
buffer[i+j] = *(f + j);
}
public void WriteString(string str) {
this.WriteString(str, false);
}
public void WriteString(string str, bool emitNullTerminator) {
if (str == null) {
this.WriteByte(0xff);
return;
}
int n = str.Length;
if (!emitNullTerminator) {
if (this.UTF8)
this.WriteCompressedUInt(GetUTF8ByteCount(str));
else
this.WriteCompressedUInt((uint)n*2);
}
MemoryStream m = this.BaseStream;
uint i = m.Position;
if (this.UTF8) {
m.Position = i+(uint)n;
byte[] buffer = m.Buffer;
for (int j = 0; j < n; j++) {
char ch = str[j];
if (ch >= 0x80) goto writeUTF8;
buffer[i++] = (byte)ch;
}
if (emitNullTerminator) {
m.Position = i+1;
buffer = m.Buffer;
buffer[i] = 0;
}
return;
writeUTF8:
int ch32 = 0;
for (int j = n-(int)(m.Position-i); j < n; j++) {
char ch = str[j];
if (ch < 0x80) {
m.Position = i+1;
buffer = m.Buffer;
buffer[i++] = (byte)ch;
} else if (ch < 0x800) {
m.Position = i+2;
buffer = m.Buffer;
buffer[i++] = (byte)(((ch>>6) & 0x1F) | 0xC0);
buffer[i++] = (byte)((ch & 0x3F) | 0x80);
} else if (0xD800 <= ch && ch <= 0xDBFF) {
ch32 = (ch & 0x3FF) << 10;
} else if (0xDC00 <= ch && ch <= 0xDFFF) {
ch32 |= ch & 0x3FF;
m.Position = i+4;
buffer = m.Buffer;
buffer[i++] = (byte)(((ch32>>18) & 0x7) | 0xF0);
buffer[i++] = (byte)(((ch32>>12) & 0x3F) | 0x80);
buffer[i++] = (byte)(((ch32>>6) & 0x3F) | 0x80);
buffer[i++] = (byte)((ch32 & 0x3F) | 0x80);
} else {
m.Position = i+3;
buffer = m.Buffer;
buffer[i++] = (byte)(((ch>>12) & 0xF) | 0xE0);
buffer[i++] = (byte)(((ch>>6) & 0x3F) | 0x80);
buffer[i++] = (byte)((ch & 0x3F) | 0x80);
}
}
if (emitNullTerminator) {
m.Position = i+1;
buffer = m.Buffer;
buffer[i] = 0;
}
} else {
m.Position = i+(uint)n*2;
byte[] buffer = m.Buffer;
for (int j = 0; j < n; j++) {
char ch = str[j];
buffer[i++] = (byte)ch;
buffer[i++] = (byte)(ch >> 8);
}
if (emitNullTerminator) {
m.Position = i+2;
buffer = m.Buffer;
buffer[i++] = 0;
buffer[i] = 0;
}
}
}
public void WriteCompressedFullInt(int value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
byte[] buffer = m.Buffer;
uint d = (uint)value;
if (d + 64 < 128) {
buffer[i++] = (byte)(d*2 + 0);
} else if (d + 64*128 < 128*128) {
buffer[i++] = (byte)(d*4 + 1);
buffer[i++] = (byte)(d >> 6);
} else if (d + 64*128*128 < 128*128*128) {
buffer[i++] = (byte)(d*8 + 3);
buffer[i++] = (byte)(d >> 5);
buffer[i++] = (byte)(d >> 13);
} else if (d + 64*128*128*128 < 128*128*128*128) {
buffer[i++] = (byte)(d*16 + 7);
buffer[i++] = (byte)(d >> 4);
buffer[i++] = (byte)(d >> 12);
buffer[i++] = (byte)(d >> 20);
} else {
buffer[i++] = (byte)15;
buffer[i++] = (byte)d;
buffer[i++] = (byte)(d >> 8);
buffer[i++] = (byte)(d >> 16);
buffer[i++] = (byte)(d >> 24);
}
m.Position=i;
}
public void WriteCompressedFullUInt(uint value) {
MemoryStream m = this.BaseStream;
uint i = m.Position;
byte[] buffer = m.Buffer;
if (value < 128) {
buffer[i++] = (byte)(value*2 + 0);
} else if (value < 128*128) {
buffer[i++] = (byte)(value*4 + 1);
buffer[i++] = (byte)(value >> 6);
} else if (value < 128*128*128) {
buffer[i++] = (byte)(value*8 + 3);
buffer[i++] = (byte)(value >> 5);
buffer[i++] = (byte)(value >> 13);
} else if (value < 128*128*128*128) {
buffer[i++] = (byte)(value*16 + 7);
buffer[i++] = (byte)(value >> 4);
buffer[i++] = (byte)(value >> 12);
buffer[i++] = (byte)(value >> 20);
} else {
buffer[i++] = (byte)15;
buffer[i++] = (byte)value;
buffer[i++] = (byte)(value >> 8);
buffer[i++] = (byte)(value >> 16);
buffer[i++] = (byte)(value >> 24);
}
m.Position=i;
}
public void WriteCompressedInt(int val) {
if (val >= 0) {
val = val << 1;
this.WriteCompressedUInt((uint)val);
} else {
if (val > -0x40) {
val = 0x40 + val;
val = (val << 1)|1;
this.WriteByte((byte)val);
} else if (val >= -0x2000) {
val = 0x2000 + val;
val = (val << 1)|1;
this.WriteByte((byte)((val >> 8)|0x80));
this.WriteByte((byte)(val & 0xff));
} else if (val >= -0x20000000) {
val = 0x20000000 + val;
val = (val << 1)|1;
this.WriteByte((byte)((val >> 24)|0xc0));
this.WriteByte((byte)((val & 0xff0000)>>16));
this.WriteByte((byte)((val & 0xff00)>>8));
this.WriteByte((byte)(val & 0xff));
} else {
//^ assume false;
}
}
}
public void WriteCompressedUInt(uint val) {
if (val <= 0x7f)
this.WriteByte((byte)val);
else if (val <= 0x3fff) {
this.WriteByte((byte)((val >> 8)|0x80));
this.WriteByte((byte)(val & 0xff));
} else if (val <= 0x1fffffff) {
this.WriteByte((byte)((val >> 24)|0xc0));
this.WriteByte((byte)((val & 0xff0000)>>16));
this.WriteByte((byte)((val & 0xff00)>>8));
this.WriteByte((byte)(val & 0xff));
} else {
//^ assume false;
}
}
public static uint GetUTF8ByteCount(string str) {
uint count = 0;
for (int i = 0, n = str.Length; i < n; i++) {
char ch = str[i];
if (ch < 0x80) {
count += 1;
} else if (ch < 0x800) {
count += 2;
} else if (0xD800 <= ch && ch <= 0xDBFF) {
count += 2;
} else if (0xDC00 <= ch && ch <= 0xDFFF) {
count += 2;
} else {
count += 3;
}
}
return count;
}
}
}
| |
using Lucene.Net.Attributes;
using NUnit.Framework;
using System;
using System.Diagnostics;
namespace Lucene.Net.Util.Packed
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
[TestFixture]
public class TestEliasFanoSequence : LuceneTestCase
{
private static EliasFanoEncoder MakeEncoder(long[] values, long indexInterval)
{
long upperBound = -1L;
foreach (long value in values)
{
Assert.IsTrue(value >= upperBound); // test data ok
upperBound = value;
}
EliasFanoEncoder efEncoder = new EliasFanoEncoder(values.Length, upperBound, indexInterval);
foreach (long value in values)
{
efEncoder.EncodeNext(value);
}
return efEncoder;
}
private static void TstDecodeAllNext(long[] values, EliasFanoDecoder efd)
{
efd.ToBeforeSequence();
long nextValue = efd.NextValue();
foreach (long expValue in values)
{
Assert.IsFalse(EliasFanoDecoder.NO_MORE_VALUES == nextValue, "nextValue at end too early");
Assert.AreEqual(expValue, nextValue);
nextValue = efd.NextValue();
}
Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, nextValue);
}
private static void TstDecodeAllPrev(long[] values, EliasFanoDecoder efd)
{
efd.ToAfterSequence();
for (int i = values.Length - 1; i >= 0; i--)
{
long previousValue = efd.PreviousValue();
Assert.IsFalse(EliasFanoDecoder.NO_MORE_VALUES == previousValue, "previousValue at end too early");
Assert.AreEqual(values[i], previousValue);
}
Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, efd.PreviousValue());
}
private static void TstDecodeAllAdvanceToExpected(long[] values, EliasFanoDecoder efd)
{
efd.ToBeforeSequence();
long previousValue = -1L;
long index = 0;
foreach (long expValue in values)
{
if (expValue > previousValue)
{
long advanceValue = efd.AdvanceToValue(expValue);
Assert.IsFalse(EliasFanoDecoder.NO_MORE_VALUES == advanceValue, "advanceValue at end too early");
Assert.AreEqual(expValue, advanceValue);
Assert.AreEqual(index, efd.CurrentIndex());
previousValue = expValue;
}
index++;
}
long advanceValue_ = efd.AdvanceToValue(previousValue + 1);
Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, advanceValue_, "at end");
}
private static void TstDecodeAdvanceToMultiples(long[] values, EliasFanoDecoder efd, long m)
{
// test advancing to multiples of m
Debug.Assert(m > 0);
long previousValue = -1L;
long index = 0;
long mm = m;
efd.ToBeforeSequence();
foreach (long expValue in values)
{
// mm > previousValue
if (expValue >= mm)
{
long advanceValue = efd.AdvanceToValue(mm);
Assert.IsFalse(EliasFanoDecoder.NO_MORE_VALUES == advanceValue, "advanceValue at end too early");
Assert.AreEqual(expValue, advanceValue);
Assert.AreEqual(index, efd.CurrentIndex());
previousValue = expValue;
do
{
mm += m;
} while (mm <= previousValue);
}
index++;
}
long advanceValue_ = efd.AdvanceToValue(mm);
Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, advanceValue_);
}
private static void TstDecodeBackToMultiples(long[] values, EliasFanoDecoder efd, long m)
{
// test backing to multiples of m
Debug.Assert(m > 0);
efd.ToAfterSequence();
int index = values.Length - 1;
if (index < 0)
{
long advanceValue = efd.BackToValue(0);
Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, advanceValue);
return; // empty values, nothing to go back to/from
}
long expValue = values[index];
long previousValue = expValue + 1;
long mm = (expValue / m) * m;
while (index >= 0)
{
expValue = values[index];
Debug.Assert(mm < previousValue);
if (expValue <= mm)
{
long backValue_ = efd.BackToValue(mm);
Assert.IsFalse(EliasFanoDecoder.NO_MORE_VALUES == backValue_, "backToValue at end too early");
Assert.AreEqual(expValue, backValue_);
Assert.AreEqual(index, efd.CurrentIndex());
previousValue = expValue;
do
{
mm -= m;
} while (mm >= previousValue);
}
index--;
}
long backValue = efd.BackToValue(mm);
Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, backValue);
}
private static void TstEqual(string mes, long[] exp, long[] act)
{
Assert.AreEqual(exp.Length, act.Length, mes + ".Length");
for (int i = 0; i < exp.Length; i++)
{
if (exp[i] != act[i])
{
Assert.Fail(mes + "[" + i + "] " + exp[i] + " != " + act[i]);
}
}
}
private static void TstDecodeAll(EliasFanoEncoder efEncoder, long[] values)
{
TstDecodeAllNext(values, efEncoder.Decoder);
TstDecodeAllPrev(values, efEncoder.Decoder);
TstDecodeAllAdvanceToExpected(values, efEncoder.Decoder);
}
private static void TstEFS(long[] values, long[] expHighLongs, long[] expLowLongs)
{
EliasFanoEncoder efEncoder = MakeEncoder(values, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL);
TstEqual("upperBits", expHighLongs, efEncoder.UpperBits);
TstEqual("lowerBits", expLowLongs, efEncoder.LowerBits);
TstDecodeAll(efEncoder, values);
}
private static void TstEFS2(long[] values)
{
EliasFanoEncoder efEncoder = MakeEncoder(values, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL);
TstDecodeAll(efEncoder, values);
}
private static void TstEFSadvanceToAndBackToMultiples(long[] values, long maxValue, long minAdvanceMultiple)
{
EliasFanoEncoder efEncoder = MakeEncoder(values, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL);
for (long m = minAdvanceMultiple; m <= maxValue; m += 1)
{
TstDecodeAdvanceToMultiples(values, efEncoder.Decoder, m);
TstDecodeBackToMultiples(values, efEncoder.Decoder, m);
}
}
private EliasFanoEncoder TstEFVI(long[] values, long indexInterval, long[] expIndexBits)
{
EliasFanoEncoder efEncVI = MakeEncoder(values, indexInterval);
TstEqual("upperZeroBitPositionIndex", expIndexBits, efEncVI.IndexBits);
return efEncVI;
}
[Test]
public virtual void TestEmpty()
{
long[] values = new long[0];
long[] expHighBits = new long[0];
long[] expLowBits = new long[0];
TstEFS(values, expHighBits, expLowBits);
}
[Test]
public virtual void TestOneValue1()
{
long[] values = new long[] { 0 };
long[] expHighBits = new long[] { 0x1L };
long[] expLowBits = new long[] { };
TstEFS(values, expHighBits, expLowBits);
}
[Test]
public virtual void TestTwoValues1()
{
long[] values = new long[] { 0, 0 };
long[] expHighBits = new long[] { 0x3L };
long[] expLowBits = new long[] { };
TstEFS(values, expHighBits, expLowBits);
}
[Test]
public virtual void TestOneValue2()
{
long[] values = new long[] { 63 };
long[] expHighBits = new long[] { 2 };
long[] expLowBits = new long[] { 31 };
TstEFS(values, expHighBits, expLowBits);
}
[Test]
public virtual void TestOneMaxValue()
{
long[] values = new long[] { long.MaxValue };
long[] expHighBits = new long[] { 2 };
long[] expLowBits = new long[] { long.MaxValue / 2 };
TstEFS(values, expHighBits, expLowBits);
}
[Test]
public virtual void TestTwoMinMaxValues()
{
long[] values = new long[] { 0, long.MaxValue };
long[] expHighBits = new long[] { 0x11 };
long[] expLowBits = new long[] { unchecked((long)0xE000000000000000L), 0x03FFFFFFFFFFFFFFL };
TstEFS(values, expHighBits, expLowBits);
}
[Test]
public virtual void TestTwoMaxValues()
{
long[] values = new long[] { long.MaxValue, long.MaxValue };
long[] expHighBits = new long[] { 0x18 };
long[] expLowBits = new long[] { -1L, 0x03FFFFFFFFFFFFFFL };
TstEFS(values, expHighBits, expLowBits);
}
[Test]
public virtual void TestExample1() // Figure 1 from Vigna 2012 paper
{
long[] values = new long[] { 5, 8, 8, 15, 32 };
long[] expLowBits = new long[] { Convert.ToInt64("0011000001", 2) }; // reverse block and bit order
long[] expHighBits = new long[] { Convert.ToInt64("1000001011010", 2) }; // reverse block and bit order
TstEFS(values, expHighBits, expLowBits);
}
[Test]
public virtual void TestHashCodeEquals()
{
long[] values = new long[] { 5, 8, 8, 15, 32 };
EliasFanoEncoder efEncoder1 = MakeEncoder(values, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL);
EliasFanoEncoder efEncoder2 = MakeEncoder(values, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL);
Assert.AreEqual(efEncoder1, efEncoder2);
Assert.AreEqual(efEncoder1.GetHashCode(), efEncoder2.GetHashCode());
EliasFanoEncoder efEncoder3 = MakeEncoder(new long[] { 1, 2, 3 }, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL);
Assert.IsFalse(efEncoder1.Equals(efEncoder3));
Assert.IsFalse(efEncoder3.Equals(efEncoder1));
Assert.IsFalse(efEncoder1.GetHashCode() == efEncoder3.GetHashCode()); // implementation ok for these.
}
[Test]
public virtual void TestMonotoneSequences()
{
for (int s = 2; s < 1222; s++)
{
long[] values = new long[s];
for (int i = 0; i < s; i++)
{
values[i] = (i / 2); // upperbound smaller than number of values, only upper bits encoded
}
TstEFS2(values);
}
}
[Test, LongRunningTest]
public virtual void TestMonotoneSequencesLonger()
{
for (int s = 2; s < 4422; s++)
{
long[] values = new long[s];
for (int i = 0; i < s; i++)
{
values[i] = (i / 2); // upperbound smaller than number of values, only upper bits encoded
}
TstEFS2(values);
}
}
[Test]
public virtual void TestStrictMonotoneSequences()
{
for (int s = 2; s < 1222; s++)
{
var values = new long[s];
for (int i = 0; i < s; i++)
{
values[i] = i * ((long)i - 1) / 2; // Add a gap of (s-1) to previous
// s = (s*(s+1) - (s-1)*s)/2
}
TstEFS2(values);
}
}
[Test, LongRunningTest]
public virtual void TestStrictMonotoneSequencesLonger()
{
for (int s = 2; s < 4422; s++)
{
var values = new long[s];
for (int i = 0; i < s; i++)
{
values[i] = i * ((long)i - 1) / 2; // Add a gap of (s-1) to previous
// s = (s*(s+1) - (s-1)*s)/2
}
TstEFS2(values);
}
}
[Test]
public virtual void TestHighBitLongZero()
{
const int s = 65;
long[] values = new long[s];
for (int i = 0; i < s - 1; i++)
{
values[i] = 0;
}
values[s - 1] = 128;
long[] expHighBits = new long[] { -1, 0, 0, 1 };
long[] expLowBits = new long[0];
TstEFS(values, expHighBits, expLowBits);
}
[Test]
public virtual void TestAdvanceToAndBackToMultiples()
{
for (int s = 2; s < 130; s++)
{
long[] values = new long[s];
for (int i = 0; i < s; i++)
{
values[i] = i * ((long)i + 1) / 2; // Add a gap of s to previous
// s = (s*(s+1) - (s-1)*s)/2
}
TstEFSadvanceToAndBackToMultiples(values, values[s - 1], 10);
}
}
[Test]
public virtual void TestEmptyIndex()
{
long indexInterval = 2;
long[] emptyLongs = new long[0];
TstEFVI(emptyLongs, indexInterval, emptyLongs);
}
[Test]
public virtual void TestMaxContentEmptyIndex()
{
long indexInterval = 2;
long[] twoLongs = new long[] { 0, 1 };
long[] emptyLongs = new long[0];
TstEFVI(twoLongs, indexInterval, emptyLongs);
}
[Test]
public virtual void TestMinContentNonEmptyIndex()
{
long indexInterval = 2;
long[] twoLongs = new long[] { 0, 2 };
long[] indexLongs = new long[] { 3 }; // high bits 1001, index position after zero bit.
TstEFVI(twoLongs, indexInterval, indexLongs);
}
[Test]
public virtual void TestIndexAdvanceToLast()
{
long indexInterval = 2;
long[] twoLongs = new long[] { 0, 2 };
long[] indexLongs = new long[] { 3 }; // high bits 1001
EliasFanoEncoder efEncVI = TstEFVI(twoLongs, indexInterval, indexLongs);
Assert.AreEqual(2, efEncVI.Decoder.AdvanceToValue(2));
}
[Test]
public virtual void TestIndexAdvanceToAfterLast()
{
long indexInterval = 2;
long[] twoLongs = new long[] { 0, 2 };
long[] indexLongs = new long[] { 3 }; // high bits 1001
EliasFanoEncoder efEncVI = TstEFVI(twoLongs, indexInterval, indexLongs);
Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, efEncVI.Decoder.AdvanceToValue(3));
}
[Test]
public virtual void TestIndexAdvanceToFirst()
{
long indexInterval = 2;
long[] twoLongs = new long[] { 0, 2 };
long[] indexLongs = new long[] { 3 }; // high bits 1001
EliasFanoEncoder efEncVI = TstEFVI(twoLongs, indexInterval, indexLongs);
Assert.AreEqual(0, efEncVI.Decoder.AdvanceToValue(0));
}
[Test]
public virtual void TestTwoIndexEntries()
{
long indexInterval = 2;
long[] twoLongs = new long[] { 0, 1, 2, 3, 4, 5 };
long[] indexLongs = new long[] { 4 + 8 * 16 }; // high bits 0b10101010101
EliasFanoEncoder efEncVI = TstEFVI(twoLongs, indexInterval, indexLongs);
EliasFanoDecoder efDecVI = efEncVI.Decoder;
Assert.AreEqual(0, efDecVI.AdvanceToValue(0), "advance 0");
Assert.AreEqual(5, efDecVI.AdvanceToValue(5), "advance 5");
Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, efDecVI.AdvanceToValue(5), "advance 6");
}
[Test]
public virtual void TestExample2a() // Figure 2 from Vigna 2012 paper
{
long indexInterval = 4;
long[] values = new long[] { 5, 8, 8, 15, 32 }; // two low bits, high values 1,2,2,3,8.
long[] indexLongs = new long[] { 8 + 12 * 16 }; // high bits 0b 0001 0000 0101 1010
EliasFanoEncoder efEncVI = TstEFVI(values, indexInterval, indexLongs);
EliasFanoDecoder efDecVI = efEncVI.Decoder;
Assert.AreEqual(32, efDecVI.AdvanceToValue(22), "advance 22");
}
[Test]
public virtual void TestExample2b() // Figure 2 from Vigna 2012 paper
{
long indexInterval = 4;
long[] values = new long[] { 5, 8, 8, 15, 32 }; // two low bits, high values 1,2,2,3,8.
long[] indexLongs = new long[] { 8 + 12 * 16 }; // high bits 0b 0001 0000 0101 1010
EliasFanoEncoder efEncVI = TstEFVI(values, indexInterval, indexLongs);
EliasFanoDecoder efDecVI = efEncVI.Decoder;
Assert.AreEqual(5, efDecVI.NextValue(), "initial next");
Assert.AreEqual(32, efDecVI.AdvanceToValue(22), "advance 22");
}
[Test]
public virtual void TestExample2NoIndex1() // Figure 2 from Vigna 2012 paper, no index, test broadword selection.
{
long indexInterval = 16;
long[] values = new long[] { 5, 8, 8, 15, 32 }; // two low bits, high values 1,2,2,3,8.
long[] indexLongs = new long[0]; // high bits 0b 0001 0000 0101 1010
EliasFanoEncoder efEncVI = TstEFVI(values, indexInterval, indexLongs);
EliasFanoDecoder efDecVI = efEncVI.Decoder;
Assert.AreEqual(32, efDecVI.AdvanceToValue(22), "advance 22");
}
[Test]
public virtual void TestExample2NoIndex2() // Figure 2 from Vigna 2012 paper, no index, test broadword selection.
{
long indexInterval = 16;
long[] values = new long[] { 5, 8, 8, 15, 32 }; // two low bits, high values 1,2,2,3,8.
long[] indexLongs = new long[0]; // high bits 0b 0001 0000 0101 1010
EliasFanoEncoder efEncVI = TstEFVI(values, indexInterval, indexLongs);
EliasFanoDecoder efDecVI = efEncVI.Decoder;
Assert.AreEqual(5, efDecVI.NextValue(), "initial next");
Assert.AreEqual(32, efDecVI.AdvanceToValue(22), "advance 22");
}
}
}
| |
// Copyright (c) 2011-2015 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SIL.Keyboarding;
using SIL.ObjectModel;
using SIL.PlatformUtilities;
using SIL.Reporting;
using SIL.Windows.Forms.Keyboarding.Linux;
using SIL.Windows.Forms.Keyboarding.Windows;
namespace SIL.Windows.Forms.Keyboarding
{
/// <summary>
/// Singleton class with methods for registering different keyboarding engines (e.g. Windows
/// system, Keyman, XKB, IBus keyboards), and activating keyboards.
/// Clients have to call KeyboardController.Initialize() before they can start using the
/// keyboarding functionality, and they have to call KeyboardController.Shutdown() before
/// the application or the unit test exits.
/// </summary>
public sealed class KeyboardController : IKeyboardController
{
#region Static methods and properties
/// <summary>
/// The null keyboard description
/// </summary>
public static readonly KeyboardDescription NullKeyboard = new NullKeyboardDescription();
private static KeyboardController _instance;
internal static KeyboardController Instance
{
get { return _instance; }
}
/// <summary>
/// Enables keyboarding. This should be called during application startup.
/// </summary>
public static void Initialize(params IKeyboardRetrievingAdaptor[] adaptors)
{
// Note: arguably it is undesirable to install this as the public keyboard controller before we initialize it.
// However, we have not in general attempted thread safety for the keyboarding code; it seems
// highly unlikely that any but the UI thread wants to manipulate keyboards. Apart from other threads, nothing
// has a chance to access this before we return. If initialization does not complete successfully, we clear the
// global.
try
{
if (_instance != null)
Shutdown();
_instance = new KeyboardController();
Keyboard.Controller = _instance;
if (adaptors.Length == 0)
_instance.SetDefaultKeyboardAdaptors();
else
_instance.SetKeyboardAdaptors(adaptors);
}
catch (Exception e)
{
Console.WriteLine("Got exception {0} initalizing keyboard controller", e.GetType());
Console.WriteLine(e.StackTrace);
Logger.WriteEvent("Got exception {0} initalizing keyboard controller", e.GetType());
Logger.WriteEvent(e.StackTrace);
if (Keyboard.Controller != null)
Keyboard.Controller.Dispose();
Keyboard.Controller = null;
throw;
}
}
/// <summary>
/// Ends support for keyboarding.
/// </summary>
public static void Shutdown()
{
if (_instance == null)
return;
_instance.Dispose();
Keyboard.Controller = null;
}
/// <summary>
/// Returns <c>true</c> if KeyboardController.Initialize() got called before.
/// </summary>
public static bool IsInitialized { get { return _instance != null; } }
/// <summary>
/// Register the control for keyboarding, optionally providing an event handler for
/// a keyboarding adapter. If <paramref ref="eventHandler"/> is <c>null</c> the
/// default handler will be used.
/// The application should call this method for each control that needs IME input before
/// displaying the control, typically after calling the InitializeComponent() method.
/// </summary>
public static void RegisterControl(Control control, object eventHandler = null)
{
_instance._eventHandlers[control] = eventHandler;
if (_instance.ControlAdded != null)
_instance.ControlAdded(_instance, new RegisterEventArgs(control, eventHandler));
}
/// <summary>
/// Unregister the control from keyboarding. The application should call this method
/// prior to disposing the control so that the keyboard adapters can release unmanaged
/// resources.
/// </summary>
public static void UnregisterControl(Control control)
{
if (_instance.ControlRemoving != null)
_instance.ControlRemoving(_instance, new ControlEventArgs(control));
_instance._eventHandlers.Remove(control);
}
/// <summary/>
/// <returns>An action that will bring up the keyboard setup application dialog</returns>
public static Action GetKeyboardSetupApplication()
{
Action program = null;
if (!HasSecondaryKeyboardSetupApplication && _instance.Adaptors.ContainsKey(KeyboardAdaptorType.OtherIm))
program = _instance.Adaptors[KeyboardAdaptorType.OtherIm].GetKeyboardSetupAction();
if (program == null)
program = _instance.Adaptors[KeyboardAdaptorType.System].GetKeyboardSetupAction();
return program;
}
public static Action GetSecondaryKeyboardSetupApplication()
{
Action program = null;
if (HasSecondaryKeyboardSetupApplication && _instance.Adaptors.ContainsKey(KeyboardAdaptorType.OtherIm))
program = _instance.Adaptors[KeyboardAdaptorType.OtherIm].GetKeyboardSetupAction();
return program;
}
/// <summary>
/// Returns <c>true</c> if there is a secondary keyboard application available, e.g.
/// Keyman setup dialog on Windows.
/// </summary>
public static bool HasSecondaryKeyboardSetupApplication
{
get
{
return _instance.Adaptors.ContainsKey(KeyboardAdaptorType.OtherIm) &&
_instance.Adaptors[KeyboardAdaptorType.OtherIm].IsSecondaryKeyboardSetupApplication;
}
}
// delegate used to detect input processor, like KeyMan
private delegate bool IsUsingInputProcessorDelegate();
private static IsUsingInputProcessorDelegate _isUsingInputProcessor;
/// <summary>
/// Returns true if the current input device is an Input Processor, like KeyMan.
/// </summary>
public static bool IsFormUsingInputProcessor(Form frm)
{
bool usingIP;
if (frm.InvokeRequired)
{
// Set up a delegate for the invoke
if (_isUsingInputProcessor == null)
_isUsingInputProcessor = IsUsingInputProcessor;
usingIP = (bool)frm.Invoke(_isUsingInputProcessor);
}
else
{
usingIP = IsUsingInputProcessor();
}
return usingIP;
}
private static bool IsUsingInputProcessor()
{
if (!Platform.IsWindows)
{
// not yet implemented on Linux
return false;
}
TfInputProcessorProfilesClass inputProcessor;
try
{
inputProcessor = new TfInputProcessorProfilesClass();
}
catch (InvalidCastException)
{
return false;
}
var profileMgr = inputProcessor as ITfInputProcessorProfileMgr;
if (profileMgr == null) return false;
var profile = profileMgr.GetActiveProfile(ref Guids.Consts.TfcatTipKeyboard);
return profile.ProfileType == TfProfileType.InputProcessor;
}
#endregion
public event EventHandler<RegisterEventArgs> ControlAdded;
public event ControlEventHandler ControlRemoving;
private IKeyboardDefinition _activeKeyboard;
private readonly Dictionary<KeyboardAdaptorType, IKeyboardRetrievingAdaptor> _adaptors;
private readonly KeyedList<string, KeyboardDescription> _keyboards;
private readonly Dictionary<Control, object> _eventHandlers;
private KeyboardController()
{
_keyboards = new KeyedList<string, KeyboardDescription>(kd => kd.Id);
_eventHandlers = new Dictionary<Control, object>();
_adaptors = new Dictionary<KeyboardAdaptorType, IKeyboardRetrievingAdaptor>();
}
private void SetDefaultKeyboardAdaptors()
{
SetKeyboardAdaptors(
Platform.IsWindows
? new IKeyboardRetrievingAdaptor[]
{
new WinKeyboardAdaptor(), new KeymanKeyboardAdaptor()
}
: new IKeyboardRetrievingAdaptor[]
{
new XkbKeyboardRetrievingAdaptor(), new IbusKeyboardRetrievingAdaptor(),
new UnityXkbKeyboardRetrievingAdaptor(), new UnityIbusKeyboardRetrievingAdaptor(),
new CombinedIbusKeyboardRetrievingAdaptor()
}
);
}
private void SetKeyboardAdaptors(IKeyboardRetrievingAdaptor[] adaptors)
{
_keyboards.Clear();
foreach (IKeyboardRetrievingAdaptor adaptor in _adaptors.Values)
adaptor.Dispose();
_adaptors.Clear();
foreach (IKeyboardRetrievingAdaptor adaptor in adaptors)
{
if (adaptor.IsApplicable)
{
if ((adaptor.Type & KeyboardAdaptorType.System) == KeyboardAdaptorType.System)
_adaptors[KeyboardAdaptorType.System] = adaptor;
if ((adaptor.Type & KeyboardAdaptorType.OtherIm) == KeyboardAdaptorType.OtherIm)
_adaptors[KeyboardAdaptorType.OtherIm] = adaptor;
}
}
foreach (IKeyboardRetrievingAdaptor adaptor in adaptors)
{
if (!_adaptors.ContainsValue(adaptor))
adaptor.Dispose();
}
// Now that we know who can deal with the keyboards we can retrieve all available
// keyboards, as well as add the used keyboard adaptors as error report property.
var bldr = new StringBuilder();
foreach (IKeyboardRetrievingAdaptor adaptor in _adaptors.Values)
{
adaptor.Initialize();
if (bldr.Length > 0)
bldr.Append(", ");
bldr.Append(adaptor.GetType().Name);
}
ErrorReport.AddProperty("KeyboardAdaptors", bldr.ToString());
Logger.WriteEvent("Keyboard adaptors in use: {0}", bldr.ToString());
}
public void UpdateAvailableKeyboards()
{
foreach (IKeyboardRetrievingAdaptor adaptor in _adaptors.Values)
adaptor.UpdateAvailableKeyboards();
}
internal IKeyedCollection<string, KeyboardDescription> Keyboards
{
get { return _keyboards; }
}
internal IDictionary<KeyboardAdaptorType, IKeyboardRetrievingAdaptor> Adaptors
{
get { return _adaptors; }
}
internal IDictionary<Control, object> EventHandlers
{
get { return _eventHandlers; }
}
#region Disposable stuff
/// <summary/>
~KeyboardController()
{
Dispose(false);
}
/// <summary/>
public bool IsDisposed { get; private set; }
/// <summary/>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary/>
private void Dispose(bool fDisposing)
{
System.Diagnostics.Debug.WriteLineIf(!fDisposing,
"****** Missing Dispose() call for " + GetType() + ". *******");
if (fDisposing && !IsDisposed)
{
// dispose managed and unmanaged objects
foreach (IKeyboardRetrievingAdaptor adaptor in _adaptors.Values)
adaptor.Dispose();
_adaptors.Clear();
}
IsDisposed = true;
}
#endregion
public IKeyboardDefinition DefaultKeyboard
{
get { return _adaptors[KeyboardAdaptorType.System].SwitchingAdaptor.DefaultKeyboard; }
}
public IKeyboardDefinition GetKeyboard(string id)
{
IKeyboardDefinition keyboard;
if (TryGetKeyboard(id, out keyboard))
return keyboard;
return NullKeyboard;
}
public bool TryGetKeyboard(string id, out IKeyboardDefinition keyboard)
{
if (string.IsNullOrEmpty(id))
{
keyboard = null;
return false;
}
KeyboardDescription kd;
if (_keyboards.TryGet(id, out kd))
{
keyboard = kd;
return true;
}
string[] parts = id.Split('|');
if (parts.Length == 2)
{
// This is the way Paratext stored IDs in 7.4-7.5 while there was a temporary bug-fix in place)
keyboard = GetKeyboard(parts[0], parts[1]);
if (keyboard != NullKeyboard)
return true;
keyboard = null;
return false;
}
// Handle old Palaso IDs
parts = id.Split('-');
if (parts.Length > 1)
{
for (int i = 1; i < parts.Length; i++)
{
keyboard = GetKeyboard(string.Join("-", parts.Take(i)), string.Join("-", parts.Skip(i)));
if (keyboard != NullKeyboard)
return true;
}
}
keyboard = null;
return false;
}
public IKeyboardDefinition GetKeyboard(string layoutName, string locale)
{
IKeyboardDefinition keyboard;
if (TryGetKeyboard(layoutName, locale, out keyboard))
return keyboard;
return NullKeyboard;
}
public bool TryGetKeyboard(string layoutName, string locale, out IKeyboardDefinition keyboard)
{
if (string.IsNullOrEmpty(layoutName) && string.IsNullOrEmpty(locale))
{
keyboard = null;
return false;
}
keyboard = _keyboards.FirstOrDefault(kd => kd.Layout == layoutName && kd.Locale == locale);
return keyboard != null;
}
public IKeyboardDefinition GetKeyboard(IInputLanguage language)
{
IKeyboardDefinition keyboard;
if (TryGetKeyboard(language, out keyboard))
return keyboard;
return NullKeyboard;
}
public bool TryGetKeyboard(IInputLanguage language, out IKeyboardDefinition keyboard)
{
// NOTE: on Windows InputLanguage.LayoutName returns a wrong name in some cases.
// Therefore we need this overload so that we can identify the keyboard correctly.
keyboard = _keyboards.FirstOrDefault(kd => kd.InputLanguage != null && kd.InputLanguage.Equals(language));
return keyboard != null;
}
public IKeyboardDefinition GetKeyboard(int windowsLcid)
{
IKeyboardDefinition keyboard;
if (TryGetKeyboard(windowsLcid, out keyboard))
return keyboard;
return NullKeyboard;
}
public bool TryGetKeyboard(int windowsLcid, out IKeyboardDefinition keyboard)
{
keyboard = _keyboards.FirstOrDefault(
kbd =>
{
if (kbd.InputLanguage == null || kbd.InputLanguage.Culture == null)
return false;
return kbd.InputLanguage.Culture.LCID == windowsLcid;
});
return keyboard != null;
}
/// <summary>
/// Activates the keyboard of the default input language
/// </summary>
public void ActivateDefaultKeyboard()
{
DefaultKeyboard.Activate();
}
/// <summary>
/// Returns everything that is installed on the system and available to be used.
/// This would typically be used to populate a list of available keyboards in configuring a writing system.
/// </summary>
public IEnumerable<IKeyboardDefinition> AvailableKeyboards
{
get { return _keyboards.Where(kd => kd.IsAvailable); }
}
/// <summary>
/// Creates and returns a keyboard definition object based on the ID.
/// </summary>
public IKeyboardDefinition CreateKeyboard(string id, KeyboardFormat format, IEnumerable<string> urls)
{
KeyboardDescription keyboard;
if (!_keyboards.TryGet(id, out keyboard))
{
var firstCompatibleAdapter = _adaptors.Values.FirstOrDefault(adaptor => adaptor.CanHandleFormat(format));
if (firstCompatibleAdapter == null)
{
Debug.Fail(string.Format("Could not load keyboard for {0}. Did not find {1} in {2} adapters", id, format, _adaptors.Count));
return NullKeyboard;
}
keyboard = firstCompatibleAdapter.CreateKeyboardDefinition(id);
_keyboards.Add(keyboard);
}
keyboard.Format = format;
if (urls != null)
{
foreach (string url in urls)
{
keyboard.Urls.Add(url);
}
}
return keyboard;
}
/// <summary>
/// Gets or sets the currently active keyboard
/// </summary>
public IKeyboardDefinition ActiveKeyboard
{
get
{
if (_activeKeyboard == null)
{
_activeKeyboard = Adaptors[KeyboardAdaptorType.System].SwitchingAdaptor.ActiveKeyboard;
if (_activeKeyboard == null || _activeKeyboard == NullKeyboard)
{
try
{
var lang = InputLanguage.CurrentInputLanguage;
_activeKeyboard = GetKeyboard(lang.LayoutName, lang.Culture.Name);
}
catch (CultureNotFoundException)
{
}
}
if (_activeKeyboard == null)
_activeKeyboard = NullKeyboard;
}
return _activeKeyboard;
}
set { _activeKeyboard = value; }
}
internal static void GetLayoutAndLocaleFromLanguageId(string id, out string layout, out string locale)
{
var parts = id.Split('_', '-');
locale = parts[0];
layout = parts.Length > 1 ? parts[parts.Length - 1] : String.Empty;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.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 OpenSimulator 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 OpenMetaverse;
namespace OpenSim.Framework
{
// The delegate we will use for performing fetch from backing store
//
public delegate Object FetchDelegate(string index);
public delegate bool ExpireDelegate(string index);
// Strategy
//
// Conservative = Minimize memory. Expire items quickly.
// Balanced = Expire items with few hits quickly.
// Aggressive = Keep cache full. Expire only when over 90% and adding
//
public enum CacheStrategy
{
Conservative = 0,
Balanced = 1,
Aggressive = 2
}
// Select classes to store data on different media
//
public enum CacheMedium
{
Memory = 0,
File = 1
}
public enum CacheFlags
{
CacheMissing = 1,
AllowUpdate = 2
}
// The base class of all cache objects. Implements comparison and sorting
// by the string member.
//
// This is not abstract because we need to instantiate it briefly as a
// method parameter
//
public class CacheItemBase : IEquatable<CacheItemBase>, IComparable<CacheItemBase>
{
public string uuid;
public DateTime entered;
public DateTime lastUsed;
public DateTime expires = new DateTime(0);
public int hits = 0;
public virtual Object Retrieve()
{
return null;
}
public virtual void Store(Object data)
{
}
public CacheItemBase(string index)
{
uuid = index;
entered = DateTime.Now;
lastUsed = entered;
}
public CacheItemBase(string index, DateTime ttl)
{
uuid = index;
entered = DateTime.Now;
lastUsed = entered;
expires = ttl;
}
public virtual bool Equals(CacheItemBase item)
{
return uuid == item.uuid;
}
public virtual int CompareTo(CacheItemBase item)
{
return uuid.CompareTo(item.uuid);
}
public virtual bool IsLocked()
{
return false;
}
}
// Simple in-memory storage. Boxes the object and stores it in a variable
//
public class MemoryCacheItem : CacheItemBase
{
private Object m_Data;
public MemoryCacheItem(string index) :
base(index)
{
}
public MemoryCacheItem(string index, DateTime ttl) :
base(index, ttl)
{
}
public MemoryCacheItem(string index, Object data) :
base(index)
{
Store(data);
}
public MemoryCacheItem(string index, DateTime ttl, Object data) :
base(index, ttl)
{
Store(data);
}
public override Object Retrieve()
{
return m_Data;
}
public override void Store(Object data)
{
m_Data = data;
}
}
// Simple persistent file storage
//
public class FileCacheItem : CacheItemBase
{
public FileCacheItem(string index) :
base(index)
{
}
public FileCacheItem(string index, DateTime ttl) :
base(index, ttl)
{
}
public FileCacheItem(string index, Object data) :
base(index)
{
Store(data);
}
public FileCacheItem(string index, DateTime ttl, Object data) :
base(index, ttl)
{
Store(data);
}
public override Object Retrieve()
{
//TODO: Add file access code
return null;
}
public override void Store(Object data)
{
//TODO: Add file access code
}
}
// The main cache class. This is the class you instantiate to create
// a cache
//
public class Cache
{
/// <summary>
/// Must only be accessed under lock.
/// </summary>
private List<CacheItemBase> m_Index = new List<CacheItemBase>();
/// <summary>
/// Must only be accessed under m_Index lock.
/// </summary>
private Dictionary<string, CacheItemBase> m_Lookup =
new Dictionary<string, CacheItemBase>();
private CacheStrategy m_Strategy;
private CacheMedium m_Medium;
private CacheFlags m_Flags = 0;
private int m_Size = 1024;
private TimeSpan m_DefaultTTL = new TimeSpan(0);
public ExpireDelegate OnExpire;
// Comparison interfaces
//
private class SortLRU : IComparer<CacheItemBase>
{
public int Compare(CacheItemBase a, CacheItemBase b)
{
if (a == null && b == null)
return 0;
if (a == null)
return -1;
if (b == null)
return 1;
return(a.lastUsed.CompareTo(b.lastUsed));
}
}
// Convenience constructors
//
public Cache()
{
m_Strategy = CacheStrategy.Balanced;
m_Medium = CacheMedium.Memory;
m_Flags = 0;
}
public Cache(CacheMedium medium) :
this(medium, CacheStrategy.Balanced)
{
}
public Cache(CacheMedium medium, CacheFlags flags) :
this(medium, CacheStrategy.Balanced, flags)
{
}
public Cache(CacheMedium medium, CacheStrategy strategy) :
this(medium, strategy, 0)
{
}
public Cache(CacheStrategy strategy, CacheFlags flags) :
this(CacheMedium.Memory, strategy, flags)
{
}
public Cache(CacheFlags flags) :
this(CacheMedium.Memory, CacheStrategy.Balanced, flags)
{
}
public Cache(CacheMedium medium, CacheStrategy strategy,
CacheFlags flags)
{
m_Strategy = strategy;
m_Medium = medium;
m_Flags = flags;
}
// Count of the items currently in cache
//
public int Count
{
get { lock (m_Index) { return m_Index.Count; } }
}
// Maximum number of items this cache will hold
//
public int Size
{
get { return m_Size; }
set { SetSize(value); }
}
private void SetSize(int newSize)
{
lock (m_Index)
{
if (Count <= Size)
return;
m_Index.Sort(new SortLRU());
m_Index.Reverse();
m_Index.RemoveRange(newSize, Count - newSize);
m_Size = newSize;
m_Lookup.Clear();
foreach (CacheItemBase item in m_Index)
m_Lookup[item.uuid] = item;
}
}
public TimeSpan DefaultTTL
{
get { return m_DefaultTTL; }
set { m_DefaultTTL = value; }
}
// Get an item from cache. Return the raw item, not it's data
//
protected virtual CacheItemBase GetItem(string index)
{
CacheItemBase item = null;
lock (m_Index)
{
if (m_Lookup.ContainsKey(index))
item = m_Lookup[index];
if (item == null)
{
Expire(true);
return null;
}
item.hits++;
item.lastUsed = DateTime.Now;
Expire(true);
}
return item;
}
// Get an item from cache. Do not try to fetch from source if not
// present. Just return null
//
public virtual Object Get(string index)
{
CacheItemBase item = GetItem(index);
if (item == null)
return null;
return item.Retrieve();
}
// Fetch an object from backing store if not cached, serve from
// cache if it is.
//
public virtual Object Get(string index, FetchDelegate fetch)
{
Object item = Get(index);
if (item != null)
return item;
Object data = fetch(index);
if (data == null)
{
if ((m_Flags & CacheFlags.CacheMissing) != 0)
{
lock (m_Index)
{
CacheItemBase missing = new CacheItemBase(index);
if (!m_Index.Contains(missing))
{
m_Index.Add(missing);
m_Lookup[index] = missing;
}
}
}
return null;
}
Store(index, data);
return data;
}
// Find an object in cache by delegate.
//
public Object Find(Predicate<CacheItemBase> d)
{
CacheItemBase item;
lock (m_Index)
item = m_Index.Find(d);
if (item == null)
return null;
return item.Retrieve();
}
public virtual void Store(string index, Object data)
{
Type container;
switch (m_Medium)
{
case CacheMedium.Memory:
container = typeof(MemoryCacheItem);
break;
case CacheMedium.File:
return;
default:
return;
}
Store(index, data, container);
}
public virtual void Store(string index, Object data, Type container)
{
Store(index, data, container, new Object[] { index });
}
public virtual void Store(string index, Object data, Type container,
Object[] parameters)
{
CacheItemBase item;
lock (m_Index)
{
Expire(false);
if (m_Index.Contains(new CacheItemBase(index)))
{
if ((m_Flags & CacheFlags.AllowUpdate) != 0)
{
item = GetItem(index);
item.hits++;
item.lastUsed = DateTime.Now;
if (m_DefaultTTL.Ticks != 0)
item.expires = DateTime.Now + m_DefaultTTL;
item.Store(data);
}
return;
}
item = (CacheItemBase)Activator.CreateInstance(container,
parameters);
if (m_DefaultTTL.Ticks != 0)
item.expires = DateTime.Now + m_DefaultTTL;
m_Index.Add(item);
m_Lookup[index] = item;
}
item.Store(data);
}
/// <summary>
/// Expire items as appropriate.
/// </summary>
/// <remarks>
/// Callers must lock m_Index.
/// </remarks>
/// <param name='getting'></param>
protected virtual void Expire(bool getting)
{
if (getting && (m_Strategy == CacheStrategy.Aggressive))
return;
if (m_DefaultTTL.Ticks != 0)
{
DateTime now= DateTime.Now;
foreach (CacheItemBase item in new List<CacheItemBase>(m_Index))
{
if (item.expires.Ticks == 0 ||
item.expires <= now)
{
m_Index.Remove(item);
m_Lookup.Remove(item.uuid);
}
}
}
switch (m_Strategy)
{
case CacheStrategy.Aggressive:
if (Count < Size)
return;
m_Index.Sort(new SortLRU());
m_Index.Reverse();
int target = (int)((float)Size * 0.9);
if (target == Count) // Cover ridiculous cache sizes
return;
ExpireDelegate doExpire = OnExpire;
if (doExpire != null)
{
List<CacheItemBase> candidates =
m_Index.GetRange(target, Count - target);
foreach (CacheItemBase i in candidates)
{
if (doExpire(i.uuid))
{
m_Index.Remove(i);
m_Lookup.Remove(i.uuid);
}
}
}
else
{
m_Index.RemoveRange(target, Count - target);
m_Lookup.Clear();
foreach (CacheItemBase item in m_Index)
m_Lookup[item.uuid] = item;
}
break;
default:
break;
}
}
public void Invalidate(string uuid)
{
lock (m_Index)
{
if (!m_Lookup.ContainsKey(uuid))
return;
CacheItemBase item = m_Lookup[uuid];
m_Lookup.Remove(uuid);
m_Index.Remove(item);
}
}
public void Clear()
{
lock (m_Index)
{
m_Index.Clear();
m_Lookup.Clear();
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System;
using System.Collections.ObjectModel;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.Xml;
using SchProtocols = System.IdentityModel.SchProtocols;
class TlsnegoTokenProvider : SspiNegotiationTokenProvider
{
SecurityTokenAuthenticator serverTokenAuthenticator;
SecurityTokenProvider clientTokenProvider;
public TlsnegoTokenProvider()
: base()
{
// empty
}
public SecurityTokenAuthenticator ServerTokenAuthenticator
{
get
{
return this.serverTokenAuthenticator;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.serverTokenAuthenticator = value;
}
}
public SecurityTokenProvider ClientTokenProvider
{
get
{
return this.clientTokenProvider;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.clientTokenProvider = value;
}
}
// helpers
static X509SecurityToken ValidateToken(SecurityToken token)
{
X509SecurityToken result = token as X509SecurityToken;
if (result == null && token != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TokenProviderReturnedBadToken, token.GetType().ToString())));
}
return result;
}
SspiNegotiationTokenProviderState CreateTlsSspiState(X509SecurityToken token)
{
X509Certificate2 clientCertificate;
if (token == null)
{
clientCertificate = null;
}
else
{
clientCertificate = token.Certificate;
}
TlsSspiNegotiation tlsNegotiation = new TlsSspiNegotiation(String.Empty, SchProtocols.Ssl3Client | SchProtocols.TlsClient, clientCertificate);
return new SspiNegotiationTokenProviderState(tlsNegotiation);
}
// overrides
public override XmlDictionaryString NegotiationValueType
{
get
{
if (this.StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
{
return XD.TrustApr2004Dictionary.TlsnegoValueTypeUri;
}
else if (this.StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
{
return DXD.TrustDec2005Dictionary.TlsnegoValueTypeUri;
}
// Not supported
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
protected override bool CreateNegotiationStateCompletesSynchronously(EndpointAddress target, Uri via)
{
if (this.ClientTokenProvider == null)
{
return true;
}
else
{
return false;
}
}
protected override IAsyncResult BeginCreateNegotiationState(EndpointAddress target, Uri via, TimeSpan timeout, AsyncCallback callback, object state)
{
EnsureEndpointAddressDoesNotRequireEncryption(target);
if (this.ClientTokenProvider == null)
{
return new CompletedAsyncResult<SspiNegotiationTokenProviderState>(CreateTlsSspiState(null), callback, state);
}
else
{
return new CreateSspiStateAsyncResult(target, via, this, timeout, callback, state);
}
}
protected override SspiNegotiationTokenProviderState EndCreateNegotiationState(IAsyncResult result)
{
if (result is CompletedAsyncResult<SspiNegotiationTokenProviderState>)
{
return CompletedAsyncResult<SspiNegotiationTokenProviderState>.End(result);
}
else
{
return CreateSspiStateAsyncResult.End(result);
}
}
protected override SspiNegotiationTokenProviderState CreateNegotiationState(EndpointAddress target, Uri via, TimeSpan timeout)
{
EnsureEndpointAddressDoesNotRequireEncryption(target);
X509SecurityToken clientToken;
if (this.ClientTokenProvider == null)
{
clientToken = null;
}
else
{
SecurityToken token = this.ClientTokenProvider.GetToken(timeout);
clientToken = ValidateToken(token);
}
return CreateTlsSspiState(clientToken);
}
protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateSspiNegotiation(ISspiNegotiation sspiNegotiation)
{
TlsSspiNegotiation tlsNegotiation = (TlsSspiNegotiation)sspiNegotiation;
if (tlsNegotiation.IsValidContext == false)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.InvalidSspiNegotiation)));
}
X509Certificate2 serverCert = tlsNegotiation.RemoteCertificate;
if (serverCert == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.ServerCertificateNotProvided)));
}
ReadOnlyCollection<IAuthorizationPolicy> authzPolicies;
if (this.ServerTokenAuthenticator != null)
{
X509SecurityToken certToken = new X509SecurityToken(serverCert, false);
authzPolicies = this.ServerTokenAuthenticator.ValidateToken(certToken);
}
else
{
authzPolicies = EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance;
}
return authzPolicies;
}
public override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.ClientTokenProvider != null)
{
SecurityUtils.OpenTokenProviderIfRequired(this.ClientTokenProvider, timeoutHelper.RemainingTime());
}
if (this.ServerTokenAuthenticator != null)
{
SecurityUtils.OpenTokenAuthenticatorIfRequired(this.ServerTokenAuthenticator, timeoutHelper.RemainingTime());
}
base.OnOpen(timeoutHelper.RemainingTime());
}
public override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.clientTokenProvider != null)
{
SecurityUtils.CloseTokenProviderIfRequired(this.ClientTokenProvider, timeoutHelper.RemainingTime());
this.clientTokenProvider = null;
}
if (this.serverTokenAuthenticator != null)
{
SecurityUtils.CloseTokenAuthenticatorIfRequired(this.ServerTokenAuthenticator, timeoutHelper.RemainingTime());
this.serverTokenAuthenticator = null;
}
base.OnClose(timeoutHelper.RemainingTime());
}
public override void OnAbort()
{
if (this.clientTokenProvider != null)
{
SecurityUtils.AbortTokenProviderIfRequired(this.ClientTokenProvider);
this.clientTokenProvider = null;
}
if (this.serverTokenAuthenticator != null)
{
SecurityUtils.AbortTokenAuthenticatorIfRequired(this.ServerTokenAuthenticator);
this.serverTokenAuthenticator = null;
}
base.OnAbort();
}
class CreateSspiStateAsyncResult : AsyncResult
{
static readonly AsyncCallback getTokensCallback = Fx.ThunkCallback(new AsyncCallback(GetTokensCallback));
TlsnegoTokenProvider tlsTokenProvider;
SspiNegotiationTokenProviderState sspiState;
public CreateSspiStateAsyncResult(EndpointAddress target, Uri via, TlsnegoTokenProvider tlsTokenProvider, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.tlsTokenProvider = tlsTokenProvider;
IAsyncResult result = this.tlsTokenProvider.ClientTokenProvider.BeginGetToken(timeout, getTokensCallback, this);
if (!result.CompletedSynchronously)
{
return;
}
SecurityToken token = this.tlsTokenProvider.ClientTokenProvider.EndGetToken(result);
X509SecurityToken clientToken = ValidateToken(token);
this.sspiState = this.tlsTokenProvider.CreateTlsSspiState(clientToken);
base.Complete(true);
}
static void GetTokensCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
CreateSspiStateAsyncResult typedResult = (CreateSspiStateAsyncResult)result.AsyncState;
try
{
SecurityToken token = typedResult.tlsTokenProvider.ClientTokenProvider.EndGetToken(result);
X509SecurityToken clientToken = TlsnegoTokenProvider.ValidateToken(token);
typedResult.sspiState = typedResult.tlsTokenProvider.CreateTlsSspiState(clientToken);
typedResult.Complete(false);
}
catch (Exception e)
{
if (Fx.IsFatal(e)) throw;
typedResult.Complete(false, e);
}
}
public static SspiNegotiationTokenProviderState End(IAsyncResult result)
{
CreateSspiStateAsyncResult asyncResult = AsyncResult.End<CreateSspiStateAsyncResult>(result);
return asyncResult.sspiState;
}
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Internal
{
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// HashSet optimized for single item
/// </summary>
/// <typeparam name="T"></typeparam>
internal struct SingleItemOptimizedHashSet<T> : ICollection<T>
{
private readonly T _singleItem;
private HashSet<T> _hashset;
private readonly IEqualityComparer<T> _comparer;
private IEqualityComparer<T> Comparer => _comparer ?? EqualityComparer<T>.Default;
public struct SingleItemScopedInsert : IDisposable
{
private readonly T _singleItem;
private readonly HashSet<T> _hashset;
/// <summary>
/// Insert single item on scope start, and remove on scope exit
/// </summary>
/// <param name="singleItem">Item to insert in scope</param>
/// <param name="existing">Existing hashset to update</param>
/// <param name="forceHashSet">Force allocation of real hashset-container</param>
/// <param name="comparer">HashSet EqualityComparer</param>
public SingleItemScopedInsert(T singleItem, ref SingleItemOptimizedHashSet<T> existing, bool forceHashSet, IEqualityComparer<T> comparer)
{
_singleItem = singleItem;
if (existing._hashset != null)
{
existing._hashset.Add(singleItem);
_hashset = existing._hashset;
}
else if (forceHashSet)
{
existing = new SingleItemOptimizedHashSet<T>(singleItem, existing, comparer);
existing.Add(singleItem);
_hashset = existing._hashset;
}
else
{
existing = new SingleItemOptimizedHashSet<T>(singleItem, existing, comparer);
_hashset = null;
}
}
public void Dispose()
{
if (_hashset != null)
{
_hashset.Remove(_singleItem);
}
}
}
public int Count => _hashset?.Count ?? (EqualityComparer<T>.Default.Equals(_singleItem, default(T)) ? 0 : 1); // Object Equals to default value
public bool IsReadOnly => false;
public SingleItemOptimizedHashSet(T singleItem, SingleItemOptimizedHashSet<T> existing, IEqualityComparer<T> comparer = null)
{
_comparer = existing._comparer ?? comparer ?? EqualityComparer<T>.Default;
if (existing._hashset != null)
{
_hashset = new HashSet<T>(existing._hashset, _comparer);
_hashset.Add(singleItem);
_singleItem = default(T);
}
else if (existing.Count == 1)
{
_hashset = new HashSet<T>(_comparer);
_hashset.Add(existing._singleItem);
_hashset.Add(singleItem);
_singleItem = default(T);
}
else
{
_hashset = null;
_singleItem = singleItem;
}
}
/// <summary>
/// Add item to collection, if it not already exists
/// </summary>
/// <param name="item">Item to insert</param>
public void Add(T item)
{
if (_hashset != null)
{
_hashset.Add(item);
}
else
{
var hashset = new HashSet<T>(Comparer);
if (Count != 0)
{
hashset.Add(_singleItem);
}
hashset.Add(item);
_hashset = hashset;
}
}
/// <summary>
/// Clear hashset
/// </summary>
public void Clear()
{
if (_hashset != null)
{
_hashset.Clear();
}
else
{
_hashset = new HashSet<T>(Comparer);
}
}
/// <summary>
/// Check if hashset contains item
/// </summary>
/// <param name="item"></param>
/// <returns>Item exists in hashset (true/false)</returns>
public bool Contains(T item)
{
if (_hashset != null)
{
return _hashset.Contains(item);
}
else
{
return Count == 1 && Comparer.Equals(_singleItem, item);
}
}
/// <summary>
/// Remove item from hashset
/// </summary>
/// <param name="item"></param>
/// <returns>Item removed from hashset (true/false)</returns>
public bool Remove(T item)
{
if (_hashset != null)
{
return _hashset.Remove(item);
}
else
{
_hashset = new HashSet<T>(Comparer);
return Comparer.Equals(_singleItem, item);
}
}
/// <summary>
/// Copy items in hashset to array
/// </summary>
/// <param name="array">Destination array</param>
/// <param name="arrayIndex">Array offset</param>
public void CopyTo(T[] array, int arrayIndex)
{
if (_hashset != null)
{
_hashset.CopyTo(array, arrayIndex);
}
else if (Count == 1)
{
array[arrayIndex] = _singleItem;
}
}
/// <summary>
/// Create hashset enumerator
/// </summary>
/// <returns>Enumerator</returns>
public IEnumerator<T> GetEnumerator()
{
if (_hashset != null)
{
return _hashset.GetEnumerator();
}
else
{
return SingleItemEnumerator();
}
}
private IEnumerator<T> SingleItemEnumerator()
{
if (Count != 0)
yield return _singleItem;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public sealed class ReferenceEqualityComparer : IEqualityComparer<T>
{
public static readonly ReferenceEqualityComparer Default = new ReferenceEqualityComparer();
bool IEqualityComparer<T>.Equals(T x, T y)
{
return ReferenceEquals(x, y);
}
int IEqualityComparer<T>.GetHashCode(T obj)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
}
}
}
| |
// 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 ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RouteTablesOperations operations.
/// </summary>
public partial interface IRouteTablesOperations
{
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteTable>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteTable>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteTable>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteTable>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteTable>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteTable>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteTable>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using ProceduralDataflow.Interfaces;
namespace ProceduralDataflow
{
public class AsyncProcDataflowBlock : IAsyncProcDataflowBlock, IStartStopable
{
private readonly int? maximumDegreeOfParallelism;
private readonly CancellationToken cancellationToken;
private readonly bool supportsPause;
private readonly Channel<Func<Task>> collection;
private readonly Channel<Func<Task>> collectionForReentrantItems;
private readonly Guid nodeId;
private readonly object pauseLockingObject = new object();
private TaskCompletionSource<int> pauseTcs;
private readonly IActionRunner actionRunner;
/// <summary>
///
/// </summary>
/// <param name="actionRunner">This is used if async actions to be executed might contain CPU-intensive operations. Can be null.</param>
/// <param name="maximumNumberOfActionsInQueue"></param>
/// <param name="maximumDegreeOfParallelism"></param>
/// <param name="cancellationToken"></param>
/// <param name="supportsPause"></param>
public AsyncProcDataflowBlock(
IActionRunner actionRunner,
int maximumNumberOfActionsInQueue,
int? maximumDegreeOfParallelism,
CancellationToken cancellationToken = default,
bool supportsPause = false)
{
this.actionRunner = actionRunner;
this.maximumDegreeOfParallelism = maximumDegreeOfParallelism;
this.cancellationToken = cancellationToken;
this.supportsPause = supportsPause;
collection = Channel.CreateBounded<Func<Task>>(maximumNumberOfActionsInQueue);
collectionForReentrantItems = Channel.CreateUnbounded<Func<Task>>();
nodeId = Guid.NewGuid();
}
public AsyncProcDataflowBlock(
int maximumNumberOfActionsInQueue,
int? maximumDegreeOfParallelism,
CancellationToken cancellationToken = default,
bool supportsPause = false)
: this(null, maximumNumberOfActionsInQueue, maximumDegreeOfParallelism, cancellationToken, supportsPause)
{
}
public DfTask Run(Func<Task> action)
{
var task = new DfTask();
var currentListOfVisitedNodes = ListOfVisitedNodes.Current.Value ?? (ListOfVisitedNodes.Current.Value = new ListOfVisitedNodes());
var firstVisit = !currentListOfVisitedNodes.VisitedNodes.Contains(nodeId);
if (firstVisit)
currentListOfVisitedNodes.VisitedNodes.Add(nodeId);
Func<Task> runAction = async () =>
{
Exception exception = null;
try
{
if (cancellationToken.IsCancellationRequested)
{
exception = new OperationCanceledException(cancellationToken);
}
else
{
await action();
}
}
catch (Exception ex)
{
exception = ex;
}
ListOfVisitedNodes.Current.Value = currentListOfVisitedNodes;
DfTask.AsyncBlockingTask = null;
if (exception == null)
task.SetResult();
else
task.SetException(exception);
if (DfTask.AsyncBlockingTask != null)
await DfTask.AsyncBlockingTask;
};
Func<Task> actionToAddToCollection =
Utilities.MakeActionRunInCurrentExecutionContextIfAny(runAction);
ListOfVisitedNodes.Current.Value = null;
if (firstVisit)
{
DfTask.AsyncBlockingTask = collection.Writer.WriteAsync(actionToAddToCollection).AsTask();
}
else
{
DfTask.AsyncBlockingTask = collectionForReentrantItems.Writer.WriteAsync(actionToAddToCollection).AsTask();
}
return task;
}
public DfTask<TResult> Run<TResult>(Func<Task<TResult>> function)
{
var task = new DfTask<TResult>();
var currentListOfVisitedNodes = ListOfVisitedNodes.Current.Value ?? (ListOfVisitedNodes.Current.Value = new ListOfVisitedNodes());
var firstVisit = !currentListOfVisitedNodes.VisitedNodes.Contains(nodeId);
if (firstVisit)
currentListOfVisitedNodes.VisitedNodes.Add(nodeId);
Func<Task> runAction = async() =>
{
TResult result = default;
Exception exception = null;
try
{
if (cancellationToken.IsCancellationRequested)
{
exception = new OperationCanceledException(cancellationToken);
}
else
{
result = await function();
}
}
catch (Exception ex)
{
exception = ex;
}
ListOfVisitedNodes.Current.Value = currentListOfVisitedNodes;
DfTask.AsyncBlockingTask = null;
if (exception == null)
task.SetResult(result);
else
task.SetException(exception);
if (DfTask.AsyncBlockingTask != null)
await DfTask.AsyncBlockingTask;
};
Func<Task> actionToAddToCollection =
Utilities.MakeActionRunInCurrentExecutionContextIfAny(runAction);
ListOfVisitedNodes.Current.Value = null;
if (firstVisit)
{
DfTask.AsyncBlockingTask = collection.Writer.WriteAsync(actionToAddToCollection).AsTask();
}
else
{
DfTask.AsyncBlockingTask = collectionForReentrantItems.Writer.WriteAsync(actionToAddToCollection).AsTask();
}
return task;
}
public void Start()
{
DoIt();
}
public void Pause()
{
if (!supportsPause)
throw new Exception("Pause is not supported based on constructor parameter");
lock (pauseLockingObject)
{
if (pauseTcs != null)
throw new Exception("Already paused");
pauseTcs = new TaskCompletionSource<int>();
}
}
public void Resume()
{
if (!supportsPause)
throw new Exception("Pause is not supported based on constructor parameter");
lock (pauseLockingObject)
{
if (pauseTcs == null)
throw new Exception("Not paused");
pauseTcs.SetResult(0);
pauseTcs = null;
}
}
private async Task DoIt()
{
List<Task> tasks = new List<Task>();
while (true)
{
var action = await GetAction();
if (action == null)
return;
if (supportsPause)
{
Task resumeTask = null;
lock (pauseLockingObject)
{
if (pauseTcs != null)
{
resumeTask = pauseTcs.Task;
}
}
if (resumeTask != null)
{
await resumeTask;
}
}
var task = actionRunner is null ? action() : actionRunner.EnqueueAction(action);
if (maximumDegreeOfParallelism.HasValue)
{
tasks.Add(task);
if (tasks.Count == maximumDegreeOfParallelism)
{
var taskToRemove = await Task.WhenAny(tasks);
tasks.Remove(taskToRemove);
}
}
}
}
private async Task<Func<Task>> GetAction()
{
return await Utilities.TakeItemFromAnyCollectionWithPriorityToFirstCollection(collectionForReentrantItems, collection);
}
public void Stop()
{
collection.Writer.TryComplete();
collectionForReentrantItems.Writer.TryComplete();
}
public static AsyncProcDataflowBlock StartDefault(
int maximumNumberOfActionsInQueue,
int? maximumDegreeOfParallelism,
bool supportsPause = false)
{
var block =
new AsyncProcDataflowBlock(
maximumNumberOfActionsInQueue,
maximumDegreeOfParallelism,
supportsPause: supportsPause);
block.Start();
return block;
}
}
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <author name="Daniel Grunwald"/>
// <version>$Revision: 5762 $</version>
// </file>
using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Threading;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Editing;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.AvalonEdit.Utils;
namespace ICSharpCode.AvalonEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
[Localizability(LocalizationCategory.Text), ContentProperty("Text")]
public class TextEditor : Control, ITextEditorComponent, IServiceProvider, IWeakEventListener
{
#region Constructors
static TextEditor()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TextEditor),
new FrameworkPropertyMetadata(typeof(TextEditor)));
FocusableProperty.OverrideMetadata(typeof(TextEditor),
new FrameworkPropertyMetadata(Boxes.True));
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea)
{
if (textArea == null)
throw new ArgumentNullException("textArea");
this.textArea = textArea;
textArea.TextView.Services.AddService(typeof(TextEditor), this);
this.Options = textArea.Options;
this.Document = new TextDocument();
}
#endregion
/// <inheritdoc/>
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return new TextEditorAutomationPeer(this);
}
/// Forward focus to TextArea.
/// <inheritdoc/>
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnGotKeyboardFocus(e);
if (!this.TextArea.IsKeyboardFocusWithin) {
Keyboard.Focus(this.TextArea);
e.Handled = true;
}
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly DependencyProperty DocumentProperty
= TextView.DocumentProperty.AddOwner(
typeof(TextEditor), new FrameworkPropertyMetadata(OnDocumentChanged));
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document {
get { return (TextDocument)GetValue(DocumentProperty); }
set { SetValue(DocumentProperty, value); }
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
if (DocumentChanged != null) {
DocumentChanged(this, e);
}
}
static void OnDocumentChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
((TextEditor)dp).OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null) {
TextDocumentWeakEventManager.TextChanged.RemoveListener(oldValue, this);
PropertyChangedEventManager.RemoveListener(oldValue.UndoStack, this, "IsOriginalFile");
}
textArea.Document = newValue;
if (newValue != null) {
TextDocumentWeakEventManager.TextChanged.AddListener(newValue, this);
PropertyChangedEventManager.AddListener(newValue.UndoStack, this, "IsOriginalFile");
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly DependencyProperty OptionsProperty
= TextView.OptionsProperty.AddOwner(typeof(TextEditor), new FrameworkPropertyMetadata(OnOptionsChanged));
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options {
get { return (TextEditorOptions)GetValue(OptionsProperty); }
set { SetValue(OptionsProperty, value); }
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
if (OptionChanged != null) {
OptionChanged(this, e);
}
}
static void OnOptionsChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
((TextEditor)dp).OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null) {
PropertyChangedWeakEventManager.RemoveListener(oldValue, this);
}
textArea.Options = newValue;
if (newValue != null) {
PropertyChangedWeakEventManager.AddListener(newValue, this);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (managerType == typeof(PropertyChangedWeakEventManager)) {
OnOptionChanged((PropertyChangedEventArgs)e);
return true;
} else if (managerType == typeof(TextDocumentWeakEventManager.TextChanged)) {
OnTextChanged(e);
return true;
} else if (managerType == typeof(PropertyChangedEventManager)) {
return HandleIsOriginalChanged((PropertyChangedEventArgs)e);
}
return false;
}
bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
return ReceiveWeakEvent(managerType, sender, e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
[Localizability(LocalizationCategory.Text), DefaultValue("")]
public string Text {
get {
TextDocument document = this.Document;
return document != null ? document.Text : string.Empty;
}
set {
TextDocument document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
//this.CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
TextDocument GetDocument()
{
TextDocument document = this.Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
if (TextChanged != null) {
TextChanged(this, e);
}
}
#endregion
#region TextArea / ScrollViewer properties
readonly TextArea textArea;
ScrollViewer scrollViewer;
/// <summary>
/// Is called after the template was applied.
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
scrollViewer = (ScrollViewer)Template.FindName("PART_ScrollViewer", this);
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea {
get {
return textArea;
}
}
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer {
get { return scrollViewer; }
}
bool CanExecute(RoutedUICommand command)
{
TextArea textArea = this.TextArea;
if (textArea == null)
return false;
else
return command.CanExecute(null, textArea);
}
void Execute(RoutedUICommand command)
{
TextArea textArea = this.TextArea;
if (textArea != null)
command.Execute(null, textArea);
}
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly DependencyProperty SyntaxHighlightingProperty =
DependencyProperty.Register("SyntaxHighlighting", typeof(IHighlightingDefinition), typeof(TextEditor),
new FrameworkPropertyMetadata(OnSyntaxHighlightingChanged));
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting {
get { return (IHighlightingDefinition)GetValue(SyntaxHighlightingProperty); }
set { SetValue(SyntaxHighlightingProperty, value); }
}
IVisualLineTransformer colorizer;
static void OnSyntaxHighlightingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TextEditor)d).OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (colorizer != null) {
this.TextArea.TextView.LineTransformers.Remove(colorizer);
colorizer = null;
}
if (newValue != null) {
colorizer = CreateColorizer(newValue);
this.TextArea.TextView.LineTransformers.Insert(0, colorizer);
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException("highlightingDefinition");
return new HighlightingColorizer(highlightingDefinition.MainRuleSet);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly DependencyProperty WordWrapProperty =
DependencyProperty.Register("WordWrap", typeof(bool), typeof(TextEditor),
new FrameworkPropertyMetadata(Boxes.False));
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
public bool WordWrap {
get { return (bool)GetValue(WordWrapProperty); }
set { SetValue(WordWrapProperty, Boxes.Box(value)); }
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly DependencyProperty IsReadOnlyProperty =
DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(TextEditor),
new FrameworkPropertyMetadata(Boxes.False, OnIsReadOnlyChanged));
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly {
get { return (bool)GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, Boxes.Box(value)); }
}
static void OnIsReadOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextEditor editor = d as TextEditor;
if (editor != null) {
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlyDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
TextEditorAutomationPeer peer = TextEditorAutomationPeer.FromElement(editor) as TextEditorAutomationPeer;
if (peer != null) {
peer.RaiseIsReadOnlyChanged((bool)e.OldValue, (bool)e.NewValue);
}
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly DependencyProperty IsModifiedProperty =
DependencyProperty.Register("IsModified", typeof(bool), typeof(TextEditor),
new FrameworkPropertyMetadata(Boxes.False, OnIsModifiedChanged));
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified {
get { return (bool)GetValue(IsModifiedProperty); }
set { SetValue(IsModifiedProperty, Boxes.Box(value)); }
}
static void OnIsModifiedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextEditor editor = d as TextEditor;
if (editor != null) {
TextDocument document = editor.Document;
if (document != null) {
UndoStack undoStack = document.UndoStack;
if ((bool)e.NewValue) {
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
} else {
undoStack.MarkAsOriginalFile();
}
}
}
}
bool HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile") {
TextDocument document = this.Document;
if (document != null) {
this.IsModified = !document.UndoStack.IsOriginalFile;
}
return true;
} else {
return false;
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly DependencyProperty ShowLineNumbersProperty =
DependencyProperty.Register("ShowLineNumbers", typeof(bool), typeof(TextEditor),
new FrameworkPropertyMetadata(Boxes.False, OnShowLineNumbersChanged));
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers {
get { return (bool)GetValue(ShowLineNumbersProperty); }
set { SetValue(ShowLineNumbersProperty, Boxes.Box(value)); }
}
static void OnShowLineNumbersChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextEditor editor = (TextEditor)d;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue) {
leftMargins.Insert(0, new LineNumberMargin());
leftMargins.Insert(1, DottedLineMargin.Create());
} else {
for (int i = 0; i < leftMargins.Count; i++) {
if (leftMargins[i] is LineNumberMargin) {
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) {
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
Execute(ApplicationCommands.Copy);
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
Execute(ApplicationCommands.Cut);
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
if (scrollViewer != null)
scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
if (scrollViewer != null)
scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
if (scrollViewer != null)
scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
if (scrollViewer != null)
scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
if (scrollViewer != null)
scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
if (scrollViewer != null)
scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
if (scrollViewer != null)
scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
if (scrollViewer != null)
scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
Execute(ApplicationCommands.Paste);
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanExecute(ApplicationCommands.Redo)) {
Execute(ApplicationCommands.Redo);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
if (scrollViewer != null)
scrollViewer.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
if (scrollViewer != null)
scrollViewer.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
if (scrollViewer != null)
scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
if (scrollViewer != null)
scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
Execute(ApplicationCommands.SelectAll);
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanExecute(ApplicationCommands.Undo)) {
Execute(ApplicationCommands.Undo);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo {
get { return CanExecute(ApplicationCommands.Redo); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo {
get { return CanExecute(ApplicationCommands.Undo); }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight {
get {
return scrollViewer != null ? scrollViewer.ExtentHeight : 0;
}
}
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth {
get {
return scrollViewer != null ? scrollViewer.ExtentWidth : 0;
}
}
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight {
get {
return scrollViewer != null ? scrollViewer.ViewportHeight : 0;
}
}
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth {
get {
return scrollViewer != null ? scrollViewer.ViewportWidth : 0;
}
}
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset {
get {
return scrollViewer != null ? scrollViewer.VerticalOffset : 0;
}
}
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset {
get {
return scrollViewer != null ? scrollViewer.HorizontalOffset : 0;
}
}
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string SelectedText {
get {
TextArea textArea = this.TextArea;
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea != null && textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
else
return string.Empty;
}
set {
if (value == null)
throw new ArgumentNullException("value");
TextArea textArea = this.TextArea;
if (textArea != null && textArea.Document != null) {
int offset = this.SelectionStart;
int length = this.SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = new SimpleSelection(offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int CaretOffset {
get {
TextArea textArea = this.TextArea;
if (textArea != null)
return textArea.Caret.Offset;
else
return 0;
}
set {
TextArea textArea = this.TextArea;
if (textArea != null)
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int SelectionStart {
get {
TextArea textArea = this.TextArea;
if (textArea != null) {
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
} else {
return 0;
}
}
set {
Select(value, SelectionLength);
}
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int SelectionLength {
get {
TextArea textArea = this.TextArea;
if (textArea != null && !textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set {
Select(SelectionStart, value);
}
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
int documentLength = Document != null ? Document.TextLength : 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException("start", start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException("length", length, "Value must be between 0 and " + (documentLength - length));
textArea.Selection = new SimpleSelection(start, start + length);
textArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int LineCount {
get {
TextDocument document = this.Document;
if (document != null)
return document.LineCount;
else
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
this.Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (StreamReader reader = FileReader.OpenStream(stream, this.Encoding ?? Encoding.UTF8)) {
this.Text = reader.ReadToEnd();
this.Encoding = reader.CurrentEncoding; // assign encoding after ReadToEnd() so that the StreamReader can autodetect the encoding
}
this.IsModified = false;
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
Load(fs);
}
}
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Encoding Encoding { get; set; }
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
StreamWriter writer = new StreamWriter(stream, this.Encoding ?? Encoding.UTF8);
writer.Write(this.Text);
writer.Flush();
// do not close the stream
this.IsModified = false;
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) {
Save(fs);
}
}
#endregion
#region MouseHover events
/// <summary>
/// The PreviewMouseHover event.
/// </summary>
public static readonly RoutedEvent PreviewMouseHoverEvent =
TextView.PreviewMouseHoverEvent.AddOwner(typeof(TextEditor));
/// <summary>
/// The MouseHover event.
/// </summary>
public static readonly RoutedEvent MouseHoverEvent =
TextView.MouseHoverEvent.AddOwner(typeof(TextEditor));
/// <summary>
/// The PreviewMouseHoverStopped event.
/// </summary>
public static readonly RoutedEvent PreviewMouseHoverStoppedEvent =
TextView.PreviewMouseHoverStoppedEvent.AddOwner(typeof(TextEditor));
/// <summary>
/// The MouseHoverStopped event.
/// </summary>
public static readonly RoutedEvent MouseHoverStoppedEvent =
TextView.MouseHoverStoppedEvent.AddOwner(typeof(TextEditor));
/// <summary>
/// Occurs when the mouse has hovered over a fixed location for some time.
/// </summary>
public event MouseEventHandler PreviewMouseHover {
add { AddHandler(PreviewMouseHoverEvent, value); }
remove { RemoveHandler(PreviewMouseHoverEvent, value); }
}
/// <summary>
/// Occurs when the mouse has hovered over a fixed location for some time.
/// </summary>
public event MouseEventHandler MouseHover {
add { AddHandler(MouseHoverEvent, value); }
remove { RemoveHandler(MouseHoverEvent, value); }
}
/// <summary>
/// Occurs when the mouse had previously hovered but now started moving again.
/// </summary>
public event MouseEventHandler PreviewMouseHoverStopped {
add { AddHandler(PreviewMouseHoverStoppedEvent, value); }
remove { RemoveHandler(PreviewMouseHoverStoppedEvent, value); }
}
/// <summary>
/// Occurs when the mouse had previously hovered but now started moving again.
/// </summary>
public event MouseEventHandler MouseHoverStopped {
add { AddHandler(MouseHoverStoppedEvent, value); }
remove { RemoveHandler(MouseHoverStoppedEvent, value); }
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return textArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (this.Document == null)
return null;
TextView textView = this.TextArea.TextView;
return textView.GetPosition(TranslatePoint(point, textView) + textView.ScrollOffset);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollPercentage = 0.3;
if (scrollViewer != null) {
Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), VisualYPosition.LineMiddle);
double verticalPos = p.Y - scrollViewer.ViewportHeight / 2;
if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > MinimumScrollPercentage * scrollViewer.ViewportHeight) {
scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos));
}
if (column > 0) {
if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) {
double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2);
if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > MinimumScrollPercentage * scrollViewer.ViewportWidth) {
scrollViewer.ScrollToHorizontalOffset(horizontalPos);
}
} else {
scrollViewer.ScrollToHorizontalOffset(0);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class WriteBufferSize_Property : PortsTest
{
private const int MAX_RANDMOM_BUFFER_SIZE = 1024 * 16;
private const int LARGE_BUFFER_SIZE = 1024 * 128;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
private void WriteBufferSize_Default()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default WriteBufferSize before Open");
serPortProp.SetAllPropertiesToDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp.VerifyPropertiesAndPrint(com1);
Debug.WriteLine("Verifying default WriteBufferSize after Open");
com1.Open();
serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp.VerifyPropertiesAndPrint(com1);
Debug.WriteLine("Verifying default WriteBufferSize after Close");
com1.Close();
serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void WriteBufferSize_AfterOpen()
{
VerifyException(1024, null, typeof(InvalidOperationException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteBufferSize_NEG1()
{
VerifyException(-1, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteBufferSize_Int32MinValue()
{
VerifyException(int.MinValue, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteBufferSize_0()
{
VerifyException(0, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteBufferSize_1()
{
Debug.WriteLine("Verifying setting WriteBufferSize=1");
VerifyException(1, typeof(IOException), typeof(InvalidOperationException), true);
}
[ConditionalFact(nameof(HasNullModem))]
public void WriteBufferSize_Smaller()
{
uint newWriteBufferSize = (uint)(new SerialPort()).WriteBufferSize;
newWriteBufferSize /= 2; //Make the new buffer size half the original size
newWriteBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit
VerifyWriteBufferSize((int)newWriteBufferSize);
}
[ConditionalFact(nameof(HasNullModem))]
public void WriteBufferSize_Larger()
{
using (var com = new SerialPort())
{
VerifyWriteBufferSize(com.WriteBufferSize * 2);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteBufferSize_Odd()
{
Debug.WriteLine("Verifying setting WriteBufferSize=Odd");
using (var com = new SerialPort())
{
int bufferSize = com.WriteBufferSize * 2 + 1;
VerifyException(bufferSize, typeof(IOException), typeof(InvalidOperationException), true);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void WriteBufferSize_Even()
{
Debug.WriteLine("Verifying setting WriteBufferSize=Even");
using (var com = new SerialPort())
{
VerifyWriteBufferSize(com.WriteBufferSize * 2);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void WriteBufferSize_Rnd()
{
Random rndGen = new Random(-55);
uint newWriteBufferSize = (uint)rndGen.Next(MAX_RANDMOM_BUFFER_SIZE);
newWriteBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit
VerifyWriteBufferSize((int)newWriteBufferSize);
}
[ConditionalFact(nameof(HasNullModem))]
public void WriteBufferSize_Large()
{
VerifyWriteBufferSize(LARGE_BUFFER_SIZE);
}
#endregion
#region Verification for Test Cases
private void VerifyException(int newWriteBufferSize, Type expectedExceptionBeforeOpen, Type expectedExceptionAfterOpen)
{
VerifyException(newWriteBufferSize, expectedExceptionBeforeOpen, expectedExceptionAfterOpen, false);
}
private void VerifyException(int newWriteBufferSize, Type expectedExceptionBeforeOpen, Type expectedExceptionAfterOpen, bool throwAtOpen)
{
VerifyExceptionBeforeOpen(newWriteBufferSize, expectedExceptionBeforeOpen, throwAtOpen);
VerifyExceptionAfterOpen(newWriteBufferSize, expectedExceptionAfterOpen);
}
private void VerifyExceptionBeforeOpen(int newWriteBufferSize, Type expectedException, bool throwAtOpen)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
try
{
com.WriteBufferSize = newWriteBufferSize;
if (throwAtOpen)
com.Open();
if (null != expectedException)
{
Fail("Err_707278ahpa!!! expected exception {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("Err_201890ioyun Expected no exception to be thrown and following was thrown \n{0}", e);
}
else if (e.GetType() != expectedException)
{
Fail("Err_545498ahpba!!! expected exception {0} and {1} was thrown", expectedException, e.GetType());
}
}
}
}
private void VerifyExceptionAfterOpen(int newWriteBufferSize, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int originalWriteBufferSize = com.WriteBufferSize;
com.Open();
try
{
com.WriteBufferSize = newWriteBufferSize;
Fail("Err_561567anhbp!!! expected exception {0} and nothing was thrown", expectedException);
}
catch (Exception e)
{
if (e.GetType() != expectedException)
{
Fail("Err_21288ajpbam!!! expected exception {0} and {1} was thrown", expectedException, e.GetType());
}
else if (originalWriteBufferSize != com.WriteBufferSize)
{
Fail("Err_454987ahbopa!!! expected WriteBufferSize={0} and actual={1}", originalWriteBufferSize, com.WriteBufferSize);
}
else if (TCSupport.SufficientHardwareRequirements(TCSupport.SerialPortRequirements.NullModem))
{
VerifyWriteBufferSize(com, originalWriteBufferSize);
}
}
}
}
private void VerifyWriteBufferSize(int newWriteBufferSize)
{
Debug.WriteLine("Verifying setting WriteBufferSize={0} BEFORE a call to Open() has been made", newWriteBufferSize);
VerifyWriteBufferSizeBeforeOpen(newWriteBufferSize);
}
private void VerifyWriteBufferSizeBeforeOpen(int newWriteBufferSize)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying setting WriteBufferSize to {0}", newWriteBufferSize);
com1.WriteBufferSize = newWriteBufferSize;
com1.Open();
VerifyWriteBufferSize(com1, newWriteBufferSize);
}
}
private void VerifyWriteBufferSize(SerialPort com1, int expectedWriteBufferSize)
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
byte[] xmitBytes = new byte[Math.Max(expectedWriteBufferSize, com1.WriteBufferSize)];
byte[] rcvBytes = new byte[xmitBytes.Length];
SerialPortProperties serPortProp = new SerialPortProperties();
Random rndGen = new Random(-55);
for (int i = 0; i < xmitBytes.Length; i++)
{
xmitBytes[i] = (byte)rndGen.Next(0, 256);
}
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com2.ReadBufferSize = expectedWriteBufferSize;
serPortProp.SetProperty("WriteBufferSize", expectedWriteBufferSize);
com2.Open();
int origBaudRate = com1.BaudRate;
com2.BaudRate = 115200;
com1.BaudRate = 115200;
serPortProp.SetProperty("BaudRate", 115200);
com1.Write(xmitBytes, 0, xmitBytes.Length);
TCSupport.WaitForReadBufferToLoad(com2, xmitBytes.Length);
Debug.WriteLine("Verifying properties after changing WriteBufferSize");
serPortProp.VerifyPropertiesAndPrint(com1);
com2.Read(rcvBytes, 0, rcvBytes.Length);
Assert.Equal(xmitBytes, rcvBytes);
com2.BaudRate = origBaudRate;
com1.BaudRate = origBaudRate;
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Property4U.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("AQUAS/Reflection")]
[ExecuteInEditMode] // Make mirror live-update even when not in play mode
public class AQUAS_Reflection : MonoBehaviour
{
#region Variables
public bool m_DisablePixelLights = true;
public int m_TextureSize = 256;
public float m_ClipPlaneOffset = 0.07f;
public LayerMask m_ReflectLayers = -1;
private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table
private RenderTexture m_ReflectionTexture = null;
private int m_OldReflectionTextureSize = 0;
private static bool s_InsideRendering = false;
public void OnWillRenderObject()
{
if( !enabled || !GetComponent<Renderer>() || !GetComponent<Renderer>().sharedMaterial || !GetComponent<Renderer>().enabled )
return;
Camera cam = Camera.current;
if( !cam )
return;
// Safeguard from recursive reflections.
if( s_InsideRendering )
return;
s_InsideRendering = true;
Camera reflectionCamera;
CreateMirrorObjects( cam, out reflectionCamera );
// find out the reflection plane: position and normal in world space
Vector3 pos = transform.position;
Vector3 normal = transform.up;
// Optionally disable pixel lights for reflection
int oldPixelLightCount = QualitySettings.pixelLightCount;
if( m_DisablePixelLights )
QualitySettings.pixelLightCount = 0;
UpdateCameraModes( cam, reflectionCamera );
// Render reflection
// Reflect camera around reflection plane
float d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset;
Vector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero;
CalculateReflectionMatrix (ref reflection, reflectionPlane);
Vector3 oldpos = cam.transform.position;
Vector3 newpos = reflection.MultiplyPoint( oldpos );
reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
// Setup oblique projection matrix so that near plane is our reflection
// plane. This way we clip everything below/above it for free.
Vector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f );
Matrix4x4 projection = cam.projectionMatrix;
CalculateObliqueMatrix (ref projection, clipPlane);
reflectionCamera.projectionMatrix = projection;
reflectionCamera.cullingMask = ~(1<<4) & m_ReflectLayers.value; // never render water layer
reflectionCamera.targetTexture = m_ReflectionTexture;
//GL.invertCulling = true; //should be used but inverts the faces of the terrain
GL.SetRevertBackfacing (true); //obsolete
reflectionCamera.transform.position = newpos;
Vector3 euler = cam.transform.eulerAngles;
reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);
reflectionCamera.Render();
reflectionCamera.transform.position = oldpos;
//GL.invertCulling = true; //should be used but inverts the faces of the terrain
GL.SetRevertBackfacing (false); //obsolete
Material[] materials = GetComponent<Renderer>().sharedMaterials;
foreach( Material mat in materials ) {
if( mat.HasProperty("_ReflectionTex") )
mat.SetTexture( "_ReflectionTex", m_ReflectionTexture );
}
// Set matrix on the shader that transforms UVs from object space into screen
// space. We want to just project reflection texture on screen.
Matrix4x4 scaleOffset = Matrix4x4.TRS(
new Vector3(0.5f,0.5f,0.5f), Quaternion.identity, new Vector3(0.5f,0.5f,0.5f) );
Vector3 scale = transform.lossyScale;
Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale( new Vector3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z) );
mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx;
foreach( Material mat in materials ) {
mat.SetMatrix( "_ProjMatrix", mtx );
}
// Restore pixel light count
if( m_DisablePixelLights )
QualitySettings.pixelLightCount = oldPixelLightCount;
s_InsideRendering = false;
}
#endregion
//<summary>
// Cleans up all the objects that were possibly created
//</summary>
void OnDisable()
{
if( m_ReflectionTexture ) {
DestroyImmediate( m_ReflectionTexture );
m_ReflectionTexture = null;
}
foreach( DictionaryEntry kvp in m_ReflectionCameras )
DestroyImmediate( ((Camera)kvp.Value).gameObject );
m_ReflectionCameras.Clear();
}
private void UpdateCameraModes( Camera src, Camera dest )
{
if( dest == null )
return;
//sets camera to clear the same way as current camera
dest.clearFlags = src.clearFlags;
dest.backgroundColor = src.backgroundColor;
if( src.clearFlags == CameraClearFlags.Skybox )
{
Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
if( !sky || !sky.material )
{
mysky.enabled = false;
}
else
{
mysky.enabled = true;
mysky.material = sky.material;
}
}
///<summary>
///Updates other values to match current camera.
///Even if camera&projection matrices are supplied, some of values are used elsewhere (e.g. skybox uses far plane)
/// </summary>
dest.farClipPlane = src.farClipPlane;
dest.nearClipPlane = src.nearClipPlane;
dest.orthographic = src.orthographic;
dest.fieldOfView = src.fieldOfView;
dest.aspect = src.aspect;
dest.orthographicSize = src.orthographicSize;
}
//<summary>
//Creates any objects needed on demand
//</summary>
private void CreateMirrorObjects( Camera currentCamera, out Camera reflectionCamera )
{
reflectionCamera = null;
//Reflection render texture
if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize )
{
if( m_ReflectionTexture )
DestroyImmediate( m_ReflectionTexture );
m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
m_ReflectionTexture.name = "__MirrorReflection" + GetInstanceID();
m_ReflectionTexture.isPowerOfTwo = true;
m_ReflectionTexture.hideFlags = HideFlags.DontSave;
m_OldReflectionTextureSize = m_TextureSize;
}
//Camera for reflection
reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
if( !reflectionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
{
GameObject go = new GameObject( "Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
reflectionCamera = go.GetComponent<Camera>();
reflectionCamera.enabled = false;
reflectionCamera.transform.position = transform.position;
reflectionCamera.transform.rotation = transform.rotation;
reflectionCamera.gameObject.AddComponent<FlareLayer>();
go.hideFlags = HideFlags.HideAndDontSave;
m_ReflectionCameras[currentCamera] = reflectionCamera;
}
}
//<summary>
//Extended sign: returns -1, 0 or 1 based on sign of a
//</summary>
private static float sgn(float a)
{
if (a > 0.0f) return 1.0f;
if (a < 0.0f) return -1.0f;
return 0.0f;
}
//<summary>
//Given position/normal of the plane, calculates plane in camera space.
//</summary>
private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint( offsetPos );
Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) );
}
//<summary>
//Adjusts the given projection matrix so that near plane is the given clipPlane
//clipPlane is given in camera space
//</summary>
private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q = projection.inverse * new Vector4(
sgn(clipPlane.x),
sgn(clipPlane.y),
1.0f,
1.0f
);
Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
// third row = clip plane - fourth row
projection[2] = c.x - projection[3];
projection[6] = c.y - projection[7];
projection[10] = c.z - projection[11];
projection[14] = c.w - projection[15];
}
//<summary>
//Calculates reflection matrix around the given plane
//</summary>
private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]);
reflectionMat.m01 = ( - 2F*plane[0]*plane[1]);
reflectionMat.m02 = ( - 2F*plane[0]*plane[2]);
reflectionMat.m03 = ( - 2F*plane[3]*plane[0]);
reflectionMat.m10 = ( - 2F*plane[1]*plane[0]);
reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]);
reflectionMat.m12 = ( - 2F*plane[1]*plane[2]);
reflectionMat.m13 = ( - 2F*plane[3]*plane[1]);
reflectionMat.m20 = ( - 2F*plane[2]*plane[0]);
reflectionMat.m21 = ( - 2F*plane[2]*plane[1]);
reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]);
reflectionMat.m23 = ( - 2F*plane[3]*plane[2]);
reflectionMat.m30 = 0F;
reflectionMat.m31 = 0F;
reflectionMat.m32 = 0F;
reflectionMat.m33 = 1F;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using System.Runtime.Versioning;
using Microsoft.VisualStudio.Shell;
using NuGet.Client.ProjectSystem;
using NuGet.PowerShell.Commands;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Resources;
using NuGetConsole.Host.PowerShell.Implementation;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Interop;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
#endif
namespace NuGet.Client.VisualStudio.PowerShell
{
/// <summary>
/// This command process the specified package against the specified project.
/// </summary>
public abstract class NuGetPowerShellBaseCommand : PSCmdlet, IExecutionContext, IErrorHandler
{
private VsSourceRepositoryManager _repoManager;
private IVsPackageSourceProvider _packageSourceProvider;
private IPackageRepositoryFactory _repositoryFactory;
private SVsServiceProvider _serviceProvider;
private IVsPackageManagerFactory _packageManagerFactory;
private ISolutionManager _solutionManager;
private VsPackageManagerContext _VsContext;
private readonly IHttpClientEvents _httpClientEvents;
internal const string PSCommandsUserAgentClient = "NuGet VS PowerShell Console";
internal const string PowerConsoleHostName = "Package Manager Host";
private readonly Lazy<string> _psCommandsUserAgent = new Lazy<string>(
() => HttpUtility.CreateUserAgentString(PSCommandsUserAgentClient, VsVersionHelper.FullVsEdition));
private ProgressRecordCollection _progressRecordCache;
private bool _overwriteAll, _ignoreAll;
public NuGetPowerShellBaseCommand(
IVsPackageSourceProvider packageSourceProvider,
IPackageRepositoryFactory packageRepositoryFactory,
SVsServiceProvider svcServceProvider,
IVsPackageManagerFactory packageManagerFactory,
ISolutionManager solutionManager,
IHttpClientEvents clientEvents)
{
_packageSourceProvider = packageSourceProvider;
_repositoryFactory = packageRepositoryFactory;
_serviceProvider = svcServceProvider;
_packageManagerFactory = packageManagerFactory;
_solutionManager = solutionManager;
_repoManager = new VsSourceRepositoryManager(_packageSourceProvider, _repositoryFactory);
_VsContext = new VsPackageManagerContext(_repoManager, _serviceProvider, _solutionManager, _packageManagerFactory);
_httpClientEvents = clientEvents;
}
internal VsSolution Solution
{
get
{
return _VsContext.GetCurrentVsSolution();
}
}
internal VsSourceRepositoryManager RepositoryManager
{
get
{
return _repoManager;
}
set
{
_repoManager = value;
}
}
internal IVsPackageManagerFactory PackageManagerFactory
{
get
{
return _packageManagerFactory;
}
set
{
_packageManagerFactory = value;
}
}
internal ISolutionManager SolutionManager
{
get
{
return _solutionManager;
}
}
internal bool IsSyncMode
{
get
{
if (Host == null || Host.PrivateData == null)
{
return false;
}
PSObject privateData = Host.PrivateData;
var syncModeProp = privateData.Properties["IsSyncMode"];
return syncModeProp != null && (bool)syncModeProp.Value;
}
}
protected virtual void LogCore(Client.MessageLevel level, string formattedMessage)
{
switch (level)
{
case Client.MessageLevel.Debug:
WriteVerbose(formattedMessage);
break;
case Client.MessageLevel.Info:
WriteLine(formattedMessage);
break;
case Client.MessageLevel.Error:
WriteError(formattedMessage);
break;
}
}
internal void Execute()
{
switch (level)
{
case Client.MessageLevel.Warning:
WriteWarning(formattedMessage);
break;
case Client.MessageLevel.Info:
WriteLine(formattedMessage);
break;
case Client.MessageLevel.Error:
WriteError(formattedMessage);
break;
}
BeginProcessing();
ProcessRecord();
EndProcessing();
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to display friendly message to the console.")]
protected sealed override void ProcessRecord()
{
try
{
ProcessRecordCore();
}
catch (Exception ex)
{
// unhandled exceptions should be terminating
ErrorHandler.HandleException(ex, terminating: true);
}
finally
{
UnsubscribeEvents();
}
}
/// <summary>
/// Derived classess must implement this method instead of ProcessRecord(), which is sealed by NuGetBaseCmdlet.
/// </summary>
protected abstract void ProcessRecordCore();
protected override void BeginProcessing()
{
if (_httpClientEvents != null)
{
_httpClientEvents.SendingRequest += OnSendingRequest;
}
}
protected override void StopProcessing()
{
UnsubscribeEvents();
base.StopProcessing();
}
protected void UnsubscribeEvents()
{
if (_httpClientEvents != null)
{
_httpClientEvents.SendingRequest -= OnSendingRequest;
}
}
protected virtual void OnSendingRequest(object sender, WebRequestEventArgs e)
{
HttpUtility.SetUserAgent(e.Request, _psCommandsUserAgent.Value);
}
protected IErrorHandler ErrorHandler
{
get
{
return this;
}
}
#region Logging
public void Log(Client.MessageLevel level, string message, params object[] args)
{
string formattedMessage = String.Format(CultureInfo.CurrentCulture, message, args);
LogCore(level, formattedMessage);
}
public virtual FileConflictAction ResolveFileConflict(string message)
{
if (_overwriteAll)
{
return FileConflictAction.OverwriteAll;
}
if (_ignoreAll)
{
return FileConflictAction.IgnoreAll;
}
var choices = new Collection<ChoiceDescription>
{
new ChoiceDescription(Resources.Cmdlet_Yes, Resources.Cmdlet_FileConflictYesHelp),
new ChoiceDescription(Resources.Cmdlet_YesAll, Resources.Cmdlet_FileConflictYesAllHelp),
new ChoiceDescription(Resources.Cmdlet_No, Resources.Cmdlet_FileConflictNoHelp),
new ChoiceDescription(Resources.Cmdlet_NoAll, Resources.Cmdlet_FileConflictNoAllHelp)
};
int choice = Host.UI.PromptForChoice(VsResources.FileConflictTitle, message, choices, defaultChoice: 2);
Debug.Assert(choice >= 0 && choice < 4);
switch (choice)
{
case 0:
return FileConflictAction.Overwrite;
case 1:
_overwriteAll = true;
return FileConflictAction.OverwriteAll;
case 2:
return FileConflictAction.Ignore;
case 3:
_ignoreAll = true;
return FileConflictAction.IgnoreAll;
}
return FileConflictAction.Ignore;
}
void IErrorHandler.HandleError(ErrorRecord errorRecord, bool terminating)
{
if (terminating)
{
ThrowTerminatingError(errorRecord);
}
else
{
WriteError(errorRecord);
}
}
void IErrorHandler.HandleException(Exception exception, bool terminating,
string errorId, ErrorCategory category, object target)
{
exception = ExceptionUtility.Unwrap(exception);
var error = new ErrorRecord(exception, errorId, category, target);
ErrorHandler.HandleError(error, terminating: terminating);
}
protected void WriteLine(string message = null)
{
if (Host == null)
{
// Host is null when running unit tests. Simply return in this case
return;
}
if (message == null)
{
Host.UI.WriteLine();
}
else
{
Host.UI.WriteLine(message);
}
}
protected void WriteProgress(int activityId, string operation, int percentComplete)
{
if (IsSyncMode)
{
// don't bother to show progress if we are in synchronous mode
return;
}
ProgressRecord progressRecord;
// retrieve the ProgressRecord object for this particular activity id from the cache.
if (ProgressRecordCache.Contains(activityId))
{
progressRecord = ProgressRecordCache[activityId];
}
else
{
progressRecord = new ProgressRecord(activityId, operation, operation);
ProgressRecordCache.Add(progressRecord);
}
progressRecord.CurrentOperation = operation;
progressRecord.PercentComplete = percentComplete;
WriteProgress(progressRecord);
}
private void OnProgressAvailable(object sender, ProgressEventArgs e)
{
WriteProgress(ProgressActivityIds.DownloadPackageId, e.Operation, e.PercentComplete);
}
protected void SubscribeToProgressEvents()
{
if (!IsSyncMode && _httpClientEvents != null)
{
_httpClientEvents.ProgressAvailable += OnProgressAvailable;
}
}
protected void UnsubscribeFromProgressEvents()
{
if (_httpClientEvents != null)
{
_httpClientEvents.ProgressAvailable -= OnProgressAvailable;
}
}
[SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes", Justification = "This exception is passed to PowerShell. We really don't care about the type of exception here.")]
protected void WriteError(string message)
{
if (!String.IsNullOrEmpty(message))
{
WriteError(new Exception(message));
}
}
protected void WriteError(Exception exception)
{
ErrorHandler.HandleException(exception, terminating: false);
}
private ProgressRecordCollection ProgressRecordCache
{
get
{
if (_progressRecordCache == null)
{
_progressRecordCache = new ProgressRecordCollection();
}
return _progressRecordCache;
}
}
void IErrorHandler.WriteProjectNotFoundError(string projectName, bool terminating)
{
var notFoundException =
new ItemNotFoundException(
String.Format(
CultureInfo.CurrentCulture,
Resources.Cmdlet_ProjectNotFound, projectName));
ErrorHandler.HandleError(
new ErrorRecord(
notFoundException,
NuGetErrorId.ProjectNotFound, // This is your locale-agnostic error id.
ErrorCategory.ObjectNotFound,
projectName),
terminating: terminating);
}
void IErrorHandler.ThrowSolutionNotOpenTerminatingError()
{
ErrorHandler.HandleException(
new InvalidOperationException(Resources.Cmdlet_NoSolution),
terminating: true,
errorId: NuGetErrorId.NoActiveSolution,
category: ErrorCategory.InvalidOperation);
}
void IErrorHandler.ThrowNoCompatibleProjectsTerminatingError()
{
ErrorHandler.HandleException(
new InvalidOperationException(Resources.Cmdlet_NoCompatibleProjects),
terminating: true,
errorId: NuGetErrorId.NoCompatibleProjects,
category: ErrorCategory.InvalidOperation);
}
#endregion Logging
#region Project APIs
/// <summary>
/// Return all projects in the solution matching the provided names. Wildcards are supported.
/// This method will automatically generate error records for non-wildcarded project names that
/// are not found.
/// </summary>
/// <param name="projectNames">An array of project names that may or may not include wildcards.</param>
/// <returns>Projects matching the project name(s) provided.</returns>
protected IEnumerable<EnvDTE.Project> GetProjectsByName(string[] projectNames)
{
var allValidProjectNames = GetAllValidProjectNames().ToList();
foreach (string projectName in projectNames)
{
// if ctrl+c hit, leave immediately
if (Stopping)
{
break;
}
// Treat every name as a wildcard; results in simpler code
var pattern = new WildcardPattern(projectName, WildcardOptions.IgnoreCase);
var matches = from s in allValidProjectNames
where pattern.IsMatch(s)
select _solutionManager.GetProject(s);
int count = 0;
foreach (var project in matches)
{
count++;
yield return project;
}
// We only emit non-terminating error record if a non-wildcarded name was not found.
// This is consistent with built-in cmdlets that support wildcarded search.
// A search with a wildcard that returns nothing should not be considered an error.
if ((count == 0) && !WildcardPattern.ContainsWildcardCharacters(projectName))
{
ErrorHandler.WriteProjectNotFoundError(projectName, terminating: false);
}
}
}
/// <summary>
/// Return all projects in current solution.
/// </summary>
/// <returns></returns>
public IEnumerable<VsProject> GetAllProjectsInSolution()
{
IEnumerable<string> projectNames = GetAllValidProjectNames();
return GetProjectsByName(projectNames);
}
/// <summary>
/// Return all projects in the solution matching the provided names. Wildcards are supported.
/// This method will automatically generate error records for non-wildcarded project names that
/// are not found.
/// </summary>
/// <param name="projectNames">An array of project names that may or may not include wildcards.</param>
/// <returns>Projects matching the project name(s) provided.</returns>
protected IEnumerable<VsProject> GetProjectsByName(IEnumerable<string> projectNames)
{
var allValidProjectNames = GetAllValidProjectNames().ToList();
foreach (string projectName in projectNames)
{
// if ctrl+c hit, leave immediately
if (Stopping)
{
break;
}
// Treat every name as a wildcard; results in simpler code
var pattern = new WildcardPattern(projectName, WildcardOptions.IgnoreCase);
var matches = from s in allValidProjectNames
where pattern.IsMatch(s)
select _solutionManager.GetProject(s);
int count = 0;
foreach (var project in matches)
{
count++;
VsProject proj = Solution.GetProject(project);
yield return proj;
}
// We only emit non-terminating error record if a non-wildcarded name was not found.
// This is consistent with built-in cmdlets that support wildcarded search.
// A search with a wildcard that returns nothing should not be considered an error.
if ((count == 0) && !WildcardPattern.ContainsWildcardCharacters(projectName))
{
ErrorHandler.WriteProjectNotFoundError(projectName, terminating: false);
}
}
}
/// <summary>
/// Return all possibly valid project names in the current solution. This includes all
/// unique names and safe names.
/// </summary>
/// <returns></returns>
protected IEnumerable<string> GetAllValidProjectNames()
{
var safeNames = _solutionManager.GetProjects().Select(p => _solutionManager.GetProjectSafeName(p));
var uniqueNames = _solutionManager.GetProjects().Select(p => p.GetCustomUniqueName());
return uniqueNames.Concat(safeNames).Distinct();
}
/// <summary>
/// This method will set the default project of PowerShell Console by project name.
/// </summary>
/// <param name="projectNames">The project name to be set to.</param>
/// <returns>Boolean indicating success or failure.</returns>
protected bool SetProjectsByName(string projectName)
{
var host = PowerShellHostService.CreateHost(PowerConsoleHostName, false);
var allValidProjectNames = host.GetAvailableProjects().ToList();
string match = allValidProjectNames.Where(p => string.Equals(p, projectName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
int matchIndex;
if (string.IsNullOrEmpty(match))
{
ErrorHandler.WriteProjectNotFoundError(projectName, terminating: false);
return false;
}
else
{
try
{
matchIndex = allValidProjectNames.IndexOf(match);
host.SetDefaultProjectIndex(matchIndex);
_solutionManager.DefaultProjectName = match;
Log(Client.MessageLevel.Info, Resources.Cmdlet_ProjectSet, match);
return true;
}
catch (Exception ex)
{
WriteError(ex);
return false;
}
}
}
#endregion Project APIs
/// <summary>
/// Create a package repository from the source by trying to resolve relative paths.
/// </summary>
protected SourceRepository CreateRepositoryFromSource(string source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
UriFormatException uriException = null;
string url = _packageSourceProvider.ResolveSource(source);
try
{
PackageSource packageSource = new PackageSource(source, url);
var sourceRepo = new AutoDetectSourceRepository(packageSource, PSCommandsUserAgentClient, _repositoryFactory);
return sourceRepo;
}
catch (UriFormatException ex)
{
// if the source is relative path, it can result in invalid uri exception
uriException = ex;
}
return null;
}
public void ExecuteScript(string packageInstallPath, string scriptRelativePath, object packageObject, Installation.InstallationTarget target)
{
IPackage package = (IPackage)packageObject;
// If we don't have a project, we're at solution level
string projectName = target.Name;
FrameworkName targetFramework = target.GetSupportedFrameworks().FirstOrDefault();
VsProject targetProject = target as VsProject;
EnvDTE.Project project = targetProject == null ? null : targetProject.DteProject;
string fullPath = Path.Combine(packageInstallPath, scriptRelativePath);
if (!File.Exists(fullPath))
{
VsNuGetTraceSources.VsPowerShellScriptExecutionFeature.Error(
"missing_script",
"[{0}] Unable to locate expected script file: {1}",
projectName,
fullPath);
}
else
{
var psVariable = SessionState.PSVariable;
string toolsPath = Path.GetDirectoryName(fullPath);
// set temp variables to pass to the script
psVariable.Set("__rootPath", packageInstallPath);
psVariable.Set("__toolsPath", toolsPath);
psVariable.Set("__package", package);
psVariable.Set("__project", project);
string command = "& " + PathHelper.EscapePSPath(fullPath) + " $__rootPath $__toolsPath $__package $__project";
Log(MessageLevel.Info, String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullPath));
InvokeCommand.InvokeScript(command, false, PipelineResultTypes.Error, null, null);
// clear temp variables
psVariable.Remove("__rootPath");
psVariable.Remove("__toolsPath");
psVariable.Remove("__package");
psVariable.Remove("__project");
}
}
public void OpenFile(string fullPath)
{
var commonOperations = ServiceLocator.GetInstance<IVsCommonOperations>();
commonOperations.OpenFile(fullPath);
}
}
public class ProgressRecordCollection : KeyedCollection<int, ProgressRecord>
{
protected override int GetKeyForItem(ProgressRecord item)
{
return item.ActivityId;
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System
{
// The BitConverter class contains methods for
// converting an array of bytes to one of the base data
// types, as well as for converting a base data type to an
// array of bytes.
public static class BitConverter
{
// This field indicates the "endianess" of the architecture.
// The value is set to true if the architecture is
// little endian; false if it is big endian.
#if BIGENDIAN
[Intrinsic]
public static readonly bool IsLittleEndian /* = false */;
#else
[Intrinsic]
public static readonly bool IsLittleEndian = true;
#endif
// Converts a Boolean into an array of bytes with length one.
public static byte[] GetBytes(bool value)
{
byte[] r = new byte[1];
r[0] = (value ? (byte)1 : (byte)0);
return r;
}
// Converts a Boolean into a Span of bytes with length one.
public static bool TryWriteBytes(Span<byte> destination, bool value)
{
if (destination.Length < sizeof(byte))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value ? (byte)1 : (byte)0);
return true;
}
// Converts a char into an array of bytes with length two.
public static byte[] GetBytes(char value)
{
byte[] bytes = new byte[sizeof(char)];
Unsafe.As<byte, char>(ref bytes[0]) = value;
return bytes;
}
// Converts a char into a Span
public static bool TryWriteBytes(Span<byte> destination, char value)
{
if (destination.Length < sizeof(char))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts a short into an array of bytes with length
// two.
public static byte[] GetBytes(short value)
{
byte[] bytes = new byte[sizeof(short)];
Unsafe.As<byte, short>(ref bytes[0]) = value;
return bytes;
}
// Converts a short into a Span
public static bool TryWriteBytes(Span<byte> destination, short value)
{
if (destination.Length < sizeof(short))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts an int into an array of bytes with length
// four.
public static byte[] GetBytes(int value)
{
byte[] bytes = new byte[sizeof(int)];
Unsafe.As<byte, int>(ref bytes[0]) = value;
return bytes;
}
// Converts an int into a Span
public static bool TryWriteBytes(Span<byte> destination, int value)
{
if (destination.Length < sizeof(int))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts a long into an array of bytes with length
// eight.
public static byte[] GetBytes(long value)
{
byte[] bytes = new byte[sizeof(long)];
Unsafe.As<byte, long>(ref bytes[0]) = value;
return bytes;
}
// Converts a long into a Span
public static bool TryWriteBytes(Span<byte> destination, long value)
{
if (destination.Length < sizeof(long))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts an ushort into an array of bytes with
// length two.
[CLSCompliant(false)]
public static byte[] GetBytes(ushort value)
{
byte[] bytes = new byte[sizeof(ushort)];
Unsafe.As<byte, ushort>(ref bytes[0]) = value;
return bytes;
}
// Converts a ushort into a Span
[CLSCompliant(false)]
public static bool TryWriteBytes(Span<byte> destination, ushort value)
{
if (destination.Length < sizeof(ushort))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts an uint into an array of bytes with
// length four.
[CLSCompliant(false)]
public static byte[] GetBytes(uint value)
{
byte[] bytes = new byte[sizeof(uint)];
Unsafe.As<byte, uint>(ref bytes[0]) = value;
return bytes;
}
// Converts a uint into a Span
[CLSCompliant(false)]
public static bool TryWriteBytes(Span<byte> destination, uint value)
{
if (destination.Length < sizeof(uint))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts an unsigned long into an array of bytes with
// length eight.
[CLSCompliant(false)]
public static byte[] GetBytes(ulong value)
{
byte[] bytes = new byte[sizeof(ulong)];
Unsafe.As<byte, ulong>(ref bytes[0]) = value;
return bytes;
}
// Converts a ulong into a Span
[CLSCompliant(false)]
public static bool TryWriteBytes(Span<byte> destination, ulong value)
{
if (destination.Length < sizeof(ulong))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts a float into an array of bytes with length
// four.
public static byte[] GetBytes(float value)
{
byte[] bytes = new byte[sizeof(float)];
Unsafe.As<byte, float>(ref bytes[0]) = value;
return bytes;
}
// Converts a float into a Span
public static bool TryWriteBytes(Span<byte> destination, float value)
{
if (destination.Length < sizeof(float))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts a double into an array of bytes with length
// eight.
public static byte[] GetBytes(double value)
{
byte[] bytes = new byte[sizeof(double)];
Unsafe.As<byte, double>(ref bytes[0]) = value;
return bytes;
}
// Converts a double into a Span
public static bool TryWriteBytes(Span<byte> destination, double value)
{
if (destination.Length < sizeof(double))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts an array of bytes into a char.
public static char ToChar(byte[] value, int startIndex) => unchecked((char)ToInt16(value, startIndex));
// Converts a Span into a char
public static char ToChar(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(char))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<char>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into a short.
public static short ToInt16(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - sizeof(short))
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
return Unsafe.ReadUnaligned<short>(ref value[startIndex]);
}
// Converts a Span into a short
public static short ToInt16(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(short))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<short>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into an int.
public static int ToInt32(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - sizeof(int))
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
return Unsafe.ReadUnaligned<int>(ref value[startIndex]);
}
// Converts a Span into an int
public static int ToInt32(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(int))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<int>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into a long.
public static long ToInt64(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - sizeof(long))
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
return Unsafe.ReadUnaligned<long>(ref value[startIndex]);
}
// Converts a Span into a long
public static long ToInt64(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(long))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<long>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(byte[] value, int startIndex) => unchecked((ushort)ToInt16(value, startIndex));
// Converts a Span into a ushort
[CLSCompliant(false)]
public static ushort ToUInt16(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(ushort))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<ushort>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into an uint.
//
[CLSCompliant(false)]
public static uint ToUInt32(byte[] value, int startIndex) => unchecked((uint)ToInt32(value, startIndex));
// Convert a Span into a uint
[CLSCompliant(false)]
public static uint ToUInt32(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(uint))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<uint>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into an unsigned long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(byte[] value, int startIndex) => unchecked((ulong)ToInt64(value, startIndex));
// Converts a Span into an unsigned long
[CLSCompliant(false)]
public static ulong ToUInt64(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(ulong))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<ulong>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into a float.
public static float ToSingle(byte[] value, int startIndex) => Int32BitsToSingle(ToInt32(value, startIndex));
// Converts a Span into a float
public static float ToSingle(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(float))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<float>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into a double.
public static double ToDouble(byte[] value, int startIndex) => Int64BitsToDouble(ToInt64(value, startIndex));
// Converts a Span into a double
public static double ToDouble(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(double))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<double>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value, int startIndex, int length)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (startIndex < 0 || startIndex >= value.Length && startIndex > 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive);
if (startIndex > value.Length - length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
if (length == 0)
{
return string.Empty;
}
if (length > (int.MaxValue / 3))
{
// (int.MaxValue / 3) == 715,827,882 Bytes == 699 MB
throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, int.MaxValue / 3));
}
return string.Create(length * 3 - 1, (value, startIndex, length), (dst, state) =>
{
const string HexValues = "0123456789ABCDEF";
var src = new ReadOnlySpan<byte>(state.value, state.startIndex, state.length);
int i = 0;
int j = 0;
byte b = src[i++];
dst[j++] = HexValues[b >> 4];
dst[j++] = HexValues[b & 0xF];
while (i < src.Length)
{
b = src[i++];
dst[j++] = '-';
dst[j++] = HexValues[b >> 4];
dst[j++] = HexValues[b & 0xF];
}
});
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
return ToString(value, 0, value.Length);
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
return ToString(value, startIndex, value.Length - startIndex);
}
/*==================================ToBoolean===================================
**Action: Convert an array of bytes to a boolean value. We treat this array
** as if the first 4 bytes were an Int4 an operate on this value.
**Returns: True if the Int4 value of the first 4 bytes is non-zero.
**Arguments: value -- The byte array
** startIndex -- The position within the array.
**Exceptions: See ToInt4.
==============================================================================*/
// Converts an array of bytes into a boolean.
public static bool ToBoolean(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (startIndex < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 1)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); // differs from other overloads, which throw base ArgumentException
return value[startIndex] != 0;
}
public static bool ToBoolean(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(byte))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<byte>(ref MemoryMarshal.GetReference(value)) != 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe long DoubleToInt64Bits(double value)
{
return *((long*)&value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe double Int64BitsToDouble(long value)
{
return *((double*)&value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int SingleToInt32Bits(float value)
{
return *((int*)&value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe float Int32BitsToSingle(int value)
{
return *((float*)&value);
}
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* 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.
* - Neither the name of the openmetaverse.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.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse.StructuredData;
namespace OpenMetaverse.Packets
{
public abstract partial class Packet
{
#region Serialization/Deserialization
public static string ToXmlString(Packet packet)
{
return OSDParser.SerializeLLSDXmlString(GetLLSD(packet));
}
public static OSD GetLLSD(Packet packet)
{
OSDMap body = new OSDMap();
Type type = packet.GetType();
foreach (FieldInfo field in type.GetFields())
{
if (field.IsPublic)
{
Type blockType = field.FieldType;
if (blockType.IsArray)
{
object blockArray = field.GetValue(packet);
Array array = (Array)blockArray;
OSDArray blockList = new OSDArray(array.Length);
IEnumerator ie = array.GetEnumerator();
while (ie.MoveNext())
{
object block = ie.Current;
blockList.Add(BuildLLSDBlock(block));
}
body[field.Name] = blockList;
}
else
{
object block = field.GetValue(packet);
body[field.Name] = BuildLLSDBlock(block);
}
}
}
return body;
}
public static byte[] ToBinary(Packet packet)
{
return OSDParser.SerializeLLSDBinary(GetLLSD(packet));
}
public static Packet FromXmlString(string xml)
{
System.Xml.XmlTextReader reader =
new System.Xml.XmlTextReader(new System.IO.MemoryStream(Utils.StringToBytes(xml)));
return FromLLSD(OSDParser.DeserializeLLSDXml(reader));
}
public static Packet FromLLSD(OSD osd)
{
// FIXME: Need the inverse of the reflection magic above done here
throw new NotImplementedException();
}
#endregion Serialization/Deserialization
/// <summary>
/// Attempts to convert an LLSD structure to a known Packet type
/// </summary>
/// <param name="capsEventName">Event name, this must match an actual
/// packet name for a Packet to be successfully built</param>
/// <param name="body">LLSD to convert to a Packet</param>
/// <returns>A Packet on success, otherwise null</returns>
public static Packet BuildPacket(string capsEventName, OSDMap body)
{
Assembly assembly = Assembly.GetExecutingAssembly();
// Check if we have a subclass of packet with the same name as this event
Type type = assembly.GetType("OpenMetaverse.Packets." + capsEventName + "Packet", false);
if (type == null)
return null;
Packet packet = null;
try
{
// Create an instance of the object
packet = (Packet)Activator.CreateInstance(type);
// Iterate over all of the fields in the packet class, looking for matches in the LLSD
foreach (FieldInfo field in type.GetFields())
{
if (body.ContainsKey(field.Name))
{
Type blockType = field.FieldType;
if (blockType.IsArray)
{
OSDArray array = (OSDArray)body[field.Name];
Type elementType = blockType.GetElementType();
object[] blockArray = (object[])Array.CreateInstance(elementType, array.Count);
for (int i = 0; i < array.Count; i++)
{
OSDMap map = (OSDMap)array[i];
blockArray[i] = ParseLLSDBlock(map, elementType);
}
field.SetValue(packet, blockArray);
}
else
{
OSDMap map = (OSDMap)((OSDArray)body[field.Name])[0];
field.SetValue(packet, ParseLLSDBlock(map, blockType));
}
}
}
}
catch (Exception)
{
//FIXME Logger.Log(e.Message, Helpers.LogLevel.Error, e);
}
return packet;
}
private static object ParseLLSDBlock(OSDMap blockData, Type blockType)
{
object block = Activator.CreateInstance(blockType);
// Iterate over each field and set the value if a match was found in the LLSD
foreach (FieldInfo field in blockType.GetFields())
{
if (blockData.ContainsKey(field.Name))
{
Type fieldType = field.FieldType;
if (fieldType == typeof(ulong))
{
// ulongs come in as a byte array, convert it manually here
byte[] bytes = blockData[field.Name].AsBinary();
ulong value = Utils.BytesToUInt64(bytes);
field.SetValue(block, value);
}
else if (fieldType == typeof(uint))
{
// uints come in as a byte array, convert it manually here
byte[] bytes = blockData[field.Name].AsBinary();
uint value = Utils.BytesToUInt(bytes);
field.SetValue(block, value);
}
else if (fieldType == typeof(ushort))
{
// Just need a bit of manual typecasting love here
field.SetValue(block, (ushort)blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(byte))
{
// Just need a bit of manual typecasting love here
field.SetValue(block, (byte)blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(short))
{
field.SetValue(block, (short)blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(string))
{
field.SetValue(block, blockData[field.Name].AsString());
}
else if (fieldType == typeof(bool))
{
field.SetValue(block, blockData[field.Name].AsBoolean());
}
else if (fieldType == typeof(float))
{
field.SetValue(block, (float)blockData[field.Name].AsReal());
}
else if (fieldType == typeof(double))
{
field.SetValue(block, blockData[field.Name].AsReal());
}
else if (fieldType == typeof(int))
{
field.SetValue(block, blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(UUID))
{
field.SetValue(block, blockData[field.Name].AsUUID());
}
else if (fieldType == typeof(Vector3))
{
Vector3 vec = ((OSDArray)blockData[field.Name]).AsVector3();
field.SetValue(block, vec);
}
else if (fieldType == typeof(Vector4))
{
Vector4 vec = ((OSDArray)blockData[field.Name]).AsVector4();
field.SetValue(block, vec);
}
else if (fieldType == typeof(Quaternion))
{
Quaternion quat = ((OSDArray)blockData[field.Name]).AsQuaternion();
field.SetValue(block, quat);
}
}
}
// Additional fields come as properties, Handle those as well.
foreach (PropertyInfo property in blockType.GetProperties())
{
if (blockData.ContainsKey(property.Name))
{
OSDType proptype = blockData[property.Name].Type;
MethodInfo set = property.GetSetMethod();
if (proptype.Equals(OSDType.Binary))
{
set.Invoke(block, new object[] { blockData[property.Name].AsBinary() });
}
else
set.Invoke(block, new object[] { Utils.StringToBytes(blockData[property.Name].AsString()) });
}
}
return block;
}
private static OSD BuildLLSDBlock(object block)
{
OSDMap map = new OSDMap();
Type blockType = block.GetType();
foreach (FieldInfo field in blockType.GetFields())
{
if (field.IsPublic)
map[field.Name] = OSD.FromObject(field.GetValue(block));
}
foreach (PropertyInfo property in blockType.GetProperties())
{
if (property.Name != "Length")
{
map[property.Name] = OSD.FromObject(property.GetValue(block, null));
}
}
return map;
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A head-tracked stereoscopic virtual reality camera rig.
/// </summary>
[ExecuteInEditMode]
public class OVRCameraRig : MonoBehaviour
{
/// <summary>
/// The left eye camera.
/// </summary>
public Camera leftEyeCamera { get; private set; }
/// <summary>
/// The right eye camera.
/// </summary>
public Camera rightEyeCamera { get; private set; }
/// <summary>
/// Provides a root transform for all anchors in tracking space.
/// </summary>
public Transform trackingSpace { get; private set; }
/// <summary>
/// Always coincides with the pose of the left eye.
/// </summary>
public Transform leftEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with average of the left and right eye poses.
/// </summary>
public Transform centerEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the right eye.
/// </summary>
public Transform rightEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the tracker.
/// </summary>
public Transform trackerAnchor { get; private set; }
/// <summary>
/// Occurs when the eye pose anchors have been set.
/// </summary>
public event System.Action<OVRCameraRig> UpdatedAnchors;
private bool needsCameraConfigure;
private readonly string trackingSpaceName = "TrackingSpace";
private readonly string trackerAnchorName = "TrackerAnchor";
private readonly string eyeAnchorName = "EyeAnchor";
private readonly string legacyEyeAnchorName = "Camera";
#region Unity Messages
private void Awake()
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
needsCameraConfigure = true;
OVRManager.NativeTextureScaleModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.VirtualTextureScaleModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.EyeTextureAntiAliasingModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.EyeTextureDepthModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.EyeTextureFormatModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.MonoscopicModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.HdrModified += (prev, current) => { needsCameraConfigure = true; };
}
private void Start()
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
UpdateCameras();
//UpdateAnchors();
}
#if !UNITY_ANDROID || UNITY_EDITOR
private void LateUpdate()
#else
private void Update()
#endif
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
UpdateCameras();
//UpdateAnchors();
}
#endregion
private void UpdateAnchors()
{
bool monoscopic = OVRManager.instance.monoscopic;
OVRPose tracker = OVRManager.tracker.GetPose();
OVRPose hmdLeftEye = OVRManager.display.GetEyePose(OVREye.Left);
OVRPose hmdRightEye = OVRManager.display.GetEyePose(OVREye.Right);
trackerAnchor.localRotation = tracker.orientation;
centerEyeAnchor.localRotation = hmdLeftEye.orientation; // using left eye for now
leftEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : hmdLeftEye.orientation;
rightEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : hmdRightEye.orientation;
trackerAnchor.localPosition = tracker.position;
centerEyeAnchor.localPosition = 0.5f * (hmdLeftEye.position + hmdRightEye.position);
leftEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : hmdLeftEye.position;
rightEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : hmdRightEye.position;
if (UpdatedAnchors != null)
{
UpdatedAnchors(this);
}
}
private void UpdateCameras()
{
if (needsCameraConfigure)
{
leftEyeCamera = ConfigureCamera(OVREye.Left);
rightEyeCamera = ConfigureCamera(OVREye.Right);
#if !UNITY_ANDROID || UNITY_EDITOR
needsCameraConfigure = false;
#endif
}
}
public void EnsureGameObjectIntegrity()
{
if (trackingSpace == null)
trackingSpace = ConfigureRootAnchor(trackingSpaceName);
if (leftEyeAnchor == null)
leftEyeAnchor = ConfigureEyeAnchor(trackingSpace, OVREye.Left);
if (centerEyeAnchor == null)
centerEyeAnchor = ConfigureEyeAnchor(trackingSpace, OVREye.Center);
if (rightEyeAnchor == null)
rightEyeAnchor = ConfigureEyeAnchor(trackingSpace, OVREye.Right);
if (trackerAnchor == null)
trackerAnchor = ConfigureTrackerAnchor(trackingSpace);
if (leftEyeCamera == null)
{
leftEyeCamera = leftEyeAnchor.GetComponent<Camera>();
if (leftEyeCamera == null)
{
leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>();
}
}
if (rightEyeCamera == null)
{
rightEyeCamera = rightEyeAnchor.GetComponent<Camera>();
if (rightEyeCamera == null)
{
rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>();
}
}
#if UNITY_ANDROID && !UNITY_EDITOR
if (leftEyeCamera != null)
{
if (leftEyeCamera.GetComponent<OVRPostRender>() == null)
{
leftEyeCamera.gameObject.AddComponent<OVRPostRender>();
}
}
if (rightEyeCamera != null)
{
if (rightEyeCamera.GetComponent<OVRPostRender>() == null)
{
rightEyeCamera.gameObject.AddComponent<OVRPostRender>();
}
}
#endif
}
private Transform ConfigureRootAnchor(string name)
{
Transform root = transform.Find(name);
if (root == null)
{
root = new GameObject(name).transform;
}
root.parent = transform;
root.localScale = Vector3.one;
root.localPosition = Vector3.zero;
root.localRotation = Quaternion.identity;
return root;
}
private Transform ConfigureEyeAnchor(Transform root, OVREye eye)
{
string name = eye.ToString() + eyeAnchorName;
Transform anchor = transform.Find(root.name + "/" + name);
if (anchor == null)
{
anchor = transform.Find(name);
}
if (anchor == null)
{
string legacyName = legacyEyeAnchorName + eye.ToString();
anchor = transform.Find(legacyName);
}
if (anchor == null)
{
anchor = new GameObject(name).transform;
}
anchor.name = name;
anchor.parent = root;
anchor.localScale = Vector3.one;
anchor.localPosition = Vector3.zero;
anchor.localRotation = Quaternion.identity;
return anchor;
}
private Transform ConfigureTrackerAnchor(Transform root)
{
string name = trackerAnchorName;
Transform anchor = transform.Find(root.name + "/" + name);
if (anchor == null)
{
anchor = new GameObject(name).transform;
}
anchor.parent = root;
anchor.localScale = Vector3.one;
anchor.localPosition = Vector3.zero;
anchor.localRotation = Quaternion.identity;
return anchor;
}
private Camera ConfigureCamera(OVREye eye)
{
Transform anchor = (eye == OVREye.Left) ? leftEyeAnchor : rightEyeAnchor;
Camera cam = anchor.GetComponent<Camera>();
OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(eye);
cam.fieldOfView = eyeDesc.fov.y;
cam.aspect = eyeDesc.resolution.x / eyeDesc.resolution.y;
cam.rect = new Rect(0f, 0f, OVRManager.instance.virtualTextureScale, OVRManager.instance.virtualTextureScale);
cam.targetTexture = OVRManager.display.GetEyeTexture(eye);
cam.hdr = OVRManager.instance.hdr;
#if UNITY_ANDROID && !UNITY_EDITOR
// Enforce camera render order
cam.depth = (eye == OVREye.Left) ?
(int)RenderEventType.LeftEyeEndFrame :
(int)RenderEventType.RightEyeEndFrame;
// If we don't clear the color buffer with a glClear, tiling GPUs
// will be forced to do an "unresolve" and read back the color buffer information.
// The clear is free on PowerVR, and possibly Mali, but it is a performance cost
// on Adreno, and we would be better off if we had the ability to discard/invalidate
// the color buffer instead of clearing.
// NOTE: The color buffer is not being invalidated in skybox mode, forcing an additional,
// wasted color buffer read before the skybox is drawn.
bool hasSkybox = ((cam.clearFlags == CameraClearFlags.Skybox) &&
((cam.gameObject.GetComponent<Skybox>() != null) || (RenderSettings.skybox != null)));
cam.clearFlags = (hasSkybox) ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;
#endif
// When rendering monoscopic, we will use the left camera render for both eyes.
if (eye == OVREye.Right)
{
cam.enabled = !OVRManager.instance.monoscopic;
}
// AA is documented to have no effect in deferred, but it causes black screens.
if (cam.actualRenderingPath == RenderingPath.DeferredLighting)
OVRManager.instance.eyeTextureAntiAliasing = 0;
return cam;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
[AddComponentMenu("Path-o-logical/PoolManager/SpawnPool")]
public sealed class SpawnPool : MonoBehaviour, IEnumerable, IList<Transform>, ICollection<Transform>, IEnumerable<Transform>
{
public delegate void OnCacheDestroy(Transform trans);
public delegate void OnDestroyFinished();
public string poolName = string.Empty;
public bool matchPoolScale;
public bool matchPoolLayer;
public bool dontDestroyOnLoad;
public bool logMessages;
public List<PrefabPool> _perPrefabPoolOptions = new List<PrefabPool>();
public Dictionary<object, bool> prefabsFoldOutStates = new Dictionary<object, bool>();
[HideInInspector]
public float maxParticleDespawnTime = 60f;
public PrefabsDict prefabs = new PrefabsDict();
public Dictionary<object, bool> _editorListItemStates = new Dictionary<object, bool>();
private List<PrefabPool> _prefabPools = new List<PrefabPool>();
internal List<Transform> spawned = new List<Transform>();
private static int miEffectLayer = LayerMask.NameToLayer("Effect");
private static int miUIEffectLayer = LayerMask.NameToLayer("UIEffect");
private static int miModelLayer = LayerMask.NameToLayer("UIModel");
private static SpawnPool.OnCacheDestroy monCacheDestroy = null;
private static SpawnPool.OnDestroyFinished mOnDestroyFinished = null;
public Transform group
{
get;
private set;
}
public Dictionary<string, PrefabPool> prefabPools
{
get
{
Dictionary<string, PrefabPool> dictionary = new Dictionary<string, PrefabPool>();
foreach (PrefabPool current in this._prefabPools)
{
dictionary[current.prefabGO.name] = current;
}
return dictionary;
}
}
public Transform this[int index]
{
get
{
return this.spawned[index];
}
set
{
throw new NotImplementedException("Read-only.");
}
}
public int Count
{
get
{
return this.spawned.Count;
}
}
public bool IsReadOnly
{
get
{
throw new NotImplementedException();
}
}
[DebuggerHidden]
IEnumerator IEnumerable.GetEnumerator()
{
SpawnPool.GetEnumerator>c__Iterator9 getEnumerator>c__Iterator = new SpawnPool.GetEnumerator>c__Iterator9();
getEnumerator>c__Iterator.<>f__this = this;
return getEnumerator>c__Iterator;
}
bool ICollection<Transform>.Remove(Transform item)
{
throw new NotImplementedException();
}
private void Awake()
{
if (this.dontDestroyOnLoad)
{
UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
}
this.group = base.transform;
if (this.poolName == string.Empty)
{
this.poolName = this.group.name.Replace("Pool", string.Empty);
this.poolName = this.poolName.Replace("(Clone)", string.Empty);
}
if (this.logMessages)
{
UnityEngine.Debug.Log(string.Format("SpawnPool {0}: Initializing..", this.poolName));
}
foreach (PrefabPool current in this._perPrefabPoolOptions)
{
if (current.prefab == null)
{
if (this.logMessages)
{
UnityEngine.Debug.LogWarning(string.Format("Initialization Warning: Pool '{0}' contains a PrefabPool with no prefab reference. Skipping.", this.poolName));
}
}
else
{
current.inspectorInstanceConstructor();
this.CreatePrefabPool(current);
}
}
CachePoolManager.Pools.Add(this);
}
public void ClearSpawnCache()
{
CachePoolManager.Pools.Remove(this);
base.StopAllCoroutines();
this.spawned.Clear();
for (int i = 0; i < this._prefabPools.Count; i++)
{
PrefabPool prefabPool = this._prefabPools[i];
Transform prefab = prefabPool.prefab;
prefabPool.SelfDestruct();
if (SpawnPool.monCacheDestroy != null)
{
SpawnPool.monCacheDestroy(prefab);
}
}
this._prefabPools.Clear();
if (SpawnPool.mOnDestroyFinished != null)
{
SpawnPool.mOnDestroyFinished();
}
}
private void OnDestroy()
{
}
public void ClearSpawnPool()
{
this.spawned.Clear();
for (int i = 0; i < this._prefabPools.Count; i++)
{
PrefabPool prefabPool = this._prefabPools[i];
Transform prefab = prefabPool.prefab;
prefabPool.SelfDestruct();
if (SpawnPool.monCacheDestroy != null)
{
SpawnPool.monCacheDestroy(prefab);
}
}
this._prefabPools.Clear();
}
public void ForceClearMemory()
{
int second = DateTime.Now.Second;
for (int i = 0; i < this._prefabPools.Count; i++)
{
PrefabPool prefabPool = this._prefabPools[i];
prefabPool.ProcessTimeOutInstance();
if (prefabPool.despawned.Count == 0 && prefabPool.spawned.Count == 0)
{
Transform prefab = prefabPool.prefab;
prefabPool.SelfDestruct();
if (SpawnPool.monCacheDestroy != null)
{
SpawnPool.monCacheDestroy(prefab);
}
this._prefabPools.RemoveAt(i);
i--;
}
}
}
public void RemoveEmptyPrefabPools()
{
for (int i = 0; i < this._prefabPools.Count; i++)
{
PrefabPool prefabPool = this._prefabPools[i];
if (prefabPool != null)
{
prefabPool.ProcessTimeOutInstance();
if (prefabPool.despawned.Count == 0 && prefabPool.spawned.Count == 0 && prefabPool.fTimeSecondWhenEmpty > 0)
{
Transform prefab = prefabPool.prefab;
prefabPool.SelfDestruct();
if (SpawnPool.monCacheDestroy != null)
{
SpawnPool.monCacheDestroy(prefab);
}
this._prefabPools.RemoveAt(i);
i--;
}
}
}
}
public static void CheckEffectWatcher(GameObject oEffect)
{
if (oEffect == null)
{
return;
}
if (oEffect.layer == SpawnPool.miEffectLayer || oEffect.layer == SpawnPool.miUIEffectLayer || oEffect.layer == SpawnPool.miModelLayer)
{
EffectWatcher effectWatcher = oEffect.GetComponent<EffectWatcher>();
if (effectWatcher == null)
{
effectWatcher = oEffect.AddComponent<EffectWatcher>();
}
effectWatcher.ResetEffect();
}
}
public static void ResetEffect(GameObject oEffect)
{
if (oEffect == null)
{
return;
}
if (oEffect.layer == SpawnPool.miEffectLayer || oEffect.layer == SpawnPool.miUIEffectLayer || oEffect.layer == SpawnPool.miModelLayer)
{
NcDuplicator componentInChildren = oEffect.GetComponentInChildren<NcDuplicator>();
if (componentInChildren != null)
{
LogSystem.LogWarning(new object[]
{
oEffect.name,
" NcDuplicator cannot be replayed."
});
return;
}
NcSpriteAnimation[] componentsInChildren = oEffect.GetComponentsInChildren<NcSpriteAnimation>(true);
for (int i = 0; i < componentsInChildren.Length; i++)
{
if (componentsInChildren[i] != null)
{
componentsInChildren[i].ResetAnimation();
}
}
NcCurveAnimation[] componentsInChildren2 = oEffect.GetComponentsInChildren<NcCurveAnimation>(true);
for (int j = 0; j < componentsInChildren2.Length; j++)
{
if (componentsInChildren2[j] != null)
{
componentsInChildren2[j].ResetAnimation();
}
}
NcDelayActive[] componentsInChildren3 = oEffect.GetComponentsInChildren<NcDelayActive>(true);
for (int k = 0; k < componentsInChildren3.Length; k++)
{
if (componentsInChildren3[k] != null)
{
componentsInChildren3[k].ResetAnimation();
}
}
NcUvAnimation[] componentsInChildren4 = oEffect.GetComponentsInChildren<NcUvAnimation>(true);
for (int l = 0; l < componentsInChildren4.Length; l++)
{
if (componentsInChildren4[l] != null)
{
componentsInChildren4[l].ResetAnimation();
}
}
ParticleSystem[] componentsInChildren5 = oEffect.GetComponentsInChildren<ParticleSystem>(true);
for (int m = 0; m < componentsInChildren5.Length; m++)
{
ParticleSystem particleSystem = componentsInChildren5[m];
if (particleSystem != null)
{
particleSystem.Stop();
particleSystem.Clear();
particleSystem.time = 0f;
particleSystem.Play();
}
}
Animation[] componentsInChildren6 = oEffect.GetComponentsInChildren<Animation>(true);
for (int n = 0; n < componentsInChildren6.Length; n++)
{
Animation animation = componentsInChildren6[n];
if (!(animation == null))
{
foreach (AnimationState animationState in animation)
{
animationState.time = 0f;
}
animation.Play();
}
}
DestroyForTime[] componentsInChildren7 = oEffect.GetComponentsInChildren<DestroyForTime>(true);
for (int num = 0; num < componentsInChildren7.Length; num++)
{
DestroyForTime destroyForTime = componentsInChildren7[num];
if (!(destroyForTime == null))
{
destroyForTime.Reset();
}
}
}
}
public static void SetCacheDestroy(SpawnPool.OnCacheDestroy onCacheDestroy)
{
SpawnPool.monCacheDestroy = onCacheDestroy;
}
public static void SetDestroyFinished(SpawnPool.OnDestroyFinished callfunc)
{
SpawnPool.mOnDestroyFinished = callfunc;
}
public void CreatePrefabPool(PrefabPool prefabPool)
{
if (this.GetPrefab(prefabPool.prefab) == null)
{
prefabPool.spawnPool = this;
this._prefabPools.Add(prefabPool);
}
if (!prefabPool.preloaded)
{
if (this.logMessages)
{
UnityEngine.Debug.Log(string.Format("SpawnPool {0}: Preloading {1} {2}", this.poolName, prefabPool.preloadAmount, prefabPool.prefab.name));
}
prefabPool.PreloadInstances();
}
}
public void Add(Transform instance, string prefabName, bool despawn, bool parent)
{
foreach (PrefabPool current in this._prefabPools)
{
if (current.prefabGO == null)
{
if (this.logMessages)
{
LogSystem.LogWarning(new object[]
{
"Unexpected Error: PrefabPool.prefabGO is null"
});
}
return;
}
if (current.prefabGO.name == prefabName)
{
current.AddUnpooled(instance, despawn);
if (this.logMessages)
{
UnityEngine.Debug.Log(string.Format("SpawnPool {0}: Adding previously unpooled instance {1}", this.poolName, instance.name));
}
if (parent)
{
instance.parent = this.group;
}
if (!despawn)
{
this.spawned.Add(instance);
}
return;
}
}
if (this.logMessages)
{
LogSystem.LogWarning(new object[]
{
string.Format("SpawnPool {0}: PrefabPool {1} not found.", this.poolName, prefabName)
});
}
}
public void Add(Transform item)
{
string message = "Use SpawnPool.Spawn() to properly add items to the pool.";
throw new NotImplementedException(message);
}
public void Remove(Transform item)
{
string message = "Use Despawn() to properly manage items that should remain in the pool but be deactivated.";
throw new NotImplementedException(message);
}
public Transform Spawn(Transform prefab, Vector3 pos, Quaternion rot)
{
int i = 0;
Transform transform;
while (i < this._prefabPools.Count)
{
PrefabPool prefabPool = this._prefabPools[i];
if (prefabPool.prefabGO == prefab.gameObject)
{
transform = prefabPool.SpawnInstance(pos, rot);
if (transform == null)
{
return null;
}
if (transform.parent != this.group)
{
transform.parent = this.group;
}
this.spawned.Add(transform);
return transform;
}
else
{
i++;
}
}
PrefabPool prefabPool2 = new PrefabPool(prefab);
this.CreatePrefabPool(prefabPool2);
transform = prefabPool2.SpawnInstance(pos, rot);
transform.parent = this.group;
this.spawned.Add(transform);
return transform;
}
public bool IsCacheObject(GameObject obj)
{
return this.spawned != null && obj != null && this.spawned.Contains(obj.transform);
}
public bool IsCachePrefab(UnityEngine.Object obj)
{
GameObject gameObject = obj as GameObject;
if (gameObject == null)
{
return false;
}
for (int i = 0; i < this._prefabPools.Count; i++)
{
PrefabPool prefabPool = this._prefabPools[i];
if (prefabPool.prefabGO == gameObject)
{
return true;
}
}
return false;
}
public bool IsInDespawn(Transform trans)
{
for (int i = 0; i < this._prefabPools.Count; i++)
{
PrefabPool prefabPool = this._prefabPools[i];
if (prefabPool.despawned.Contains(trans))
{
return true;
}
}
return false;
}
public Transform Spawn(Transform prefab)
{
return this.Spawn(prefab, Vector3.zero, Quaternion.identity);
}
public ParticleEmitter Spawn(ParticleEmitter prefab, Vector3 pos, Quaternion quat)
{
Transform transform = this.Spawn(prefab.transform, pos, quat);
if (transform == null)
{
return null;
}
ParticleAnimator component = transform.GetComponent<ParticleAnimator>();
if (component != null)
{
component.autodestruct = false;
}
ParticleEmitter component2 = transform.GetComponent<ParticleEmitter>();
component2.emit = true;
base.StartCoroutine(this.ListenForEmitDespawn(component2));
return component2;
}
public ParticleSystem Spawn(ParticleSystem prefab, Vector3 pos, Quaternion quat)
{
Transform transform = this.Spawn(prefab.transform, pos, quat);
if (transform == null)
{
return null;
}
ParticleSystem component = transform.GetComponent<ParticleSystem>();
base.StartCoroutine(this.ListenForEmitDespawn(component));
return component;
}
public ParticleEmitter Spawn(ParticleEmitter prefab, Vector3 pos, Quaternion quat, string colorPropertyName, Color color)
{
Transform transform = this.Spawn(prefab.transform, pos, quat);
if (transform == null)
{
return null;
}
ParticleAnimator component = transform.GetComponent<ParticleAnimator>();
if (component != null)
{
component.autodestruct = false;
}
ParticleEmitter component2 = transform.GetComponent<ParticleEmitter>();
component2.renderer.material.SetColor(colorPropertyName, color);
component2.emit = true;
base.StartCoroutine(this.ListenForEmitDespawn(component2));
return component2;
}
private void DespawnTree(Transform xform)
{
for (int i = xform.childCount - 1; i >= 0; i--)
{
Transform child = xform.GetChild(i);
if (!(child == null))
{
this.DespawnTree(child);
}
}
if (this.IsSpawned(xform))
{
xform.parent = base.transform;
this.DespawnObject(xform);
}
}
private void DespawnObject(Transform xform)
{
bool flag = false;
for (int i = 0; i < this._prefabPools.Count; i++)
{
PrefabPool prefabPool = this._prefabPools[i];
if (prefabPool.spawned.Contains(xform))
{
flag = prefabPool.DespawnInstance(xform);
break;
}
if (prefabPool.despawned.Contains(xform))
{
if (this.logMessages)
{
LogSystem.LogWarning(new object[]
{
string.Format("SpawnPool {0}: {1} has already been despawned. You cannot despawn something more than once!", this.poolName, xform.name)
});
}
return;
}
}
if (!flag)
{
if (this.logMessages)
{
LogSystem.LogWarning(new object[]
{
string.Format("SpawnPool {0}: {1} not found in SpawnPool", this.poolName, xform.name)
});
}
return;
}
this.spawned.Remove(xform);
}
public void Despawn(Transform xform)
{
if (xform == null)
{
return;
}
this.DespawnTree(xform);
}
public void Despawn(Transform instance, float seconds)
{
base.StartCoroutine(this.DoDespawnAfterSeconds(instance, seconds));
}
[DebuggerHidden]
private IEnumerator DoDespawnAfterSeconds(Transform instance, float seconds)
{
SpawnPool.<DoDespawnAfterSeconds>c__IteratorA <DoDespawnAfterSeconds>c__IteratorA = new SpawnPool.<DoDespawnAfterSeconds>c__IteratorA();
<DoDespawnAfterSeconds>c__IteratorA.seconds = seconds;
<DoDespawnAfterSeconds>c__IteratorA.instance = instance;
<DoDespawnAfterSeconds>c__IteratorA.<$>seconds = seconds;
<DoDespawnAfterSeconds>c__IteratorA.<$>instance = instance;
<DoDespawnAfterSeconds>c__IteratorA.<>f__this = this;
return <DoDespawnAfterSeconds>c__IteratorA;
}
public void DespawnAll()
{
for (int i = 0; i < this.spawned.Count; i++)
{
Transform xform = this.spawned[i];
this.Despawn(xform);
}
}
public bool IsSpawned(Transform instance)
{
return this.spawned.Contains(instance);
}
public Transform GetPrefab(Transform prefab)
{
foreach (PrefabPool current in this._prefabPools)
{
if (current.prefabGO == null && this.logMessages)
{
LogSystem.LogWarning(new object[]
{
string.Format("SpawnPool {0}: PrefabPool.prefabGO is null", this.poolName)
});
}
if (current.prefabGO == prefab.gameObject)
{
return current.prefab;
}
}
return null;
}
public GameObject GetPrefab(GameObject prefab)
{
foreach (PrefabPool current in this._prefabPools)
{
if (current.prefabGO == null && this.logMessages)
{
LogSystem.LogWarning(new object[]
{
string.Format("SpawnPool {0}: PrefabPool.prefabGO is null", this.poolName)
});
}
if (current.prefabGO == prefab)
{
return current.prefabGO;
}
}
return null;
}
[DebuggerHidden]
private IEnumerator ListenForEmitDespawn(ParticleEmitter emitter)
{
SpawnPool.<ListenForEmitDespawn>c__IteratorB <ListenForEmitDespawn>c__IteratorB = new SpawnPool.<ListenForEmitDespawn>c__IteratorB();
<ListenForEmitDespawn>c__IteratorB.emitter = emitter;
<ListenForEmitDespawn>c__IteratorB.<$>emitter = emitter;
<ListenForEmitDespawn>c__IteratorB.<>f__this = this;
return <ListenForEmitDespawn>c__IteratorB;
}
[DebuggerHidden]
private IEnumerator ListenForEmitDespawn(ParticleSystem emitter)
{
SpawnPool.<ListenForEmitDespawn>c__IteratorC <ListenForEmitDespawn>c__IteratorC = new SpawnPool.<ListenForEmitDespawn>c__IteratorC();
<ListenForEmitDespawn>c__IteratorC.emitter = emitter;
<ListenForEmitDespawn>c__IteratorC.<$>emitter = emitter;
<ListenForEmitDespawn>c__IteratorC.<>f__this = this;
return <ListenForEmitDespawn>c__IteratorC;
}
public override string ToString()
{
List<string> list = new List<string>();
foreach (Transform current in this.spawned)
{
list.Add(current.name);
}
return string.Join(", ", list.ToArray());
}
public string ToPrefabString()
{
List<string> list = new List<string>();
foreach (PrefabPool current in this._prefabPools)
{
list.Add(current.prefab.name);
}
return string.Join(", ", list.ToArray());
}
public bool Contains(Transform item)
{
string message = "Use IsSpawned(Transform instance) instead.";
throw new NotImplementedException(message);
}
public void CopyTo(Transform[] array, int arrayIndex)
{
this.spawned.CopyTo(array, arrayIndex);
}
[DebuggerHidden]
public IEnumerator<Transform> GetEnumerator()
{
SpawnPool.<GetEnumerator>c__IteratorD <GetEnumerator>c__IteratorD = new SpawnPool.<GetEnumerator>c__IteratorD();
<GetEnumerator>c__IteratorD.<>f__this = this;
return <GetEnumerator>c__IteratorD;
}
public int IndexOf(Transform item)
{
throw new NotImplementedException();
}
public void Insert(int index, Transform item)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
}
| |
// 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 CompareScalarNotGreaterThanSingle()
{
var test = new SimpleBinaryOpTest__CompareScalarNotGreaterThanSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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__CompareScalarNotGreaterThanSingle
{
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(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
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<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, 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 Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareScalarNotGreaterThanSingle testClass)
{
var result = Sse.CompareScalarNotGreaterThan(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareScalarNotGreaterThanSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareScalarNotGreaterThan(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareScalarNotGreaterThanSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleBinaryOpTest__CompareScalarNotGreaterThanSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse.CompareScalarNotGreaterThan(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_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 = Sse.CompareScalarNotGreaterThan(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_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 = Sse.CompareScalarNotGreaterThan(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_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(Sse).GetMethod(nameof(Sse.CompareScalarNotGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarNotGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarNotGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse.CompareScalarNotGreaterThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = Sse.CompareScalarNotGreaterThan(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(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<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareScalarNotGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareScalarNotGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareScalarNotGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareScalarNotGreaterThanSingle();
var result = Sse.CompareScalarNotGreaterThan(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__CompareScalarNotGreaterThanSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = Sse.CompareScalarNotGreaterThan(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse.CompareScalarNotGreaterThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareScalarNotGreaterThan(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(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 = Sse.CompareScalarNotGreaterThan(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 = Sse.CompareScalarNotGreaterThan(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&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(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != (!(left[0] > right[0]) ? -1 : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarNotGreaterThan)}<Single>(Vector128<Single>, Vector128<Single>): {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;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Internal;
#nullable enable
namespace Microsoft.Extensions.StackTrace.Sources
{
internal class StackTraceHelper
{
public static IList<StackFrameInfo> GetFrames(Exception exception, out AggregateException? error)
{
if (exception == null)
{
error = default;
return Array.Empty<StackFrameInfo>();
}
var needFileInfo = true;
var stackTrace = new System.Diagnostics.StackTrace(exception, needFileInfo);
var stackFrames = stackTrace.GetFrames();
if (stackFrames == null)
{
error = default;
return Array.Empty<StackFrameInfo>();
}
var frames = new List<StackFrameInfo>(stackFrames.Length);
List<Exception>? exceptions = null;
for (var i = 0; i < stackFrames.Length; i++)
{
var frame = stackFrames[i];
var method = frame.GetMethod();
// Always show last stackFrame
if (!ShowInStackTrace(method) && i < stackFrames.Length - 1)
{
continue;
}
var stackFrame = new StackFrameInfo(frame.GetFileLineNumber(), frame.GetFileName(), frame, GetMethodDisplayString(frame.GetMethod()));
frames.Add(stackFrame);
}
if (exceptions != null)
{
error = new AggregateException(exceptions);
return frames;
}
error = default;
return frames;
}
internal static MethodDisplayInfo? GetMethodDisplayString(MethodBase? method)
{
// Special case: no method available
if (method == null)
{
return null;
}
// Type name
var type = method.DeclaringType;
var methodName = method.Name;
string? subMethod = null;
if (type != null && type.IsDefined(typeof(CompilerGeneratedAttribute)) &&
(typeof(IAsyncStateMachine).IsAssignableFrom(type) || typeof(IEnumerator).IsAssignableFrom(type)))
{
// Convert StateMachine methods to correct overload +MoveNext()
if (TryResolveStateMachineMethod(ref method, out type))
{
subMethod = methodName;
}
}
string? declaringTypeName = null;
// ResolveStateMachineMethod may have set declaringType to null
if (type != null)
{
declaringTypeName = TypeNameHelper.GetTypeDisplayName(type, includeGenericParameterNames: true);
}
string? genericArguments = null;
if (method.IsGenericMethod)
{
genericArguments = "<" + string.Join(", ", method.GetGenericArguments()
.Select(arg => TypeNameHelper.GetTypeDisplayName(arg, fullName: false, includeGenericParameterNames: true))) + ">";
}
// Method parameters
var parameters = method.GetParameters().Select(parameter =>
{
var parameterType = parameter.ParameterType;
var prefix = string.Empty;
if (parameter.IsOut)
{
prefix = "out";
}
else if (parameterType != null && parameterType.IsByRef)
{
prefix = "ref";
}
var parameterTypeString = "?";
if (parameterType != null)
{
if (parameterType.IsByRef)
{
parameterType = parameterType.GetElementType();
}
parameterTypeString = TypeNameHelper.GetTypeDisplayName(parameterType!, fullName: false, includeGenericParameterNames: true);
}
return new ParameterDisplayInfo
{
Prefix = prefix,
Name = parameter.Name,
Type = parameterTypeString,
};
});
var methodDisplayInfo = new MethodDisplayInfo(declaringTypeName, method.Name, genericArguments, subMethod, parameters);
return methodDisplayInfo;
}
private static bool ShowInStackTrace(MethodBase? method)
{
Debug.Assert(method != null);
// Don't show any methods marked with the StackTraceHiddenAttribute
// https://github.com/dotnet/coreclr/pull/14652
if (HasStackTraceHiddenAttribute(method))
{
return false;
}
var type = method.DeclaringType;
if (type == null)
{
return true;
}
if (HasStackTraceHiddenAttribute(type))
{
return false;
}
// Fallbacks for runtime pre-StackTraceHiddenAttribute
if (type == typeof(ExceptionDispatchInfo) && method.Name == "Throw")
{
return false;
}
else if (type == typeof(TaskAwaiter) ||
type == typeof(TaskAwaiter<>) ||
type == typeof(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter) ||
type == typeof(ConfiguredTaskAwaitable<>.ConfiguredTaskAwaiter))
{
switch (method.Name)
{
case "HandleNonSuccessAndDebuggerNotification":
case "ThrowForNonSuccess":
case "ValidateEnd":
case "GetResult":
return false;
}
}
return true;
}
private static bool TryResolveStateMachineMethod(ref MethodBase method, out Type? declaringType)
{
Debug.Assert(method != null);
Debug.Assert(method.DeclaringType != null);
declaringType = method.DeclaringType;
var parentType = declaringType.DeclaringType;
if (parentType == null)
{
return false;
}
var methods = parentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
if (methods == null)
{
return false;
}
foreach (var candidateMethod in methods)
{
var attributes = candidateMethod.GetCustomAttributes<StateMachineAttribute>();
if (attributes == null)
{
continue;
}
foreach (var asma in attributes)
{
if (asma.StateMachineType == declaringType)
{
method = candidateMethod;
declaringType = candidateMethod.DeclaringType;
// Mark the iterator as changed; so it gets the + annotation of the original method
// async statemachines resolve directly to their builder methods so aren't marked as changed
return asma is IteratorStateMachineAttribute;
}
}
}
return false;
}
private static bool HasStackTraceHiddenAttribute(MemberInfo memberInfo)
{
IList<CustomAttributeData> attributes;
try
{
// Accessing MemberInfo.GetCustomAttributesData throws for some types (such as types in dynamically generated assemblies).
// We'll skip looking up StackTraceHiddenAttributes on such types.
attributes = memberInfo.GetCustomAttributesData();
}
catch
{
return false;
}
for (var i = 0; i < attributes.Count; i++)
{
if (attributes[i].AttributeType.Name == "StackTraceHiddenAttribute")
{
return true;
}
}
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;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.Security;
using System.Runtime.CompilerServices;
namespace System.Runtime.Serialization
{
#if USE_REFEMIT
public class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext
#else
internal class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext
#endif
{
private ISerializationSurrogateProvider _serializationSurrogateProvider;
private SerializationMode _mode;
internal XmlObjectSerializerWriteContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
: base(serializer, rootTypeDataContract, dataContractResolver)
{
_mode = SerializationMode.SharedContract;
this.preserveObjectReferences = serializer.PreserveObjectReferences;
_serializationSurrogateProvider = serializer.SerializationSurrogateProvider;
}
internal XmlObjectSerializerWriteContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
: base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
{
}
internal override SerializationMode Mode
{
get { return _mode; }
}
internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract)
{
return false;
}
internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName)
{
return false;
}
internal override void WriteAnyType(XmlWriterDelegator xmlWriter, object value)
{
if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/))
xmlWriter.WriteAnyType(value);
}
internal override void WriteString(XmlWriterDelegator xmlWriter, string value)
{
if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/))
xmlWriter.WriteString(value);
}
internal override void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns)
{
if (value == null)
WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/))
xmlWriter.WriteString(value);
xmlWriter.WriteEndElementPrimitive();
}
}
internal override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value)
{
if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/))
xmlWriter.WriteBase64(value);
}
internal override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns)
{
if (value == null)
WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/))
xmlWriter.WriteBase64(value);
xmlWriter.WriteEndElementPrimitive();
}
}
internal override void WriteUri(XmlWriterDelegator xmlWriter, Uri value)
{
if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/))
xmlWriter.WriteUri(value);
}
internal override void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns)
{
if (value == null)
WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/))
xmlWriter.WriteUri(value);
xmlWriter.WriteEndElementPrimitive();
}
}
internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value)
{
if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/))
xmlWriter.WriteQName(value);
}
internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns)
{
if (value == null)
WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns);
else
{
if (ns != null && ns.Value != null && ns.Value.Length > 0)
xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns);
else
xmlWriter.WriteStartElement(name, ns);
if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/))
xmlWriter.WriteQName(value);
xmlWriter.WriteEndElement();
}
}
internal override void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
{
if (_serializationSurrogateProvider == null)
{
base.InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle);
}
else
{
InternalSerializeWithSurrogate(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle);
}
}
internal override bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
{
if (preserveObjectReferences && !this.IsGetOnlyCollection)
{
bool isNew = true;
int objectId = SerializedObjects.GetId(obj, ref isNew);
if (isNew)
xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.IdLocalName, DictionaryGlobals.SerializationNamespace, objectId);
else
{
xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, objectId);
xmlWriter.WriteAttributeBool(Globals.XsiPrefix, DictionaryGlobals.XsiNilLocalName, DictionaryGlobals.SchemaInstanceNamespace, true);
}
return !isNew;
}
return base.OnHandleReference(xmlWriter, obj, canContainCyclicReference);
}
internal override void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
{
if (preserveObjectReferences && !this.IsGetOnlyCollection)
return;
base.OnEndHandleReference(xmlWriter, obj, canContainCyclicReference);
}
internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable)
{
if (_serializationSurrogateProvider != null)
{
while (memberType.IsArray)
memberType = memberType.GetElementType();
memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType);
if (!DataContract.IsTypeSerializable(memberType))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType)));
return;
}
base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable);
}
internal override Type GetSurrogatedType(Type type)
{
if (_serializationSurrogateProvider == null)
{
return base.GetSurrogatedType(type);
}
else
{
type = DataContract.UnwrapNullableType(type);
Type surrogateType = DataContractSerializer.GetSurrogatedType(_serializationSurrogateProvider, type);
if (this.IsGetOnlyCollection && surrogateType != type)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser,
DataContract.GetClrTypeFullName(type))));
}
else
{
return surrogateType;
}
}
}
private void InternalSerializeWithSurrogate(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
{
RuntimeTypeHandle objTypeHandle = isDeclaredType ? declaredTypeHandle : obj.GetType().TypeHandle;
object oldObj = obj;
int objOldId = 0;
Type objType = Type.GetTypeFromHandle(objTypeHandle);
Type declaredType = GetSurrogatedType(Type.GetTypeFromHandle(declaredTypeHandle));
declaredTypeHandle = declaredType.TypeHandle;
obj = DataContractSerializer.SurrogateToDataContractType(_serializationSurrogateProvider, obj, declaredType, ref objType);
objTypeHandle = objType.TypeHandle;
if (oldObj != obj)
objOldId = SerializedObjects.ReassignId(0, oldObj, obj);
if (writeXsiType)
{
declaredType = Globals.TypeOfObject;
SerializeWithXsiType(xmlWriter, obj, objTypeHandle, objType, -1, declaredType.TypeHandle, declaredType);
}
else if (declaredTypeHandle.Equals(objTypeHandle))
{
DataContract contract = GetDataContract(objTypeHandle, objType);
SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle);
}
else
{
SerializeWithXsiType(xmlWriter, obj, objTypeHandle, objType, -1, declaredTypeHandle, declaredType);
}
if (oldObj != obj)
SerializedObjects.ReassignId(objOldId, obj, oldObj);
}
internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size)
{
if (preserveObjectReferences && size > -1)
xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.ArraySizeLocalName, DictionaryGlobals.SerializationNamespace, size);
}
}
}
| |
using System;
using UnityEngine;
namespace UnityStandardAssets.Vehicles.Car
{
internal enum CarDriveType
{
FrontWheelDrive,
RearWheelDrive,
FourWheelDrive
}
internal enum SpeedType
{
MPH,
KPH
}
public class CarController : MonoBehaviour
{
[SerializeField] private CarDriveType m_CarDriveType = CarDriveType.FourWheelDrive;
[SerializeField] private WheelCollider[] m_WheelColliders = new WheelCollider[4];
[SerializeField] private GameObject[] m_WheelMeshes = new GameObject[4];
[SerializeField] private WheelEffects[] m_WheelEffects = new WheelEffects[4];
[SerializeField] private Vector3 m_CentreOfMassOffset;
[SerializeField] private float m_MaximumSteerAngle;
[Range(0, 1)] [SerializeField] private float m_SteerHelper; // 0 is raw physics , 1 the car will grip in the direction it is facing
[Range(0, 1)] [SerializeField] private float m_TractionControl; // 0 is no traction control, 1 is full interference
[SerializeField] private float m_FullTorqueOverAllWheels;
[SerializeField] private float m_ReverseTorque;
[SerializeField] private float m_MaxHandbrakeTorque;
[SerializeField] private float m_Downforce = 100f;
[SerializeField] private SpeedType m_SpeedType;
[SerializeField] private float m_Topspeed = 200;
[SerializeField] private static int NoOfGears = 5;
[SerializeField] private float m_RevRangeBoundary = 1f;
[SerializeField] private float m_SlipLimit;
[SerializeField] private float m_BrakeTorque;
private Quaternion[] m_WheelMeshLocalRotations;
private Vector3 m_Prevpos, m_Pos;
private float m_SteerAngle;
private int m_GearNum;
private float m_GearFactor;
private float m_OldRotation;
private float m_CurrentTorque;
private Rigidbody m_Rigidbody;
private const float k_ReversingThreshold = 0.01f;
public bool Skidding { get; private set; }
public float BrakeInput { get; private set; }
public float CurrentSteerAngle{ get { return m_SteerAngle; }}
public float CurrentSpeed{ get { return m_Rigidbody.velocity.magnitude*2.23693629f; }}
public float MaxSpeed{get { return m_Topspeed; }}
public float Revs { get; private set; }
public float AccelInput { get; private set; }
public float jumpForce = 40000;
public float nitroForce = 40000;
public float reactionForce = 100;
public int nitroBottle = 10;
public Color color;
// Use this for initialization
private void Start()
{
m_WheelMeshLocalRotations = new Quaternion[4];
for (int i = 0; i < 4; i++)
{
m_WheelMeshLocalRotations[i] = m_WheelMeshes[i].transform.localRotation;
}
m_WheelColliders[0].attachedRigidbody.centerOfMass = m_CentreOfMassOffset;
m_MaxHandbrakeTorque = float.MaxValue;
m_Rigidbody = GetComponent<Rigidbody>();
m_CurrentTorque = m_FullTorqueOverAllWheels - (m_TractionControl*m_FullTorqueOverAllWheels);
SetColor();
}
void OnCollisionEnter (Collision col)
{
if(col.gameObject.tag == "Player")
{
gameObject.GetComponent<Rigidbody>().AddForce (reactionForce * col.relativeVelocity, ForceMode.Impulse);
}
}
private void SetColor()
{
foreach (Renderer renderer in GetComponentsInChildren<Renderer>())
{
String name = renderer.material.name;
if ("SkyCarBodyGrey (Instance)".Equals(name))
{
renderer.material.color = Color.black;
renderer.material.SetColor("_EmissionColor", color);
}
}
}
private void GearChanging()
{
float f = Mathf.Abs(CurrentSpeed/MaxSpeed);
float upgearlimit = (1/(float) NoOfGears)*(m_GearNum + 1);
float downgearlimit = (1/(float) NoOfGears)*m_GearNum;
if (m_GearNum > 0 && f < downgearlimit)
{
m_GearNum--;
}
if (f > upgearlimit && (m_GearNum < (NoOfGears - 1)))
{
m_GearNum++;
}
}
// simple function to add a curved bias towards 1 for a value in the 0-1 range
private static float CurveFactor(float factor)
{
return 1 - (1 - factor)*(1 - factor);
}
// unclamped version of Lerp, to allow value to exceed the from-to range
private static float ULerp(float from, float to, float value)
{
return (1.0f - value)*from + value*to;
}
private void CalculateGearFactor()
{
float f = (1/(float) NoOfGears);
// gear factor is a normalised representation of the current speed within the current gear's range of speeds.
// We smooth towards the 'target' gear factor, so that revs don't instantly snap up or down when changing gear.
var targetGearFactor = Mathf.InverseLerp(f*m_GearNum, f*(m_GearNum + 1), Mathf.Abs(CurrentSpeed/MaxSpeed));
m_GearFactor = Mathf.Lerp(m_GearFactor, targetGearFactor, Time.deltaTime*5f);
}
private void CalculateRevs()
{
// calculate engine revs (for display / sound)
// (this is done in retrospect - revs are not used in force/power calculations)
CalculateGearFactor();
var gearNumFactor = m_GearNum/(float) NoOfGears;
var revsRangeMin = ULerp(0f, m_RevRangeBoundary, CurveFactor(gearNumFactor));
var revsRangeMax = ULerp(m_RevRangeBoundary, 1f, gearNumFactor);
Revs = ULerp(revsRangeMin, revsRangeMax, m_GearFactor);
}
public void Jump(float j) {
if (j > 0) {
m_Rigidbody.AddForce (Vector3.up * jumpForce);
}
}
public void Nitro(float nitro, float footbrake) {
if (nitro > 0 && footbrake > 0 && nitroBottle > 0) {
m_Rigidbody.AddForce (m_Rigidbody.velocity * 250);
nitroBottle -= 2;
} else {
nitroBottle += 1;
}
}
public void Move(float steering, float accel, float footbrake, float handbrake)
{
for (int i = 0; i < 4; i++)
{
Quaternion quat;
Vector3 position;
m_WheelColliders[i].GetWorldPose(out position, out quat);
m_WheelMeshes[i].transform.position = position;
m_WheelMeshes[i].transform.rotation = quat;
}
//clamp input values
steering = Mathf.Clamp(steering, -1, 1);
AccelInput = accel = Mathf.Clamp(accel, 0, 1);
BrakeInput = footbrake = -1*Mathf.Clamp(footbrake, -1, 0);
handbrake = Mathf.Clamp(handbrake, 0, 1);
//Set the steer on the front wheels.
//Assuming that wheels 0 and 1 are the front wheels.
m_SteerAngle = steering*m_MaximumSteerAngle;
m_WheelColliders[0].steerAngle = m_SteerAngle;
m_WheelColliders[1].steerAngle = m_SteerAngle;
SteerHelper();
ApplyDrive(accel, footbrake);
CapSpeed();
//Set the handbrake.
//Assuming that wheels 2 and 3 are the rear wheels.
if (handbrake > 0f)
{
var hbTorque = handbrake*m_MaxHandbrakeTorque;
m_WheelColliders[2].brakeTorque = hbTorque;
m_WheelColliders[3].brakeTorque = hbTorque;
}
CalculateRevs();
GearChanging();
AddDownForce();
CheckForWheelSpin();
TractionControl();
}
private void CapSpeed()
{
float speed = m_Rigidbody.velocity.magnitude;
switch (m_SpeedType)
{
case SpeedType.MPH:
speed *= 2.23693629f;
if (speed > m_Topspeed)
m_Rigidbody.velocity = (m_Topspeed/2.23693629f) * m_Rigidbody.velocity.normalized;
break;
case SpeedType.KPH:
speed *= 3.6f;
if (speed > m_Topspeed)
m_Rigidbody.velocity = (m_Topspeed/3.6f) * m_Rigidbody.velocity.normalized;
break;
}
}
private void ApplyDrive(float accel, float footbrake)
{
float thrustTorque;
switch (m_CarDriveType)
{
case CarDriveType.FourWheelDrive:
thrustTorque = accel * (m_CurrentTorque / 4f);
for (int i = 0; i < 4; i++)
{
m_WheelColliders[i].motorTorque = thrustTorque;
}
break;
case CarDriveType.FrontWheelDrive:
thrustTorque = accel * (m_CurrentTorque / 2f);
m_WheelColliders[0].motorTorque = m_WheelColliders[1].motorTorque = thrustTorque;
break;
case CarDriveType.RearWheelDrive:
thrustTorque = accel * (m_CurrentTorque / 2f);
m_WheelColliders[2].motorTorque = m_WheelColliders[3].motorTorque = thrustTorque;
break;
}
for (int i = 0; i < 4; i++)
{
if (CurrentSpeed > 5 && Vector3.Angle(transform.forward, m_Rigidbody.velocity) < 50f)
{
m_WheelColliders[i].brakeTorque = m_BrakeTorque*footbrake;
}
else if (footbrake > 0)
{
m_WheelColliders[i].brakeTorque = 0f;
m_WheelColliders[i].motorTorque = -m_ReverseTorque*footbrake;
}
}
}
private void SteerHelper()
{
for (int i = 0; i < 4; i++)
{
WheelHit wheelhit;
m_WheelColliders[i].GetGroundHit(out wheelhit);
if (wheelhit.normal == Vector3.zero)
return; // wheels arent on the ground so dont realign the rigidbody velocity
}
// this if is needed to avoid gimbal lock problems that will make the car suddenly shift direction
if (Mathf.Abs(m_OldRotation - transform.eulerAngles.y) < 10f)
{
var turnadjust = (transform.eulerAngles.y - m_OldRotation) * m_SteerHelper;
Quaternion velRotation = Quaternion.AngleAxis(turnadjust, Vector3.up);
m_Rigidbody.velocity = velRotation * m_Rigidbody.velocity;
}
m_OldRotation = transform.eulerAngles.y;
}
// this is used to add more grip in relation to speed
private void AddDownForce()
{
m_WheelColliders[0].attachedRigidbody.AddForce(-transform.up*m_Downforce*
m_WheelColliders[0].attachedRigidbody.velocity.magnitude);
}
// checks if the wheels are spinning and is so does three things
// 1) emits particles
// 2) plays tiure skidding sounds
// 3) leaves skidmarks on the ground
// these effects are controlled through the WheelEffects class
private void CheckForWheelSpin()
{
// loop through all wheels
for (int i = 0; i < 4; i++)
{
WheelHit wheelHit;
m_WheelColliders[i].GetGroundHit(out wheelHit);
// is the tire slipping above the given threshhold
if (Mathf.Abs(wheelHit.forwardSlip) >= m_SlipLimit || Mathf.Abs(wheelHit.sidewaysSlip) >= m_SlipLimit)
{
m_WheelEffects[i].EmitTyreSmoke();
// avoiding all four tires screeching at the same time
// if they do it can lead to some strange audio artefacts
if (!AnySkidSoundPlaying())
{
m_WheelEffects[i].PlayAudio();
}
continue;
}
// if it wasnt slipping stop all the audio
if (m_WheelEffects[i].PlayingAudio)
{
m_WheelEffects[i].StopAudio();
}
// end the trail generation
m_WheelEffects[i].EndSkidTrail();
}
}
// crude traction control that reduces the power to wheel if the car is wheel spinning too much
private void TractionControl()
{
WheelHit wheelHit;
switch (m_CarDriveType)
{
case CarDriveType.FourWheelDrive:
// loop through all wheels
for (int i = 0; i < 4; i++)
{
m_WheelColliders[i].GetGroundHit(out wheelHit);
AdjustTorque(wheelHit.forwardSlip);
}
break;
case CarDriveType.RearWheelDrive:
m_WheelColliders[2].GetGroundHit(out wheelHit);
AdjustTorque(wheelHit.forwardSlip);
m_WheelColliders[3].GetGroundHit(out wheelHit);
AdjustTorque(wheelHit.forwardSlip);
break;
case CarDriveType.FrontWheelDrive:
m_WheelColliders[0].GetGroundHit(out wheelHit);
AdjustTorque(wheelHit.forwardSlip);
m_WheelColliders[1].GetGroundHit(out wheelHit);
AdjustTorque(wheelHit.forwardSlip);
break;
}
}
private void AdjustTorque(float forwardSlip)
{
if (forwardSlip >= m_SlipLimit && m_CurrentTorque >= 0)
{
m_CurrentTorque -= 10 * m_TractionControl;
}
else
{
m_CurrentTorque += 10 * m_TractionControl;
if (m_CurrentTorque > m_FullTorqueOverAllWheels)
{
m_CurrentTorque = m_FullTorqueOverAllWheels;
}
}
}
private bool AnySkidSoundPlaying()
{
for (int i = 0; i < 4; i++)
{
if (m_WheelEffects[i].PlayingAudio)
{
return true;
}
}
return false;
}
}
}
| |
//#define ASTAR_POOL_DEBUG //@SHOWINEDITOR Enables debugging of path pooling. Will log warnings and info messages about paths not beeing pooled correctly.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Pathfinding {
/** Provides additional traversal information to a path request.
* \see \ref turnbased
*/
public interface ITraversalProvider {
bool CanTraverse (Path path, GraphNode node);
uint GetTraversalCost (Path path, GraphNode node);
}
/** Convenience class to access the default implementation of the ITraversalProvider */
public static class DefaultITraversalProvider {
public static bool CanTraverse (Path path, GraphNode node) {
return node.Walkable && (path.enabledTags >> (int)node.Tag & 0x1) != 0;
}
public static uint GetTraversalCost (Path path, GraphNode node) {
return path.GetTagPenalty((int)node.Tag) + node.Penalty;
}
}
/** Base class for all path types */
public abstract class Path : IPathInternals {
#if ASTAR_POOL_DEBUG
private string pathTraceInfo = "";
private List<string> claimInfo = new List<string>();
~Path() {
Debug.Log("Destroying " + GetType().Name + " instance");
if (claimed.Count > 0) {
Debug.LogWarning("Pool Is Leaking. See list of claims:\n" +
"Each message below will list what objects are currently claiming the path." +
" These objects have removed their reference to the path object but has not called .Release on it (which is bad).\n" + pathTraceInfo+"\n");
for (int i = 0; i < claimed.Count; i++) {
Debug.LogWarning("- Claim "+ (i+1) + " is by a " + claimed[i].GetType().Name + "\n"+claimInfo[i]);
}
} else {
Debug.Log("Some scripts are not using pooling.\n" + pathTraceInfo + "\n");
}
}
#endif
/** Data for the thread calculating this path */
protected PathHandler pathHandler;
/** Callback to call when the path is complete.
* This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path
*/
public OnPathDelegate callback;
/** Immediate callback to call when the path is complete.
* \warning This may be called from a separate thread. Usually you do not want to use this one.
*
* \see callback
*/
public OnPathDelegate immediateCallback;
/** Returns the state of the path in the pathfinding pipeline */
internal PathState PipelineState { get; private set; }
System.Object stateLock = new object ();
/** Provides additional traversal information to a path request.
* \see \ref turnbased
*/
public ITraversalProvider traversalProvider;
/** Backing field for #CompleteState */
protected PathCompleteState completeState;
/** Current state of the path */
public PathCompleteState CompleteState {
get { return completeState; }
protected set {
// Locking is used to avoid multithreading race conditions
// in which the error state is set on the main thread to cancel the path and then a pathfinding thread marks the path as
// completed which would replace the error state (if a lock and check would not have been used).
lock (stateLock) {
// Once the path is put in the error state, it cannot be set to any other state
if (completeState != PathCompleteState.Error) completeState = value;
}
}
}
/** If the path failed, this is true.
* \see #errorLog
* \see This is equivalent to checking path.CompleteState == PathCompleteState.Error
*/
public bool error { get { return CompleteState == PathCompleteState.Error; } }
/** Additional info on why a path failed.
* \see #AstarPath.logPathResults
*/
public string errorLog { get; private set; }
/** Holds the path as a Node array. All nodes the path traverses.
* This may not be the same nodes as the post processed path traverses.
*/
public List<GraphNode> path;
/** Holds the (possibly post processed) path as a Vector3 list */
public List<Vector3> vectorPath;
/** The node currently being processed */
protected PathNode currentR;
/** How long it took to calculate this path in milliseconds */
internal float duration;
/** Number of nodes this path has searched */
internal int searchedNodes;
/** True if the path is currently pooled.
* Do not set this value. Only read. It is used internally.
*
* \see PathPool
* \version Was named 'recycled' in 3.7.5 and earlier.
*/
bool IPathInternals.Pooled { get; set; }
/** True if the path is currently recycled (i.e in the path pool).
* Do not set this value. Only read. It is used internally.
*
* \deprecated Has been renamed to 'pooled' to use more widely underestood terminology
*/
[System.Obsolete("Has been renamed to 'Pooled' to use more widely underestood terminology", true)]
internal bool recycled { get { return false; } }
/** True if the Reset function has been called.
* Used to alert users when they are doing something wrong.
*/
protected bool hasBeenReset;
/** Constraint for how to search for nodes */
public NNConstraint nnConstraint = PathNNConstraint.Default;
/** Internal linked list implementation.
* \warning This is used internally by the system. You should never change this.
*/
internal Path next;
/** Determines which heuristic to use */
public Heuristic heuristic;
/** Scale of the heuristic values.
* \see AstarPath.heuristicScale
*/
public float heuristicScale = 1F;
/** ID of this path. Used to distinguish between different paths */
internal ushort pathID { get; private set; }
/** Target to use for H score calculation. Used alongside #hTarget. */
protected GraphNode hTargetNode;
/** Target to use for H score calculations. \see Pathfinding.Node.H */
protected Int3 hTarget;
/** Which graph tags are traversable.
* This is a bitmask so -1 = all bits set = all tags traversable.
* For example, to set bit 5 to true, you would do
* \code myPath.enabledTags |= 1 << 5; \endcode
* To set it to false, you would do
* \code myPath.enabledTags &= ~(1 << 5); \endcode
*
* The Seeker has a popup field where you can set which tags to use.
* \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
* So you need to change the Seeker value via script, not set this value if you want to change it via script.
*
* \see CanTraverse
*/
public int enabledTags = -1;
/** List of zeroes to use as default tag penalties */
static readonly int[] ZeroTagPenalties = new int[32];
/** The tag penalties that are actually used.
* If manualTagPenalties is null, this will be ZeroTagPenalties
* \see tagPenalties
*/
protected int[] internalTagPenalties;
/** Tag penalties set by other scripts
* \see tagPenalties
*/
protected int[] manualTagPenalties;
/** Penalties for each tag.
* Tag 0 which is the default tag, will have added a penalty of tagPenalties[0].
* These should only be positive values since the A* algorithm cannot handle negative penalties.
* \note This array will never be null. If you try to set it to null or with a length which is not 32. It will be set to "new int[0]".
*
* \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
* So you need to change the Seeker value via script, not set this value if you want to change it via script.
*
* \see Seeker.tagPenalties
*/
public int[] tagPenalties {
get {
return manualTagPenalties;
}
set {
if (value == null || value.Length != 32) {
manualTagPenalties = null;
internalTagPenalties = ZeroTagPenalties;
} else {
manualTagPenalties = value;
internalTagPenalties = value;
}
}
}
/** True for paths that want to search all nodes and not jump over nodes as optimizations.
* This disables Jump Point Search when that is enabled to prevent e.g ConstantPath and FloodPath
* to become completely useless.
*/
internal virtual bool FloodingPath {
get {
return false;
}
}
/** Total Length of the path.
* Calculates the total length of the #vectorPath.
* Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value.
* \returns Total length of #vectorPath, if #vectorPath is null positive infinity is returned.
*/
public float GetTotalLength () {
if (vectorPath == null) return float.PositiveInfinity;
float tot = 0;
for (int i = 0; i < vectorPath.Count-1; i++) tot += Vector3.Distance(vectorPath[i], vectorPath[i+1]);
return tot;
}
/** Waits until this path has been calculated and returned.
* Allows for very easy scripting.
* \code
* IEnumerator Start () {
* var path = seeker.StartPath(transform.position, transform.position + transform.forward*10, null);
* yield return StartCoroutine(path.WaitForPath());
* // The path is calculated now
* }
* \endcode
*
* \note Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated
* while AstarPath.WaitForPath will halt all operations until the path has been calculated.
*
* \throws System.InvalidOperationException if the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function.
*
* \see #BlockUntilCalculated
* \see https://docs.unity3d.com/Manual/Coroutines.html
*/
public IEnumerator WaitForPath () {
if (PipelineState == PathState.Created) throw new System.InvalidOperationException("This path has not been started yet");
while (PipelineState != PathState.Returned) yield return null;
}
/** Blocks until this path has been calculated and returned.
* Normally it takes a few frames for a path to be calculated and returned.
* This function will ensure that the path will be calculated when this function returns
* and that the callback for that path has been called.
*
* Use this function only if you really need to.
* There is a point to spreading path calculations out over several frames.
* It smoothes out the framerate and makes sure requesting a large
* number of paths at the same time does not cause lag.
*
* \note Graph updates and other callbacks might get called during the execution of this function.
*
* \code
* Path p = seeker.StartPath (transform.position, transform.position + Vector3.forward * 10);
* p.BlockUntilCalculated();
* // The path is calculated now
* \endcode
*
* \see This is equivalent to calling AstarPath.BlockUntilCalculated(Path)
* \see WaitForPath
*/
public void BlockUntilCalculated () {
AstarPath.BlockUntilCalculated(this);
}
/** Estimated cost from the specified node to the target.
* \see https://en.wikipedia.org/wiki/A*_search_algorithm
*/
internal uint CalculateHScore (GraphNode node) {
uint h;
switch (heuristic) {
case Heuristic.Euclidean:
h = (uint)(((GetHTarget() - node.position).costMagnitude)*heuristicScale);
// Inlining this check and the return
// for each case saves an extra jump.
// This code is pretty hot
if (hTargetNode != null) {
h = System.Math.Max(h, AstarPath.active.euclideanEmbedding.GetHeuristic(node.NodeIndex, hTargetNode.NodeIndex));
}
return h;
case Heuristic.Manhattan:
Int3 p2 = node.position;
h = (uint)((System.Math.Abs(hTarget.x-p2.x) + System.Math.Abs(hTarget.y-p2.y) + System.Math.Abs(hTarget.z-p2.z))*heuristicScale);
if (hTargetNode != null) {
h = System.Math.Max(h, AstarPath.active.euclideanEmbedding.GetHeuristic(node.NodeIndex, hTargetNode.NodeIndex));
}
return h;
case Heuristic.DiagonalManhattan:
Int3 p = GetHTarget() - node.position;
p.x = System.Math.Abs(p.x);
p.y = System.Math.Abs(p.y);
p.z = System.Math.Abs(p.z);
int diag = System.Math.Min(p.x, p.z);
int diag2 = System.Math.Max(p.x, p.z);
h = (uint)((((14*diag)/10) + (diag2-diag) + p.y) * heuristicScale);
if (hTargetNode != null) {
h = System.Math.Max(h, AstarPath.active.euclideanEmbedding.GetHeuristic(node.NodeIndex, hTargetNode.NodeIndex));
}
return h;
}
return 0U;
}
/** Returns penalty for the given tag.
* \param tag A value between 0 (inclusive) and 32 (exclusive).
*/
internal uint GetTagPenalty (int tag) {
return (uint)internalTagPenalties[tag];
}
internal Int3 GetHTarget () {
return hTarget;
}
/** Returns if the node can be traversed.
* This per default equals to if the node is walkable and if the node's tag is included in #enabledTags */
internal bool CanTraverse (GraphNode node) {
// Use traversal provider if set, otherwise fall back on default behaviour
// This method is hot, but this branch is extremely well predicted so it
// doesn't affect performance much (profiling indicates it is just above
// the noise level, somewhere around 0%-0.3%)
if (traversalProvider != null)
return traversalProvider.CanTraverse(this, node);
unchecked { return node.Walkable && (enabledTags >> (int)node.Tag & 0x1) != 0; }
}
internal uint GetTraversalCost (GraphNode node) {
#if ASTAR_NO_TRAVERSAL_COST
return 0;
#else
// Use traversal provider if set, otherwise fall back on default behaviour
if (traversalProvider != null)
return traversalProvider.GetTraversalCost(this, node);
unchecked { return GetTagPenalty((int)node.Tag) + node.Penalty; }
#endif
}
/** May be called by graph nodes to get a special cost for some connections.
* Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have
* a very large area can be marked on the start and end nodes, this method will be called
* to get the actual cost for moving from the start position to its neighbours instead
* of as would otherwise be the case, from the start node's position to its neighbours.
* The position of a node and the actual start point on the node can vary quite a lot.
*
* The default behaviour of this method is to return the previous cost of the connection,
* essentiall making no change at all.
*
* This method should return the same regardless of the order of a and b.
* That is f(a,b) == f(b,a) should hold.
*
* \param a Moving from this node
* \param b Moving to this node
* \param currentCost The cost of moving between the nodes. Return this value if there is no meaningful special cost to return.
*/
internal virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) {
return currentCost;
}
/** Returns if this path is done calculating.
* \returns If #CompleteState is not \link Pathfinding.PathCompleteState.NotCalculated NotCalculated\endlink.
*
* \note The callback for the path might not have been called yet.
*
* \since Added in 3.0.8
*
* \see #Seeker.IsDone which also takes into account if the %path %callback has been called and had modifiers applied.
*/
public bool IsDone () {
return CompleteState != PathCompleteState.NotCalculated;
}
/** Threadsafe increment of the state */
void IPathInternals.AdvanceState (PathState s) {
lock (stateLock) {
PipelineState = (PathState)System.Math.Max((int)PipelineState, (int)s);
}
}
/** Returns the state of the path in the pathfinding pipeline.
* \deprecated Use the #Pathfinding.Path.PipelineState property instead
*/
[System.Obsolete("Use the 'PipelineState' property instead")]
public PathState GetState () {
return PipelineState;
}
/** Causes the path to fail and sets #errorLog to \a msg */
internal void FailWithError (string msg) {
Error();
if (errorLog != "") errorLog += "\n" + msg;
else errorLog = msg;
}
/** Logs an error.
* \deprecated Use #FailWithError instead
*/
[System.Obsolete("Use FailWithError instead")]
internal void LogError (string msg) {
Log(msg);
}
/** Appends a message to the #errorLog.
* Nothing is logged to the console.
*
* \note If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization.
*
* \deprecated Use #FailWithError instead
*/
[System.Obsolete("Use FailWithError instead")]
internal void Log (string msg) {
errorLog += msg;
}
/** Aborts the path because of an error.
* Sets #error to true.
* This function is called when an error has occurred (e.g a valid path could not be found).
* \see #FailWithError
*/
public void Error () {
CompleteState = PathCompleteState.Error;
}
/** Performs some error checking.
* Makes sure the user isn't using old code paths and that no major errors have been made.
*
* Causes the path to fail if any errors are found.
*/
private void ErrorCheck () {
if (!hasBeenReset) FailWithError("Please use the static Construct function for creating paths, do not use the normal constructors.");
if (((IPathInternals)this).Pooled) FailWithError("The path is currently in a path pool. Are you sending the path for calculation twice?");
if (pathHandler == null) FailWithError("Field pathHandler is not set. Please report this bug.");
if (PipelineState > PathState.Processing) FailWithError("This path has already been processed. Do not request a path with the same path object twice.");
}
/** Called when the path enters the pool.
* This method should release e.g pooled lists and other pooled resources
* The base version of this method releases vectorPath and path lists.
* Reset() will be called after this function, not before.
* \warning Do not call this function manually.
*/
protected virtual void OnEnterPool () {
if (vectorPath != null) Pathfinding.Util.ListPool<Vector3>.Release(ref vectorPath);
if (path != null) Pathfinding.Util.ListPool<GraphNode>.Release(ref path);
// Clear the callback to remove a potential memory leak
// while the path is in the pool (which it could be for a long time).
callback = null;
immediateCallback = null;
traversalProvider = null;
}
/** Reset all values to their default values.
*
* \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to
* override this function, resetting ALL their variables to enable pooling of paths.
* If this is not done, trying to use that path type for pooling could result in weird behaviour.
* The best way is to reset to default values the variables declared in the extended path type and then
* call the base function in inheriting types with base.Reset().
*/
protected virtual void Reset () {
#if ASTAR_POOL_DEBUG
pathTraceInfo = "This path was got from the pool or created from here (stacktrace):\n";
pathTraceInfo += System.Environment.StackTrace;
#endif
if (System.Object.ReferenceEquals(AstarPath.active, null))
throw new System.NullReferenceException("No AstarPath object found in the scene. " +
"Make sure there is one or do not create paths in Awake");
hasBeenReset = true;
PipelineState = (int)PathState.Created;
releasedNotSilent = false;
pathHandler = null;
callback = null;
immediateCallback = null;
errorLog = "";
completeState = PathCompleteState.NotCalculated;
path = Pathfinding.Util.ListPool<GraphNode>.Claim();
vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim();
currentR = null;
duration = 0;
searchedNodes = 0;
nnConstraint = PathNNConstraint.Default;
next = null;
heuristic = AstarPath.active.heuristic;
heuristicScale = AstarPath.active.heuristicScale;
enabledTags = -1;
tagPenalties = null;
pathID = AstarPath.active.GetNextPathID();
hTarget = Int3.zero;
hTargetNode = null;
traversalProvider = null;
}
/** List of claims on this path with reference objects */
private List<System.Object> claimed = new List<System.Object>();
/** True if the path has been released with a non-silent call yet.
*
* \see Release
* \see Claim
*/
private bool releasedNotSilent;
/** Claim this path (pooling).
* A claim on a path will ensure that it is not pooled.
* If you are using a path, you will want to claim it when you first get it and then release it when you will not
* use it anymore. When there are no claims on the path, it will be reset and put in a pool.
*
* This is essentially just reference counting.
*
* The object passed to this method is merely used as a way to more easily detect when pooling is not done correctly.
* It can be any object, when used from a movement script you can just pass "this". This class will throw an exception
* if you try to call Claim on the same path twice with the same object (which is usually not what you want) or
* if you try to call Release with an object that has not been used in a Claim call for that path.
* The object passed to the Claim method needs to be the same as the one you pass to this method.
*
* \see Release
* \see Pool
* \see \ref pooling
* \see https://en.wikipedia.org/wiki/Reference_counting
*/
public void Claim (System.Object o) {
if (System.Object.ReferenceEquals(o, null)) throw new System.ArgumentNullException("o");
for (int i = 0; i < claimed.Count; i++) {
// Need to use ReferenceEquals because it might be called from another thread
if (System.Object.ReferenceEquals(claimed[i], o))
throw new System.ArgumentException("You have already claimed the path with that object ("+o+"). Are you claiming the path with the same object twice?");
}
claimed.Add(o);
#if ASTAR_POOL_DEBUG
claimInfo.Add(o.ToString() + "\n\nClaimed from:\n" + System.Environment.StackTrace);
#endif
}
/** Releases the path silently (pooling).
* \deprecated Use Release(o, true) instead
*/
[System.Obsolete("Use Release(o, true) instead")]
internal void ReleaseSilent (System.Object o) {
Release(o, true);
}
/** Releases a path claim (pooling).
* Removes the claim of the path by the specified object.
* When the claim count reaches zero, the path will be pooled, all variables will be cleared and the path will be put in a pool to be used again.
* This is great for performance since fewer allocations are made.
*
* If the silent parameter is true, this method will remove the claim by the specified object
* but the path will not be pooled if the claim count reches zero unless a Release call (not silent) has been made earlier.
* This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not cause paths to be pooled.
* This enables users to skip the claim/release calls if they want without the path being pooled by the Seeker or AstarPath and
* thus causing strange bugs.
*
* \see Claim
* \see PathPool
*/
public void Release (System.Object o, bool silent = false) {
if (o == null) throw new System.ArgumentNullException("o");
for (int i = 0; i < claimed.Count; i++) {
// Need to use ReferenceEquals because it might be called from another thread
if (System.Object.ReferenceEquals(claimed[i], o)) {
claimed.RemoveAt(i);
#if ASTAR_POOL_DEBUG
claimInfo.RemoveAt(i);
#endif
if (!silent) {
releasedNotSilent = true;
}
if (claimed.Count == 0 && releasedNotSilent) {
PathPool.Pool(this);
}
return;
}
}
if (claimed.Count == 0) {
throw new System.ArgumentException("You are releasing a path which is not claimed at all (most likely it has been pooled already). " +
"Are you releasing the path with the same object ("+o+") twice?" +
"\nCheck out the documentation on path pooling for help.");
}
throw new System.ArgumentException("You are releasing a path which has not been claimed with this object ("+o+"). " +
"Are you releasing the path with the same object twice?\n" +
"Check out the documentation on path pooling for help.");
}
/** Traces the calculated path from the end node to the start.
* This will build an array (#path) of the nodes this path will pass through and also set the #vectorPath array to the #path arrays positions.
* Assumes the #vectorPath and #path are empty and not null (which will be the case for a correctly initialized path).
*/
protected virtual void Trace (PathNode from) {
// Current node we are processing
PathNode c = from;
int count = 0;
while (c != null) {
c = c.parent;
count++;
if (count > 2048) {
Debug.LogWarning("Infinite loop? >2048 node path. Remove this message if you really have that long paths (Path.cs, Trace method)");
break;
}
}
// Ensure capacities for lists
AstarProfiler.StartProfile("Check List Capacities");
if (path.Capacity < count) path.Capacity = count;
if (vectorPath.Capacity < count) vectorPath.Capacity = count;
AstarProfiler.EndProfile();
c = from;
for (int i = 0; i < count; i++) {
path.Add(c.node);
c = c.parent;
}
// Reverse
int half = count/2;
for (int i = 0; i < half; i++) {
var tmp = path[i];
path[i] = path[count-i-1];
path[count - i - 1] = tmp;
}
for (int i = 0; i < count; i++) {
vectorPath.Add((Vector3)path[i].position);
}
}
/** Writes text shared for all overrides of DebugString to the string builder.
* \see DebugString
*/
protected void DebugStringPrefix (PathLog logMode, System.Text.StringBuilder text) {
text.Append(error ? "Path Failed : " : "Path Completed : ");
text.Append("Computation Time ");
text.Append(duration.ToString(logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms "));
text.Append("Searched Nodes ").Append(searchedNodes);
if (!error) {
text.Append(" Path Length ");
text.Append(path == null ? "Null" : path.Count.ToString());
}
}
/** Writes text shared for all overrides of DebugString to the string builder.
* \see DebugString
*/
protected void DebugStringSuffix (PathLog logMode, System.Text.StringBuilder text) {
if (error) {
text.Append("\nError: ").Append(errorLog);
}
// Can only print this from the Unity thread
// since otherwise an exception might be thrown
if (logMode == PathLog.Heavy && !AstarPath.active.IsUsingMultithreading) {
text.Append("\nCallback references ");
if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine();
else text.AppendLine("NULL");
}
text.Append("\nPath Number ").Append(pathID).Append(" (unique id)");
}
/** Returns a string with information about it.
* More information is emitted when logMode == Heavy.
* An empty string is returned if logMode == None
* or logMode == OnlyErrors and this path did not fail.
*/
internal virtual string DebugString (PathLog logMode) {
if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) {
return "";
}
// Get a cached string builder for this thread
System.Text.StringBuilder text = pathHandler.DebugStringBuilder;
text.Length = 0;
DebugStringPrefix(logMode, text);
DebugStringSuffix(logMode, text);
return text.ToString();
}
/** Calls callback to return the calculated path. \see #callback */
protected virtual void ReturnPath () {
if (callback != null) {
callback(this);
}
}
/** Prepares low level path variables for calculation.
* Called before a path search will take place.
* Always called before the Prepare, Initialize and CalculateStep functions
*/
protected void PrepareBase (PathHandler pathHandler) {
//Path IDs have overflowed 65K, cleanup is needed
//Since pathIDs are handed out sequentially, we can do this
if (pathHandler.PathID > pathID) {
pathHandler.ClearPathIDs();
}
//Make sure the path has a reference to the pathHandler
this.pathHandler = pathHandler;
//Assign relevant path data to the pathHandler
pathHandler.InitializeForPath(this);
// Make sure that internalTagPenalties is an array which has the length 32
if (internalTagPenalties == null || internalTagPenalties.Length != 32)
internalTagPenalties = ZeroTagPenalties;
try {
ErrorCheck();
} catch (System.Exception e) {
FailWithError(e.Message);
}
}
/** Called before the path is started.
* Called right before Initialize
*/
protected abstract void Prepare ();
/** Always called after the path has been calculated.
* Guaranteed to be called before other paths have been calculated on
* the same thread.
* Use for cleaning up things like node tagging and similar.
*/
protected virtual void Cleanup () {}
/** Initializes the path.
* Sets up the open list and adds the first node to it
*/
protected abstract void Initialize ();
/** Calculates the until it is complete or the time has progressed past \a targetTick */
protected abstract void CalculateStep (long targetTick);
PathHandler IPathInternals.PathHandler { get { return pathHandler; } }
void IPathInternals.OnEnterPool () { OnEnterPool(); }
void IPathInternals.Reset () { Reset(); }
void IPathInternals.ReturnPath () { ReturnPath(); }
void IPathInternals.PrepareBase (PathHandler handler) { PrepareBase(handler); }
void IPathInternals.Prepare () { Prepare(); }
void IPathInternals.Cleanup () { Cleanup(); }
void IPathInternals.Initialize () { Initialize(); }
void IPathInternals.CalculateStep (long targetTick) { CalculateStep(targetTick); }
}
/** Used for hiding internal methods of the Path class */
internal interface IPathInternals {
PathHandler PathHandler { get; }
bool Pooled { get; set; }
void AdvanceState (PathState s);
void OnEnterPool ();
void Reset ();
void ReturnPath ();
void PrepareBase (PathHandler handler);
void Prepare ();
void Initialize ();
void Cleanup ();
void CalculateStep (long targetTick);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
namespace SF.Snowball
{
/// <summary>
/// This is the rev 500 of the snowball SVN trunk,
/// but modified:
/// made abstract and introduced abstract method stem to avoid expensive reflection in filter class
/// </summary>
public abstract class SnowballProgram
{
protected internal SnowballProgram()
{
current = new System.Text.StringBuilder();
SetCurrent("");
}
public abstract bool Stem();
/// <summary> Set the current string.</summary>
public virtual void SetCurrent(System.String value)
{
//// current.Replace(current.ToString(0, current.Length - 0), value_Renamed, 0, current.Length - 0);
current.Remove(0, current.Length);
current.Append(value);
cursor = 0;
limit = current.Length;
limit_backward = 0;
bra = cursor;
ket = limit;
}
/// <summary> Get the current string.</summary>
virtual public System.String GetCurrent()
{
string result = current.ToString();
// Make a new StringBuffer. If we reuse the old one, and a user of
// the library keeps a reference to the buffer returned (for example,
// by converting it to a String in a way which doesn't force a copy),
// the buffer size will not decrease, and we will risk wasting a large
// amount of memory.
// Thanks to Wolfram Esser for spotting this problem.
current = new StringBuilder();
return result;
}
// current string
protected internal System.Text.StringBuilder current;
protected internal int cursor;
protected internal int limit;
protected internal int limit_backward;
protected internal int bra;
protected internal int ket;
protected internal virtual void copy_from(SnowballProgram other)
{
current = other.current;
cursor = other.cursor;
limit = other.limit;
limit_backward = other.limit_backward;
bra = other.bra;
ket = other.ket;
}
protected internal virtual bool in_grouping(char[] s, int min, int max)
{
if (cursor >= limit)
return false;
char ch = current[cursor];
if (ch > max || ch < min)
return false;
ch -= (char) (min);
if ((s[ch >> 3] & (0x1 << (ch & 0x7))) == 0)
return false;
cursor++;
return true;
}
protected internal virtual bool in_grouping_b(char[] s, int min, int max)
{
if (cursor <= limit_backward)
return false;
char ch = current[cursor - 1];
if (ch > max || ch < min)
return false;
ch -= (char) (min);
if ((s[ch >> 3] & (0x1 << (ch & 0x7))) == 0)
return false;
cursor--;
return true;
}
protected internal virtual bool out_grouping(char[] s, int min, int max)
{
if (cursor >= limit)
return false;
char ch = current[cursor];
if (ch > max || ch < min)
{
cursor++;
return true;
}
ch -= (char) (min);
if ((s[ch >> 3] & (0x1 << (ch & 0x7))) == 0)
{
cursor++;
return true;
}
return false;
}
protected internal virtual bool out_grouping_b(char[] s, int min, int max)
{
if (cursor <= limit_backward)
return false;
char ch = current[cursor - 1];
if (ch > max || ch < min)
{
cursor--;
return true;
}
ch -= (char) (min);
if ((s[ch >> 3] & (0x1 << (ch & 0x7))) == 0)
{
cursor--;
return true;
}
return false;
}
protected internal virtual bool in_range(int min, int max)
{
if (cursor >= limit)
return false;
char ch = current[cursor];
if (ch > max || ch < min)
return false;
cursor++;
return true;
}
protected internal virtual bool in_range_b(int min, int max)
{
if (cursor <= limit_backward)
return false;
char ch = current[cursor - 1];
if (ch > max || ch < min)
return false;
cursor--;
return true;
}
protected internal virtual bool out_range(int min, int max)
{
if (cursor >= limit)
return false;
char ch = current[cursor];
if (!(ch > max || ch < min))
return false;
cursor++;
return true;
}
protected internal virtual bool out_range_b(int min, int max)
{
if (cursor <= limit_backward)
return false;
char ch = current[cursor - 1];
if (!(ch > max || ch < min))
return false;
cursor--;
return true;
}
protected internal virtual bool eq_s(int s_size, System.String s)
{
if (limit - cursor < s_size)
return false;
int i;
for (i = 0; i != s_size; i++)
{
if (current[cursor + i] != s[i])
return false;
}
cursor += s_size;
return true;
}
protected internal virtual bool eq_s_b(int s_size, System.String s)
{
if (cursor - limit_backward < s_size)
return false;
int i;
for (i = 0; i != s_size; i++)
{
if (current[cursor - s_size + i] != s[i])
return false;
}
cursor -= s_size;
return true;
}
protected internal virtual bool eq_v(System.Text.StringBuilder s)
{
return eq_s(s.Length, s.ToString());
}
protected internal virtual bool eq_v_b(System.Text.StringBuilder s)
{
return eq_s_b(s.Length, s.ToString());
}
protected internal virtual int find_among(Among[] v, int v_size)
{
int i = 0;
int j = v_size;
int c = cursor;
int l = limit;
int common_i = 0;
int common_j = 0;
bool first_key_inspected = false;
while (true)
{
int k = i + ((j - i) >> 1);
int diff = 0;
int common = common_i < common_j?common_i:common_j; // smaller
Among w = v[k];
int i2;
for (i2 = common; i2 < w.s_size; i2++)
{
if (c + common == l)
{
diff = - 1;
break;
}
diff = current[c + common] - w.s[i2];
if (diff != 0)
break;
common++;
}
if (diff < 0)
{
j = k;
common_j = common;
}
else
{
i = k;
common_i = common;
}
if (j - i <= 1)
{
if (i > 0)
break; // v->s has been inspected
if (j == i)
break; // only one item in v
// - but now we need to go round once more to get
// v->s inspected. This looks messy, but is actually
// the optimal approach.
if (first_key_inspected)
break;
first_key_inspected = true;
}
}
while (true)
{
Among w = v[i];
if (common_i >= w.s_size)
{
cursor = c + w.s_size;
if (w.method == null)
return w.result;
bool res;
try
{
System.Object resobj = w.method.Invoke(w.methodobject, (System.Object[]) new System.Object[0]);
// {{Aroush}} UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1043_3"'
res = resobj.ToString().Equals("true");
}
catch (System.Reflection.TargetInvocationException)
{
res = false;
// FIXME - debug message
}
catch (System.UnauthorizedAccessException)
{
res = false;
// FIXME - debug message
}
cursor = c + w.s_size;
if (res)
return w.result;
}
i = w.substring_i;
if (i < 0)
return 0;
}
}
// find_among_b is for backwards processing. Same comments apply
protected internal virtual int find_among_b(Among[] v, int v_size)
{
int i = 0;
int j = v_size;
int c = cursor;
int lb = limit_backward;
int common_i = 0;
int common_j = 0;
bool first_key_inspected = false;
while (true)
{
int k = i + ((j - i) >> 1);
int diff = 0;
int common = common_i < common_j?common_i:common_j;
Among w = v[k];
int i2;
for (i2 = w.s_size - 1 - common; i2 >= 0; i2--)
{
if (c - common == lb)
{
diff = - 1;
break;
}
diff = current[c - 1 - common] - w.s[i2];
if (diff != 0)
break;
common++;
}
if (diff < 0)
{
j = k;
common_j = common;
}
else
{
i = k;
common_i = common;
}
if (j - i <= 1)
{
if (i > 0)
break;
if (j == i)
break;
if (first_key_inspected)
break;
first_key_inspected = true;
}
}
while (true)
{
Among w = v[i];
if (common_i >= w.s_size)
{
cursor = c - w.s_size;
if (w.method == null)
return w.result;
bool res;
try
{
System.Object resobj = w.method.Invoke(w.methodobject, (System.Object[]) new System.Object[0]);
// {{Aroush}} UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1043_3"'
res = resobj.ToString().Equals("true");
}
catch (System.Reflection.TargetInvocationException)
{
res = false;
// FIXME - debug message
}
catch (System.UnauthorizedAccessException)
{
res = false;
// FIXME - debug message
}
cursor = c - w.s_size;
if (res)
return w.result;
}
i = w.substring_i;
if (i < 0)
return 0;
}
}
/* to replace chars between c_bra and c_ket in current by the
* chars in s.
*/
protected internal virtual int replace_s(int c_bra, int c_ket, System.String s)
{
int adjustment = s.Length - (c_ket - c_bra);
if (current.Length > bra)
current.Replace(current.ToString(bra, ket - bra), s, bra, ket - bra);
else
current.Append(s);
limit += adjustment;
if (cursor >= c_ket)
cursor += adjustment;
else if (cursor > c_bra)
cursor = c_bra;
return adjustment;
}
protected internal virtual void slice_check()
{
if (bra < 0 || bra > ket || ket > limit || limit > current.Length)
// this line could be removed
{
System.Console.Error.WriteLine("faulty slice operation");
// FIXME: report error somehow.
/*
fprintf(stderr, "faulty slice operation:\n");
debug(z, -1, 0);
exit(1);
*/
}
}
protected internal virtual void slice_from(System.String s)
{
slice_check();
replace_s(bra, ket, s);
}
protected internal virtual void slice_from(System.Text.StringBuilder s)
{
slice_from(s.ToString());
}
protected internal virtual void slice_del()
{
slice_from("");
}
protected internal virtual void insert(int c_bra, int c_ket, System.String s)
{
int adjustment = replace_s(c_bra, c_ket, s);
if (c_bra <= bra)
bra += adjustment;
if (c_bra <= ket)
ket += adjustment;
}
protected internal virtual void insert(int c_bra, int c_ket, System.Text.StringBuilder s)
{
insert(c_bra, c_ket, s.ToString());
}
/* Copy the slice into the supplied StringBuffer */
protected internal virtual System.Text.StringBuilder slice_to(System.Text.StringBuilder s)
{
slice_check();
int len = ket - bra;
//// s.Replace(s.ToString(0, s.Length - 0), current.ToString(bra, ket), 0, s.Length - 0);
s.Remove(0, s.Length);
s.Append(current.ToString(bra, len));
return s;
}
protected internal virtual System.Text.StringBuilder assign_to(System.Text.StringBuilder s)
{
//// s.Replace(s.ToString(0, s.Length - 0), current.ToString(0, limit), 0, s.Length - 0);
s.Remove(0, s.Length);
s.Append(current.ToString(0, limit));
return s;
}
/*
extern void debug(struct SN_env * z, int number, int line_count)
{ int i;
int limit = SIZE(z->p);
//if (number >= 0) printf("%3d (line %4d): '", number, line_count);
if (number >= 0) printf("%3d (line %4d): [%d]'", number, line_count,limit);
for (i = 0; i <= limit; i++)
{ if (z->lb == i) printf("{");
if (z->bra == i) printf("[");
if (z->c == i) printf("|");
if (z->ket == i) printf("]");
if (z->l == i) printf("}");
if (i < limit)
{ int ch = z->p[i];
if (ch == 0) ch = '#';
printf("%c", ch);
}
}
printf("'\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;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Net.Security;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class OpenSsl
{
private static readonly Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate;
private unsafe static readonly Ssl.SslCtxSetAlpnCallback s_alpnServerCallback = AlpnServerSelectCallback;
private static readonly IdnMapping s_idnMapping = new IdnMapping();
#region internal methods
internal static SafeChannelBindingHandle QueryChannelBinding(SafeSslHandle context, ChannelBindingKind bindingType)
{
Debug.Assert(
bindingType != ChannelBindingKind.Endpoint,
"Endpoint binding should be handled by EndpointChannelBindingToken");
SafeChannelBindingHandle bindingHandle;
switch (bindingType)
{
case ChannelBindingKind.Unique:
bindingHandle = new SafeChannelBindingHandle(bindingType);
QueryUniqueChannelBinding(context, bindingHandle);
break;
default:
// Keeping parity with windows, we should return null in this case.
bindingHandle = null;
break;
}
return bindingHandle;
}
internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, SslAuthenticationOptions sslAuthenticationOptions)
{
SafeSslHandle context = null;
// Always use SSLv23_method, regardless of protocols. It supports negotiating to the highest
// mutually supported version and can thus handle any of the set protocols, and we then use
// SetProtocolOptions to ensure we only allow the ones requested.
using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(Ssl.SslMethods.SSLv23_method))
{
if (innerContext.IsInvalid)
{
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
// TLS 1.3 uses different ciphersuite restrictions than previous versions.
// It has no equivalent to a NoEncryption option.
if (policy == EncryptionPolicy.NoEncryption)
{
if (protocols == SslProtocols.None)
{
protocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
}
else
{
protocols &= ~SslProtocols.Tls13;
if (protocols == SslProtocols.None)
{
throw new SslException(
SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy));
}
}
}
// Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just
// create the handle, it's rooted by the using, no one else has a reference to it, etc.
Ssl.SetProtocolOptions(innerContext.DangerousGetHandle(), protocols);
// The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet
// shutdown (we aren't negotiating for session close to enable later session
// restoration).
//
// If you find yourself wanting to remove this line to enable bidirectional
// close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect().
// https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html
Ssl.SslCtxSetQuietShutdown(innerContext);
if (!Ssl.SetEncryptionPolicy(innerContext, policy))
{
Crypto.ErrClearError();
throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy));
}
bool hasCertificateAndKey =
certHandle != null && !certHandle.IsInvalid
&& certKeyHandle != null && !certKeyHandle.IsInvalid;
if (hasCertificateAndKey)
{
SetSslCertificate(innerContext, certHandle, certKeyHandle);
}
if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired)
{
Ssl.SslCtxSetVerify(innerContext, s_verifyClientCertificate);
}
GCHandle alpnHandle = default;
try
{
if (sslAuthenticationOptions.ApplicationProtocols != null)
{
if (sslAuthenticationOptions.IsServer)
{
alpnHandle = GCHandle.Alloc(sslAuthenticationOptions.ApplicationProtocols);
Interop.Ssl.SslCtxSetAlpnSelectCb(innerContext, s_alpnServerCallback, GCHandle.ToIntPtr(alpnHandle));
}
else
{
if (Interop.Ssl.SslCtxSetAlpnProtos(innerContext, sslAuthenticationOptions.ApplicationProtocols) != 0)
{
throw CreateSslException(SR.net_alpn_config_failed);
}
}
}
context = SafeSslHandle.Create(innerContext, sslAuthenticationOptions.IsServer);
Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create");
if (context.IsInvalid)
{
context.Dispose();
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
if (!sslAuthenticationOptions.IsServer)
{
// The IdnMapping converts unicode input into the IDNA punycode sequence.
string punyCode = s_idnMapping.GetAscii(sslAuthenticationOptions.TargetHost);
// Similar to windows behavior, set SNI on openssl by default for client context, ignore errors.
if (!Ssl.SslSetTlsExtHostName(context, punyCode))
{
Crypto.ErrClearError();
}
}
if (hasCertificateAndKey)
{
bool hasCertReference = false;
try
{
certHandle.DangerousAddRef(ref hasCertReference);
using (X509Certificate2 cert = new X509Certificate2(certHandle.DangerousGetHandle()))
{
X509Chain chain = null;
try
{
chain = TLSCertificateExtensions.BuildNewChain(cert, includeClientApplicationPolicy: false);
if (chain != null && !Ssl.AddExtraChainCertificates(context, chain))
{
throw CreateSslException(SR.net_ssl_use_cert_failed);
}
}
finally
{
if (chain != null)
{
int elementsCount = chain.ChainElements.Count;
for (int i = 0; i < elementsCount; i++)
{
chain.ChainElements[i].Certificate.Dispose();
}
chain.Dispose();
}
}
}
}
finally
{
if (hasCertReference)
certHandle.DangerousRelease();
}
}
context.AlpnHandle = alpnHandle;
}
catch
{
if (alpnHandle.IsAllocated)
{
alpnHandle.Free();
}
throw;
}
}
return context;
}
internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount)
{
sendBuf = null;
sendCount = 0;
if ((recvBuf != null) && (recvCount > 0))
{
if (BioWrite(context.InputBio, recvBuf, recvOffset, recvCount) <= 0)
{
// Make sure we clear out the error that is stored in the queue
throw Crypto.CreateOpenSslCryptographicException();
}
}
int retVal = Ssl.SslDoHandshake(context);
if (retVal != 1)
{
Exception innerError;
Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError);
if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ))
{
throw new SslException(SR.Format(SR.net_ssl_handshake_failed_error, error), innerError);
}
}
sendCount = Crypto.BioCtrlPending(context.OutputBio);
if (sendCount > 0)
{
sendBuf = new byte[sendCount];
try
{
sendCount = BioRead(context.OutputBio, sendBuf, sendCount);
}
finally
{
if (sendCount <= 0)
{
// Make sure we clear out the error that is stored in the queue
Crypto.ErrClearError();
sendBuf = null;
sendCount = 0;
}
}
}
bool stateOk = Ssl.IsSslStateOK(context);
if (stateOk)
{
context.MarkHandshakeCompleted();
}
return stateOk;
}
internal static int Encrypt(SafeSslHandle context, ReadOnlyMemory<byte> input, ref byte[] output, out Ssl.SslErrorCode errorCode)
{
#if DEBUG
ulong assertNoError = Crypto.ErrPeekError();
Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error.");
#endif
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal;
unsafe
{
using (MemoryHandle handle = input.Pin())
{
retVal = Ssl.SslWrite(context, (byte*)handle.Pointer, input.Length);
}
}
if (retVal != input.Length)
{
errorCode = GetSslError(context, retVal, out Exception innerError);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
break;
default:
throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
}
}
else
{
int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);
if (output == null || output.Length < capacityNeeded)
{
output = new byte[capacityNeeded];
}
retVal = BioRead(context.OutputBio, output, capacityNeeded);
if (retVal <= 0)
{
// Make sure we clear out the error that is stored in the queue
Crypto.ErrClearError();
}
}
return retVal;
}
internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int offset, int count, out Ssl.SslErrorCode errorCode)
{
#if DEBUG
ulong assertNoError = Crypto.ErrPeekError();
Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error.");
#endif
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal = BioWrite(context.InputBio, outBuffer, offset, count);
if (retVal == count)
{
unsafe
{
fixed (byte* fixedBuffer = outBuffer)
{
retVal = Ssl.SslRead(context, fixedBuffer + offset, outBuffer.Length);
}
}
if (retVal > 0)
{
count = retVal;
}
}
if (retVal != count)
{
Exception innerError;
errorCode = GetSslError(context, retVal, out innerError);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
break;
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
// update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ
errorCode = Ssl.IsSslRenegotiatePending(context) ?
Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE :
Ssl.SslErrorCode.SSL_ERROR_WANT_READ;
break;
default:
throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError);
}
}
return retVal;
}
internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context)
{
return Ssl.SslGetPeerCertificate(context);
}
internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context)
{
return Ssl.SslGetPeerCertChain(context);
}
#endregion
#region private methods
private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
{
bool sessionReused = Ssl.SslSessionReused(context);
int certHashLength = context.IsServer ^ sessionReused ?
Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) :
Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length);
if (0 == certHashLength)
{
throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed);
}
bindingHandle.SetCertHashLength(certHashLength);
}
private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr)
{
// Full validation is handled after the handshake in VerifyCertificateProperties and the
// user callback. It's also up to those handlers to decide if a null certificate
// is appropriate. So just return success to tell OpenSSL that the cert is acceptable,
// we'll process it after the handshake finishes.
const int OpenSslSuccess = 1;
return OpenSslSuccess;
}
private static unsafe int AlpnServerSelectCallback(IntPtr ssl, out byte* outp, out byte outlen, byte* inp, uint inlen, IntPtr arg)
{
outp = null;
outlen = 0;
GCHandle protocolHandle = GCHandle.FromIntPtr(arg);
if (!(protocolHandle.Target is List<SslApplicationProtocol> protocolList))
{
return Ssl.SSL_TLSEXT_ERR_ALERT_FATAL;
}
try
{
for (int i = 0; i < protocolList.Count; i++)
{
var clientList = new Span<byte>(inp, (int)inlen);
while (clientList.Length > 0)
{
byte length = clientList[0];
Span<byte> clientProto = clientList.Slice(1, length);
if (clientProto.SequenceEqual(protocolList[i].Protocol.Span))
{
fixed (byte* p = &MemoryMarshal.GetReference(clientProto)) outp = p;
outlen = length;
return Ssl.SSL_TLSEXT_ERR_OK;
}
clientList = clientList.Slice(1 + length);
}
}
}
catch
{
// No common application protocol was negotiated, set the target on the alpnHandle to null.
// It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed.
protocolHandle.Target = null;
return Ssl.SSL_TLSEXT_ERR_ALERT_FATAL;
}
// No common application protocol was negotiated, set the target on the alpnHandle to null.
// It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed.
protocolHandle.Target = null;
return Ssl.SSL_TLSEXT_ERR_ALERT_FATAL;
}
private static int BioRead(SafeBioHandle bio, byte[] buffer, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= count);
int bytes = Crypto.BioRead(bio, buffer, count);
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_read_bio_failed_error);
}
return bytes;
}
private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
int bytes;
unsafe
{
fixed (byte* bufPtr = buffer)
{
bytes = Ssl.BioWrite(bio, bufPtr + offset, count);
}
}
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_write_bio_failed_error);
}
return bytes;
}
private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception innerError)
{
ErrorInfo lastErrno = Sys.GetLastErrorInfo(); // cache it before we make more P/Invoke calls, just in case we need it
Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result);
switch (retVal)
{
case Ssl.SslErrorCode.SSL_ERROR_SYSCALL:
// Some I/O error occurred
innerError =
Crypto.ErrPeekError() != 0 ? Crypto.CreateOpenSslCryptographicException() : // crypto error queue not empty
result == 0 ? new EndOfStreamException() : // end of file that violates protocol
result == -1 && lastErrno.Error != Error.SUCCESS ? new IOException(lastErrno.GetErrorMessage(), lastErrno.RawErrno) : // underlying I/O error
null; // no additional info available
break;
case Ssl.SslErrorCode.SSL_ERROR_SSL:
// OpenSSL failure occurred. The error queue contains more details, when building the exception the queue will be cleared.
innerError = Interop.Crypto.CreateOpenSslCryptographicException();
break;
default:
// No additional info available.
innerError = null;
break;
}
return retVal;
}
private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr)
{
Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid");
Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid");
int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_cert_failed);
}
retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_private_key_failed);
}
//check private key
retVal = Ssl.SslCtxCheckPrivateKey(contextPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_check_private_key_failed);
}
}
internal static SslException CreateSslException(string message)
{
// Capture last error to be consistent with CreateOpenSslCryptographicException
ulong errorVal = Crypto.ErrPeekLastError();
Crypto.ErrClearError();
string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal)));
return new SslException(msg, (int)errorVal);
}
#endregion
#region Internal class
internal sealed class SslException : Exception
{
public SslException(string inputMessage)
: base(inputMessage)
{
}
public SslException(string inputMessage, Exception ex)
: base(inputMessage, ex)
{
}
public SslException(string inputMessage, int error)
: this(inputMessage)
{
HResult = error;
}
public SslException(int error)
: this(SR.Format(SR.net_generic_operation_failed, error))
{
HResult = error;
}
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tenancy_config/rpc/property_svc.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 HOLMS.Types.TenancyConfig.RPC {
/// <summary>Holder for reflection information generated from tenancy_config/rpc/property_svc.proto</summary>
public static partial class PropertySvcReflection {
#region Descriptor
/// <summary>File descriptor for tenancy_config/rpc/property_svc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PropertySvcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiV0ZW5hbmN5X2NvbmZpZy9ycGMvcHJvcGVydHlfc3ZjLnByb3RvEh5ob2xt",
"cy50eXBlcy50ZW5hbmN5X2NvbmZpZy5ycGMaKnByaW1pdGl2ZS9zZXJ2ZXJf",
"YWN0aW9uX2NvbmZpcm1hdGlvbi5wcm90bxobZ29vZ2xlL3Byb3RvYnVmL2Vt",
"cHR5LnByb3RvGiJ0ZW5hbmN5X2NvbmZpZy9mdWxsX3Byb3BlcnR5LnByb3Rv",
"Gh10ZW5hbmN5X2NvbmZpZy9wcm9wZXJ0eS5wcm90bxoydGVuYW5jeV9jb25m",
"aWcvaW5kaWNhdG9ycy9wcm9wZXJ0eV9pbmRpY2F0b3IucHJvdG8aNnRlbmFu",
"Y3lfY29uZmlnL3Byb3BlcnR5X2NvbmZpcm1hdGlvbl9sZXR0ZXJfdGV4dC5w",
"cm90bxo2dGVuYW5jeV9jb25maWcvcHJvcGVydHlfY2FuY2VsbGF0aW9uX2xl",
"dHRlcl90ZXh0LnByb3RvGjF0ZW5hbmN5X2NvbmZpZy9wcm9wZXJ0eV9hcnJp",
"dmFsX2xldHRlcl90ZXh0LnByb3RvGjF0ZW5hbmN5X2NvbmZpZy9wcm9wZXJ0",
"eV9lbWFpbF9zZW5kZXJfY29uZmlnLnByb3RvIlIKFlByb3BlcnR5U3ZjQWxs",
"UmVzcG9uc2USOAoKcHJvcGVydGllcxgBIAMoCzIkLmhvbG1zLnR5cGVzLnRl",
"bmFuY3lfY29uZmlnLlByb3BlcnR5IloKGlByb3BlcnR5U3ZjQWxsRnVsbFJl",
"c3BvbnNlEjwKCnByb3BlcnRpZXMYASADKAsyKC5ob2xtcy50eXBlcy50ZW5h",
"bmN5X2NvbmZpZy5GdWxsUHJvcGVydHkihQEKH1Byb3BlcnR5U3ZjQWNjcnVl",
"UmV2ZW51ZVJlcXVlc3QSSgoIcHJvcGVydHkYASABKAsyOC5ob2xtcy50eXBl",
"cy50ZW5hbmN5X2NvbmZpZy5pbmRpY2F0b3JzLlByb3BlcnR5SW5kaWNhdG9y",
"EhYKDnJ1bl9ldmVyeV9taW5zGAIgASgNInAKI0dldEFsbENvbmZpcm1hdGlv",
"bkJvZHlUZXh0c1Jlc3BvbnNlEkkKBXRleHRzGAEgAygLMjouaG9sbXMudHlw",
"ZXMudGVuYW5jeV9jb25maWcuUHJvcGVydHlDb25maXJtYXRpb25MZXR0ZXJU",
"ZXh0InAKI0dldEFsbENhbmNlbGxhdGlvbkJvZHlUZXh0c1Jlc3BvbnNlEkkK",
"BXRleHRzGAEgAygLMjouaG9sbXMudHlwZXMudGVuYW5jeV9jb25maWcuUHJv",
"cGVydHlDYW5jZWxsYXRpb25MZXR0ZXJUZXh0ImYKHkdldEFsbEFycml2YWxC",
"b2R5VGV4dHNSZXNwb25zZRJECgV0ZXh0cxgBIAMoCzI1LmhvbG1zLnR5cGVz",
"LnRlbmFuY3lfY29uZmlnLlByb3BlcnR5QXJyaXZhbExldHRlclRleHQiagog",
"R2V0QWxsRW1haWxTZW5kZXJDb25maWdzUmVzcG9uc2USRgoHY29uZmlncxgB",
"IAMoCzI1LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLlByb3BlcnR5RW1h",
"aWxTZW5kZXJDb25maWcy9BEKC1Byb3BlcnR5U3ZjElUKA0FsbBIWLmdvb2ds",
"ZS5wcm90b2J1Zi5FbXB0eRo2LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmln",
"LnJwYy5Qcm9wZXJ0eVN2Y0FsbFJlc3BvbnNlEmkKB0dldEJ5SWQSOC5ob2xt",
"cy50eXBlcy50ZW5hbmN5X2NvbmZpZy5pbmRpY2F0b3JzLlByb3BlcnR5SW5k",
"aWNhdG9yGiQuaG9sbXMudHlwZXMudGVuYW5jeV9jb25maWcuUHJvcGVydHkS",
"VAoGQ3JlYXRlEiQuaG9sbXMudHlwZXMudGVuYW5jeV9jb25maWcuUHJvcGVy",
"dHkaJC5ob2xtcy50eXBlcy50ZW5hbmN5X2NvbmZpZy5Qcm9wZXJ0eRJUCgZV",
"cGRhdGUSJC5ob2xtcy50eXBlcy50ZW5hbmN5X2NvbmZpZy5Qcm9wZXJ0eRok",
"LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLlByb3BlcnR5El8KBkRlbGV0",
"ZRIkLmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLlByb3BlcnR5Gi8uaG9s",
"bXMudHlwZXMucHJpbWl0aXZlLlNlcnZlckFjdGlvbkNvbmZpcm1hdGlvbhJd",
"CgdBbGxGdWxsEhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5GjouaG9sbXMudHlw",
"ZXMudGVuYW5jeV9jb25maWcucnBjLlByb3BlcnR5U3ZjQWxsRnVsbFJlc3Bv",
"bnNlEnUKD0dldEZ1bGxQcm9wZXJ0eRI4LmhvbG1zLnR5cGVzLnRlbmFuY3lf",
"Y29uZmlnLmluZGljYXRvcnMuUHJvcGVydHlJbmRpY2F0b3IaKC5ob2xtcy50",
"eXBlcy50ZW5hbmN5X2NvbmZpZy5GdWxsUHJvcGVydHkSaAoNQWNjcnVlUmV2",
"ZW51ZRI/LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLnJwYy5Qcm9wZXJ0",
"eVN2Y0FjY3J1ZVJldmVudWVSZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVmLkVt",
"cHR5EnoKG0dldEFsbENvbmZpcm1hdGlvbkJvZHlUZXh0cxIWLmdvb2dsZS5w",
"cm90b2J1Zi5FbXB0eRpDLmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLnJw",
"Yy5HZXRBbGxDb25maXJtYXRpb25Cb2R5VGV4dHNSZXNwb25zZRKPAQoXR2V0",
"Q29uZmlybWF0aW9uQm9keVRleHQSOC5ob2xtcy50eXBlcy50ZW5hbmN5X2Nv",
"bmZpZy5pbmRpY2F0b3JzLlByb3BlcnR5SW5kaWNhdG9yGjouaG9sbXMudHlw",
"ZXMudGVuYW5jeV9jb25maWcuUHJvcGVydHlDb25maXJtYXRpb25MZXR0ZXJU",
"ZXh0EnUKH1NldFByb3BlcnR5Q29uZmlybWF0aW9uQm9keVRleHQSOi5ob2xt",
"cy50eXBlcy50ZW5hbmN5X2NvbmZpZy5Qcm9wZXJ0eUNvbmZpcm1hdGlvbkxl",
"dHRlclRleHQaFi5nb29nbGUucHJvdG9idWYuRW1wdHkScAoWR2V0QWxsQXJy",
"aXZhbEJvZHlUZXh0cxIWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eRo+LmhvbG1z",
"LnR5cGVzLnRlbmFuY3lfY29uZmlnLnJwYy5HZXRBbGxBcnJpdmFsQm9keVRl",
"eHRzUmVzcG9uc2UShQEKEkdldEFycml2YWxCb2R5VGV4dBI4LmhvbG1zLnR5",
"cGVzLnRlbmFuY3lfY29uZmlnLmluZGljYXRvcnMuUHJvcGVydHlJbmRpY2F0",
"b3IaNS5ob2xtcy50eXBlcy50ZW5hbmN5X2NvbmZpZy5Qcm9wZXJ0eUFycml2",
"YWxMZXR0ZXJUZXh0EmsKGlNldFByb3BlcnR5QXJyaXZhbEJvZHlUZXh0EjUu",
"aG9sbXMudHlwZXMudGVuYW5jeV9jb25maWcuUHJvcGVydHlBcnJpdmFsTGV0",
"dGVyVGV4dBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eRJ6ChtHZXRBbGxDYW5j",
"ZWxsYXRpb25Cb2R5VGV4dHMSFi5nb29nbGUucHJvdG9idWYuRW1wdHkaQy5o",
"b2xtcy50eXBlcy50ZW5hbmN5X2NvbmZpZy5ycGMuR2V0QWxsQ2FuY2VsbGF0",
"aW9uQm9keVRleHRzUmVzcG9uc2USjwEKF0dldENhbmNlbGxhdGlvbkJvZHlU",
"ZXh0EjguaG9sbXMudHlwZXMudGVuYW5jeV9jb25maWcuaW5kaWNhdG9ycy5Q",
"cm9wZXJ0eUluZGljYXRvcho6LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmln",
"LlByb3BlcnR5Q2FuY2VsbGF0aW9uTGV0dGVyVGV4dBJ1Ch9TZXRQcm9wZXJ0",
"eUNhbmNlbGxhdGlvbkJvZHlUZXh0EjouaG9sbXMudHlwZXMudGVuYW5jeV9j",
"b25maWcuUHJvcGVydHlDYW5jZWxsYXRpb25MZXR0ZXJUZXh0GhYuZ29vZ2xl",
"LnByb3RvYnVmLkVtcHR5EnQKGEdldEFsbEVtYWlsU2VuZGVyQ29uZmlncxIW",
"Lmdvb2dsZS5wcm90b2J1Zi5FbXB0eRpALmhvbG1zLnR5cGVzLnRlbmFuY3lf",
"Y29uZmlnLnJwYy5HZXRBbGxFbWFpbFNlbmRlckNvbmZpZ3NSZXNwb25zZRKH",
"AQoUR2V0RW1haWxTZW5kZXJDb25maWcSOC5ob2xtcy50eXBlcy50ZW5hbmN5",
"X2NvbmZpZy5pbmRpY2F0b3JzLlByb3BlcnR5SW5kaWNhdG9yGjUuaG9sbXMu",
"dHlwZXMudGVuYW5jeV9jb25maWcuUHJvcGVydHlFbWFpbFNlbmRlckNvbmZp",
"ZxJlChRTZXRFbWFpbFNlbmRlckNvbmZpZxI1LmhvbG1zLnR5cGVzLnRlbmFu",
"Y3lfY29uZmlnLlByb3BlcnR5RW1haWxTZW5kZXJDb25maWcaFi5nb29nbGUu",
"cHJvdG9idWYuRW1wdHlCM1oRdGVuYW5jeWNvbmZpZy9ycGOqAh1IT0xNUy5U",
"eXBlcy5UZW5hbmN5Q29uZmlnLlJQQ2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.ServerActionConfirmationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::HOLMS.Types.TenancyConfig.FullPropertyReflection.Descriptor, global::HOLMS.Types.TenancyConfig.PropertyReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicatorReflection.Descriptor, global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterTextReflection.Descriptor, global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterTextReflection.Descriptor, global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterTextReflection.Descriptor, global::HOLMS.Types.TenancyConfig.PropertyEmailSenderConfigReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.PropertySvcAllResponse), global::HOLMS.Types.TenancyConfig.RPC.PropertySvcAllResponse.Parser, new[]{ "Properties" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.PropertySvcAllFullResponse), global::HOLMS.Types.TenancyConfig.RPC.PropertySvcAllFullResponse.Parser, new[]{ "Properties" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.PropertySvcAccrueRevenueRequest), global::HOLMS.Types.TenancyConfig.RPC.PropertySvcAccrueRevenueRequest.Parser, new[]{ "Property", "RunEveryMins" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.GetAllConfirmationBodyTextsResponse), global::HOLMS.Types.TenancyConfig.RPC.GetAllConfirmationBodyTextsResponse.Parser, new[]{ "Texts" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.GetAllCancellationBodyTextsResponse), global::HOLMS.Types.TenancyConfig.RPC.GetAllCancellationBodyTextsResponse.Parser, new[]{ "Texts" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.GetAllArrivalBodyTextsResponse), global::HOLMS.Types.TenancyConfig.RPC.GetAllArrivalBodyTextsResponse.Parser, new[]{ "Texts" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.GetAllEmailSenderConfigsResponse), global::HOLMS.Types.TenancyConfig.RPC.GetAllEmailSenderConfigsResponse.Parser, new[]{ "Configs" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PropertySvcAllResponse : pb::IMessage<PropertySvcAllResponse> {
private static readonly pb::MessageParser<PropertySvcAllResponse> _parser = new pb::MessageParser<PropertySvcAllResponse>(() => new PropertySvcAllResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PropertySvcAllResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.PropertySvcReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PropertySvcAllResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PropertySvcAllResponse(PropertySvcAllResponse other) : this() {
properties_ = other.properties_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PropertySvcAllResponse Clone() {
return new PropertySvcAllResponse(this);
}
/// <summary>Field number for the "properties" field.</summary>
public const int PropertiesFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.TenancyConfig.Property> _repeated_properties_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.TenancyConfig.Property.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.Property> properties_ = new pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.Property>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.Property> Properties {
get { return properties_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PropertySvcAllResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PropertySvcAllResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!properties_.Equals(other.properties_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= properties_.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) {
properties_.WriteTo(output, _repeated_properties_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += properties_.CalculateSize(_repeated_properties_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PropertySvcAllResponse other) {
if (other == null) {
return;
}
properties_.Add(other.properties_);
}
[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: {
properties_.AddEntriesFrom(input, _repeated_properties_codec);
break;
}
}
}
}
}
public sealed partial class PropertySvcAllFullResponse : pb::IMessage<PropertySvcAllFullResponse> {
private static readonly pb::MessageParser<PropertySvcAllFullResponse> _parser = new pb::MessageParser<PropertySvcAllFullResponse>(() => new PropertySvcAllFullResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PropertySvcAllFullResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.PropertySvcReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PropertySvcAllFullResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PropertySvcAllFullResponse(PropertySvcAllFullResponse other) : this() {
properties_ = other.properties_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PropertySvcAllFullResponse Clone() {
return new PropertySvcAllFullResponse(this);
}
/// <summary>Field number for the "properties" field.</summary>
public const int PropertiesFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.TenancyConfig.FullProperty> _repeated_properties_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.TenancyConfig.FullProperty.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.FullProperty> properties_ = new pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.FullProperty>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.FullProperty> Properties {
get { return properties_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PropertySvcAllFullResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PropertySvcAllFullResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!properties_.Equals(other.properties_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= properties_.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) {
properties_.WriteTo(output, _repeated_properties_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += properties_.CalculateSize(_repeated_properties_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PropertySvcAllFullResponse other) {
if (other == null) {
return;
}
properties_.Add(other.properties_);
}
[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: {
properties_.AddEntriesFrom(input, _repeated_properties_codec);
break;
}
}
}
}
}
public sealed partial class PropertySvcAccrueRevenueRequest : pb::IMessage<PropertySvcAccrueRevenueRequest> {
private static readonly pb::MessageParser<PropertySvcAccrueRevenueRequest> _parser = new pb::MessageParser<PropertySvcAccrueRevenueRequest>(() => new PropertySvcAccrueRevenueRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PropertySvcAccrueRevenueRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.PropertySvcReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PropertySvcAccrueRevenueRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PropertySvcAccrueRevenueRequest(PropertySvcAccrueRevenueRequest other) : this() {
Property = other.property_ != null ? other.Property.Clone() : null;
runEveryMins_ = other.runEveryMins_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PropertySvcAccrueRevenueRequest Clone() {
return new PropertySvcAccrueRevenueRequest(this);
}
/// <summary>Field number for the "property" field.</summary>
public const int PropertyFieldNumber = 1;
private global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator property_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator Property {
get { return property_; }
set {
property_ = value;
}
}
/// <summary>Field number for the "run_every_mins" field.</summary>
public const int RunEveryMinsFieldNumber = 2;
private uint runEveryMins_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint RunEveryMins {
get { return runEveryMins_; }
set {
runEveryMins_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PropertySvcAccrueRevenueRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PropertySvcAccrueRevenueRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Property, other.Property)) return false;
if (RunEveryMins != other.RunEveryMins) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (property_ != null) hash ^= Property.GetHashCode();
if (RunEveryMins != 0) hash ^= RunEveryMins.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 (property_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Property);
}
if (RunEveryMins != 0) {
output.WriteRawTag(16);
output.WriteUInt32(RunEveryMins);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (property_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Property);
}
if (RunEveryMins != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(RunEveryMins);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PropertySvcAccrueRevenueRequest other) {
if (other == null) {
return;
}
if (other.property_ != null) {
if (property_ == null) {
property_ = new global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator();
}
Property.MergeFrom(other.Property);
}
if (other.RunEveryMins != 0) {
RunEveryMins = other.RunEveryMins;
}
}
[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: {
if (property_ == null) {
property_ = new global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator();
}
input.ReadMessage(property_);
break;
}
case 16: {
RunEveryMins = input.ReadUInt32();
break;
}
}
}
}
}
public sealed partial class GetAllConfirmationBodyTextsResponse : pb::IMessage<GetAllConfirmationBodyTextsResponse> {
private static readonly pb::MessageParser<GetAllConfirmationBodyTextsResponse> _parser = new pb::MessageParser<GetAllConfirmationBodyTextsResponse>(() => new GetAllConfirmationBodyTextsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetAllConfirmationBodyTextsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.PropertySvcReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllConfirmationBodyTextsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllConfirmationBodyTextsResponse(GetAllConfirmationBodyTextsResponse other) : this() {
texts_ = other.texts_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllConfirmationBodyTextsResponse Clone() {
return new GetAllConfirmationBodyTextsResponse(this);
}
/// <summary>Field number for the "texts" field.</summary>
public const int TextsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText> _repeated_texts_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText> texts_ = new pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText> Texts {
get { return texts_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetAllConfirmationBodyTextsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetAllConfirmationBodyTextsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!texts_.Equals(other.texts_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= texts_.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) {
texts_.WriteTo(output, _repeated_texts_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += texts_.CalculateSize(_repeated_texts_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetAllConfirmationBodyTextsResponse other) {
if (other == null) {
return;
}
texts_.Add(other.texts_);
}
[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: {
texts_.AddEntriesFrom(input, _repeated_texts_codec);
break;
}
}
}
}
}
public sealed partial class GetAllCancellationBodyTextsResponse : pb::IMessage<GetAllCancellationBodyTextsResponse> {
private static readonly pb::MessageParser<GetAllCancellationBodyTextsResponse> _parser = new pb::MessageParser<GetAllCancellationBodyTextsResponse>(() => new GetAllCancellationBodyTextsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetAllCancellationBodyTextsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.PropertySvcReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllCancellationBodyTextsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllCancellationBodyTextsResponse(GetAllCancellationBodyTextsResponse other) : this() {
texts_ = other.texts_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllCancellationBodyTextsResponse Clone() {
return new GetAllCancellationBodyTextsResponse(this);
}
/// <summary>Field number for the "texts" field.</summary>
public const int TextsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText> _repeated_texts_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText> texts_ = new pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText> Texts {
get { return texts_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetAllCancellationBodyTextsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetAllCancellationBodyTextsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!texts_.Equals(other.texts_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= texts_.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) {
texts_.WriteTo(output, _repeated_texts_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += texts_.CalculateSize(_repeated_texts_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetAllCancellationBodyTextsResponse other) {
if (other == null) {
return;
}
texts_.Add(other.texts_);
}
[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: {
texts_.AddEntriesFrom(input, _repeated_texts_codec);
break;
}
}
}
}
}
public sealed partial class GetAllArrivalBodyTextsResponse : pb::IMessage<GetAllArrivalBodyTextsResponse> {
private static readonly pb::MessageParser<GetAllArrivalBodyTextsResponse> _parser = new pb::MessageParser<GetAllArrivalBodyTextsResponse>(() => new GetAllArrivalBodyTextsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetAllArrivalBodyTextsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.PropertySvcReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllArrivalBodyTextsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllArrivalBodyTextsResponse(GetAllArrivalBodyTextsResponse other) : this() {
texts_ = other.texts_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllArrivalBodyTextsResponse Clone() {
return new GetAllArrivalBodyTextsResponse(this);
}
/// <summary>Field number for the "texts" field.</summary>
public const int TextsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText> _repeated_texts_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText> texts_ = new pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText> Texts {
get { return texts_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetAllArrivalBodyTextsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetAllArrivalBodyTextsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!texts_.Equals(other.texts_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= texts_.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) {
texts_.WriteTo(output, _repeated_texts_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += texts_.CalculateSize(_repeated_texts_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetAllArrivalBodyTextsResponse other) {
if (other == null) {
return;
}
texts_.Add(other.texts_);
}
[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: {
texts_.AddEntriesFrom(input, _repeated_texts_codec);
break;
}
}
}
}
}
public sealed partial class GetAllEmailSenderConfigsResponse : pb::IMessage<GetAllEmailSenderConfigsResponse> {
private static readonly pb::MessageParser<GetAllEmailSenderConfigsResponse> _parser = new pb::MessageParser<GetAllEmailSenderConfigsResponse>(() => new GetAllEmailSenderConfigsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetAllEmailSenderConfigsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.PropertySvcReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllEmailSenderConfigsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllEmailSenderConfigsResponse(GetAllEmailSenderConfigsResponse other) : this() {
configs_ = other.configs_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetAllEmailSenderConfigsResponse Clone() {
return new GetAllEmailSenderConfigsResponse(this);
}
/// <summary>Field number for the "configs" field.</summary>
public const int ConfigsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.TenancyConfig.PropertyEmailSenderConfig> _repeated_configs_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.TenancyConfig.PropertyEmailSenderConfig.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyEmailSenderConfig> configs_ = new pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyEmailSenderConfig>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.PropertyEmailSenderConfig> Configs {
get { return configs_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetAllEmailSenderConfigsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetAllEmailSenderConfigsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!configs_.Equals(other.configs_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= configs_.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) {
configs_.WriteTo(output, _repeated_configs_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += configs_.CalculateSize(_repeated_configs_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetAllEmailSenderConfigsResponse other) {
if (other == null) {
return;
}
configs_.Add(other.configs_);
}
[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: {
configs_.AddEntriesFrom(input, _repeated_configs_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.IO;
using EmergeTk;
using EmergeTk.Model;
using EmergeTk.Model.Security;
using EmergeTk.Widgets.Html;
namespace EmergeTk.Administration
{
public class Designer : Generic, IAdmin
{
Label label;
private string template;
private string filePath;
#region IAdmin implementation
public string AdminName {
get {
return "Views";
}
}
public string Description {
get {
return "Auto-generate widget templates for model forms and scaffolds.";
}
}
public Permission AdminPermission
{
get {
return Permission.GetOrCreatePermission("View Templates");
}
}
#endregion
public override void Initialize ()
{
Label l = RootContext.CreateWidget<Label>(this);
l.Text = "<h3>Model Forms</h3>";
Type[] modelTypes = TypeLoader.GetTypesOfBaseType( typeof(AbstractRecord) );
foreach( Type t in modelTypes )
{
LinkButton lb = RootContext.CreateWidget<LinkButton>(this);
lb.Label = "New " + t.FullName + " ModelForm<BR>";
lb.StateBag["t"] = t;
lb.OnClick += new EventHandler<ClickEventArgs>( newModelForm );
}
//find all types that derive from AbstractRecord
l = RootContext.CreateWidget<Label>(this);
l.Text = "<P/><h3>Scaffold Templates</h3>";
foreach( Type t in modelTypes )
{
LinkButton lb = RootContext.CreateWidget<LinkButton>(this);
lb.Label = "New " + t.FullName + " Scaffold Template<BR>";
lb.StateBag["t"] = t;
lb.OnClick += new EventHandler<ClickEventArgs>( newScaffoldTemplate );
}
this.label = RootContext.CreateWidget<Label>(this);
}
public void newScaffoldTemplate( object sender, ClickEventArgs ea )
{
Generic g = RootContext.CreateWidget<Generic>(this);
g.TagName = "Code";
Type t = ea.Source.StateBag["t"] as Type;
ColumnInfo[] fields = ColumnInfoManager.RequestColumns(t);
template = @"<Widget xmlns:emg=""http://www.emergetk.com/"">";
foreach( ColumnInfo ci in fields )
{
template += string.Format(
@"
<div class=""field field{0}"">
<strong>{0}</strong> : {{{0}}}
</div>", ci.Name );
}
template +=
@"
<div class=""buttonPane"">
<emg:PlaceHolder Id=""EditPlaceHolder""/>
<emg:PlaceHolder Id=""DeletePlaceHolder""/>
</div>
</Widget>";
log.Debug(template);
FileInfo newFi = ThemeManager.Instance.RequestNewPhysicalFilePath( "Views" + Path.DirectorySeparatorChar + t.FullName.Replace('.', Path.DirectorySeparatorChar) + ".scaffoldtemplate" );
Directory.CreateDirectory( newFi.Directory.FullName );
this.filePath = newFi.FullName;
//System.Web.HttpContext.Current.Server.MapPath();
log.Debug("Writing new template out to file at " + newFi.FullName);
if (File.Exists(newFi.FullName))
{
this.label.Text = "A custom scaffold template for this type already exists.";
ConfirmButton cb = this.RootContext.CreateWidget<ConfirmButton>(this);
cb.OnConfirm += new EventHandler<ClickEventArgs>(cb_OnConfirm);
cb.Label = "Overwrite existing file";
}
else
{
this.SaveXml();
}
}
public void newModelForm( object sender, ClickEventArgs ea )
{
Generic g = RootContext.CreateWidget<Generic>(this);
g.TagName = "Code";
Type t = ea.Source.StateBag["t"] as Type;
ColumnInfo[] fields = ColumnInfoManager.RequestColumns(t);
template = @"<Widget xmlns:emg=""http://www.emergetk.com/"">";
foreach( ColumnInfo ci in fields )
{
template += string.Format(
@"
<div class=""editFieldInput editFieldInput{0}"">
<emg:PlaceHolder Id=""{0}Label""/>
<emg:PlaceHolder Id=""{0}Input""/>
</div>", ci.Name );
}
template +=
@"
<div class=""buttonPane"">
<emg:PlaceHolder Id=""SubmitButton""/>
<emg:PlaceHolder Id=""CancelButton""/>
<emg:PlaceHolder Id=""DeleteButton""/>
</div>
</Widget>";
log.Debug(template);
FileInfo newFi = ThemeManager.Instance.RequestNewPhysicalFilePath( "Views" + Path.DirectorySeparatorChar + t.FullName.Replace('.', Path.DirectorySeparatorChar) + ".modelform" );
Directory.CreateDirectory( newFi.Directory.FullName );
this.filePath = newFi.FullName;
log.Debug("Writing new template out to file at " + filePath);
if (File.Exists(filePath))
{
this.label.Text = "A custom model form for this type already exists.";
ConfirmButton cb = this.RootContext.CreateWidget<ConfirmButton>(this);
cb.OnConfirm += new EventHandler<ClickEventArgs>(cb_OnConfirm);
cb.Label = "Overwrite existing file";
}
else
{
this.SaveXml();
}
}
void cb_OnConfirm(object sender, ClickEventArgs ea)
{
ea.Source.Remove();
this.SaveXml();
}
private void SaveXml()
{
TextWriter tw = new StreamWriter(filePath);
tw.Write(template);
tw.Close();
tw.Dispose();
template = System.Web.HttpUtility.HtmlEncode(template);
this.label.Text = template;
}
public override string BaseXml {
get {
return
@"
<Widget xmlns:emg=""http://www.emergetk.com/"">
<h1>EmergeTk Designer</h1>
<h2>Generate Model Form</h2>
</Widget>
";
}
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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 DiscUtils.Iso9660
{
using System;
using System.Collections.Generic;
using System.IO;
using DiscUtils.Vfs;
internal class VfsCDReader : VfsReadOnlyFileSystem<ReaderDirEntry, File, ReaderDirectory, IsoContext>, IClusterBasedFileSystem, IUnixFileSystem
{
private static readonly Iso9660Variant[] DefaultVariantsNoJoliet = new Iso9660Variant[] { Iso9660Variant.RockRidge, Iso9660Variant.Iso9660 };
private static readonly Iso9660Variant[] DefaultVariantsWithJoliet = new Iso9660Variant[] { Iso9660Variant.Joliet, Iso9660Variant.RockRidge, Iso9660Variant.Iso9660 };
private Stream _data;
private bool _hideVersions;
private BootVolumeDescriptor _bootVolDesc;
private byte[] _bootCatalog;
private Iso9660Variant _activeVariant;
/// <summary>
/// Initializes a new instance of the VfsCDReader class.
/// </summary>
/// <param name="data">The stream to read the ISO image from.</param>
/// <param name="joliet">Whether to read Joliet extensions.</param>
/// <param name="hideVersions">Hides version numbers (e.g. ";1") from the end of files.</param>
public VfsCDReader(Stream data, bool joliet, bool hideVersions)
: this(data, joliet ? DefaultVariantsWithJoliet : DefaultVariantsNoJoliet, hideVersions)
{
}
/// <summary>
/// Initializes a new instance of the VfsCDReader class.
/// </summary>
/// <param name="data">The stream to read the ISO image from.</param>
/// <param name="variantPriorities">Which possible file system variants to use, and with which priority.</param>
/// <param name="hideVersions">Hides version numbers (e.g. ";1") from the end of files.</param>
/// <remarks>
/// <para>
/// The implementation considers each of the file system variants in <c>variantProperties</c> and selects
/// the first which is determined to be present. In this example Joliet, then Rock Ridge, then vanilla
/// Iso9660 will be considered:
/// </para>
/// <code lang="cs">
/// VfsCDReader(stream, new Iso9660Variant[] {Joliet, RockRidge, Iso9660}, true);
/// </code>
/// <para>The Iso9660 variant should normally be specified as the final entry in the list. Placing it earlier
/// in the list will effectively mask later items and not including it may prevent some ISOs from being read.</para>
/// </remarks>
public VfsCDReader(Stream data, Iso9660Variant[] variantPriorities, bool hideVersions)
: base(new DiscFileSystemOptions())
{
_data = data;
_hideVersions = hideVersions;
long vdpos = 0x8000; // Skip lead-in
byte[] buffer = new byte[IsoUtilities.SectorSize];
long pvdPos = 0;
long svdPos = 0;
BaseVolumeDescriptor bvd;
do
{
data.Position = vdpos;
int numRead = data.Read(buffer, 0, IsoUtilities.SectorSize);
if (numRead != IsoUtilities.SectorSize)
{
break;
}
bvd = new BaseVolumeDescriptor(buffer, 0);
switch (bvd.VolumeDescriptorType)
{
case VolumeDescriptorType.Boot:
_bootVolDesc = new BootVolumeDescriptor(buffer, 0);
if (_bootVolDesc.SystemId != BootVolumeDescriptor.ElToritoSystemIdentifier)
{
_bootVolDesc = null;
}
break;
case VolumeDescriptorType.Primary: // Primary Vol Descriptor
pvdPos = vdpos;
break;
case VolumeDescriptorType.Supplementary: // Supplementary Vol Descriptor
svdPos = vdpos;
break;
case VolumeDescriptorType.Partition: // Volume Partition Descriptor
break;
case VolumeDescriptorType.SetTerminator: // Volume Descriptor Set Terminator
break;
}
vdpos += IsoUtilities.SectorSize;
}
while (bvd.VolumeDescriptorType != VolumeDescriptorType.SetTerminator);
_activeVariant = Iso9660Variant.None;
foreach (var variant in variantPriorities)
{
switch (variant)
{
case Iso9660Variant.Joliet:
if (svdPos != 0)
{
data.Position = svdPos;
data.Read(buffer, 0, IsoUtilities.SectorSize);
var volDesc = new SupplementaryVolumeDescriptor(buffer, 0);
Context = new IsoContext { VolumeDescriptor = volDesc, DataStream = _data };
RootDirectory = new ReaderDirectory(Context, new ReaderDirEntry(Context, volDesc.RootDirectory));
_activeVariant = Iso9660Variant.Iso9660;
}
break;
case Iso9660Variant.RockRidge:
case Iso9660Variant.Iso9660:
if (pvdPos != 0)
{
data.Position = pvdPos;
data.Read(buffer, 0, IsoUtilities.SectorSize);
var volDesc = new PrimaryVolumeDescriptor(buffer, 0);
IsoContext context = new IsoContext { VolumeDescriptor = volDesc, DataStream = _data };
DirectoryRecord rootSelfRecord = ReadRootSelfRecord(context);
InitializeSusp(context, rootSelfRecord);
if (variant == Iso9660Variant.Iso9660
|| (variant == Iso9660Variant.RockRidge && !string.IsNullOrEmpty(context.RockRidgeIdentifier)))
{
Context = context;
RootDirectory = new ReaderDirectory(context, new ReaderDirEntry(context, rootSelfRecord));
_activeVariant = variant;
}
}
break;
}
if (_activeVariant != Iso9660Variant.None)
{
break;
}
}
if (_activeVariant == Iso9660Variant.None)
{
throw new IOException("None of the permitted ISO9660 file system variants was detected");
}
}
/// <summary>
/// Provides the friendly name for the CD filesystem.
/// </summary>
public override string FriendlyName
{
get { return "ISO 9660 (CD-ROM)"; }
}
/// <summary>
/// Gets the Volume Identifier.
/// </summary>
public override string VolumeLabel
{
get { return Context.VolumeDescriptor.VolumeIdentifier; }
}
public bool HasBootImage
{
get
{
if (_bootVolDesc == null)
{
return false;
}
byte[] bootCatalog = GetBootCatalog();
if (bootCatalog == null)
{
return false;
}
BootValidationEntry entry = new BootValidationEntry(bootCatalog, 0);
return entry.ChecksumValid;
}
}
public BootDeviceEmulation BootEmulation
{
get
{
BootInitialEntry initialEntry = GetBootInitialEntry();
if (initialEntry != null)
{
return initialEntry.BootMediaType;
}
return BootDeviceEmulation.NoEmulation;
}
}
public int BootLoadSegment
{
get
{
BootInitialEntry initialEntry = GetBootInitialEntry();
if (initialEntry != null)
{
return initialEntry.LoadSegment;
}
return 0;
}
}
public long BootImageStart
{
get
{
BootInitialEntry initialEntry = GetBootInitialEntry();
if (initialEntry != null)
{
return initialEntry.ImageStart * IsoUtilities.SectorSize;
}
else
{
return 0;
}
}
}
public long ClusterSize
{
get { return IsoUtilities.SectorSize; }
}
public long TotalClusters
{
get { return Context.VolumeDescriptor.VolumeSpaceSize; }
}
public Iso9660Variant ActiveVariant
{
get { return _activeVariant; }
}
public Stream OpenBootImage()
{
BootInitialEntry initialEntry = GetBootInitialEntry();
if (initialEntry != null)
{
return new SubStream(_data, initialEntry.ImageStart * IsoUtilities.SectorSize, initialEntry.SectorCount * Sizes.Sector);
}
else
{
throw new InvalidOperationException("No valid boot image");
}
}
public UnixFileSystemInfo GetUnixFileInfo(string path)
{
File file = GetFile(path);
return file.UnixFileInfo;
}
public long ClusterToOffset(long cluster)
{
return cluster * ClusterSize;
}
public long OffsetToCluster(long offset)
{
return offset / ClusterSize;
}
public Range<long, long>[] PathToClusters(string path)
{
ReaderDirEntry entry = GetDirectoryEntry(path);
if (entry == null)
{
throw new FileNotFoundException("File not found", path);
}
if (entry.Record.FileUnitSize != 0 || entry.Record.InterleaveGapSize != 0)
{
throw new NotSupportedException("Non-contiguous extents not supported");
}
return new Range<long, long>[] { new Range<long, long>(entry.Record.LocationOfExtent, Utilities.Ceil(entry.Record.DataLength, IsoUtilities.SectorSize)) };
}
public StreamExtent[] PathToExtents(string path)
{
ReaderDirEntry entry = GetDirectoryEntry(path);
if (entry == null)
{
throw new FileNotFoundException("File not found", path);
}
if (entry.Record.FileUnitSize != 0 || entry.Record.InterleaveGapSize != 0)
{
throw new NotSupportedException("Non-contiguous extents not supported");
}
return new StreamExtent[] { new StreamExtent(entry.Record.LocationOfExtent * IsoUtilities.SectorSize, entry.Record.DataLength) };
}
public ClusterMap BuildClusterMap()
{
long totalClusters = TotalClusters;
ClusterRoles[] clusterToRole = new ClusterRoles[totalClusters];
object[] clusterToFileId = new object[totalClusters];
Dictionary<object, string[]> fileIdToPaths = new Dictionary<object, string[]>();
ForAllDirEntries(
string.Empty,
(path, entry) =>
{
string[] paths = null;
if (fileIdToPaths.ContainsKey(entry.UniqueCacheId))
{
paths = fileIdToPaths[entry.UniqueCacheId];
}
if (paths == null)
{
fileIdToPaths[entry.UniqueCacheId] = new string[] { path };
}
else
{
string[] newPaths = new string[paths.Length + 1];
Array.Copy(paths, newPaths, paths.Length);
newPaths[paths.Length] = path;
fileIdToPaths[entry.UniqueCacheId] = newPaths;
}
if (entry.Record.FileUnitSize != 0 || entry.Record.InterleaveGapSize != 0)
{
throw new NotSupportedException("Non-contiguous extents not supported");
}
long clusters = Utilities.Ceil(entry.Record.DataLength, IsoUtilities.SectorSize);
for (long i = 0; i < clusters; ++i)
{
clusterToRole[i + entry.Record.LocationOfExtent] = ClusterRoles.DataFile;
clusterToFileId[i + entry.Record.LocationOfExtent] = entry.UniqueCacheId;
}
});
return new ClusterMap(clusterToRole, clusterToFileId, fileIdToPaths);
}
/// <summary>
/// Size of the Filesystem in bytes
/// </summary>
public override long Size
{
get { throw new NotSupportedException("Filesystem size is not (yet) supported"); }
}
/// <summary>
/// Used space of the Filesystem in bytes
/// </summary>
public override long UsedSpace
{
get { throw new NotSupportedException("Filesystem size is not (yet) supported"); }
}
/// <summary>
/// Available space of the Filesystem in bytes
/// </summary>
public override long AvailableSpace
{
get { throw new NotSupportedException("Filesystem size is not (yet) supported"); }
}
protected override File ConvertDirEntryToFile(ReaderDirEntry dirEntry)
{
if (dirEntry.IsDirectory)
{
return new ReaderDirectory(Context, dirEntry);
}
else
{
return new File(Context, dirEntry);
}
}
protected override string FormatFileName(string name)
{
if (_hideVersions)
{
int pos = name.LastIndexOf(';');
if (pos > 0)
{
return name.Substring(0, pos);
}
}
return name;
}
private static void InitializeSusp(IsoContext context, DirectoryRecord rootSelfRecord)
{
// Stage 1 - SUSP present?
List<SuspExtension> extensions = new List<SuspExtension>();
if (!SuspRecords.DetectSharingProtocol(rootSelfRecord.SystemUseData, 0))
{
context.SuspExtensions = new List<SuspExtension>();
context.SuspDetected = false;
return;
}
else
{
context.SuspDetected = true;
}
SuspRecords suspRecords = new SuspRecords(context, rootSelfRecord.SystemUseData, 0);
// Stage 2 - Init general SUSP params
SharingProtocolSystemUseEntry spEntry = (SharingProtocolSystemUseEntry)suspRecords.GetEntries(null, "SP")[0];
context.SuspSkipBytes = spEntry.SystemAreaSkip;
// Stage 3 - Init extensions
List<SystemUseEntry> extensionEntries = suspRecords.GetEntries(null, "ER");
if (extensionEntries != null)
{
foreach (ExtensionSystemUseEntry extension in extensionEntries)
{
switch (extension.ExtensionIdentifier)
{
case "RRIP_1991A":
case "IEEE_P1282":
case "IEEE_1282":
extensions.Add(new RockRidgeExtension(extension.ExtensionIdentifier));
context.RockRidgeIdentifier = extension.ExtensionIdentifier;
break;
default:
extensions.Add(new GenericSuspExtension(extension.ExtensionIdentifier));
break;
}
}
}
else if (suspRecords.GetEntries(null, "RR") != null)
{
// Some ISO creators don't add the 'ER' record for RockRidge, but write the (legacy)
// RR record anyway
extensions.Add(new RockRidgeExtension("RRIP_1991A"));
context.RockRidgeIdentifier = "RRIP_1991A";
}
context.SuspExtensions = extensions;
}
private static DirectoryRecord ReadRootSelfRecord(IsoContext context)
{
context.DataStream.Position = context.VolumeDescriptor.RootDirectory.LocationOfExtent * context.VolumeDescriptor.LogicalBlockSize;
byte[] firstSector = Utilities.ReadFully(context.DataStream, context.VolumeDescriptor.LogicalBlockSize);
DirectoryRecord rootSelfRecord;
DirectoryRecord.ReadFrom(firstSector, 0, context.VolumeDescriptor.CharacterEncoding, out rootSelfRecord);
return rootSelfRecord;
}
private BootInitialEntry GetBootInitialEntry()
{
byte[] bootCatalog = GetBootCatalog();
if (bootCatalog == null)
{
return null;
}
BootValidationEntry validationEntry = new BootValidationEntry(bootCatalog, 0);
if (!validationEntry.ChecksumValid)
{
return null;
}
return new BootInitialEntry(bootCatalog, 0x20);
}
private byte[] GetBootCatalog()
{
if (_bootCatalog == null && _bootVolDesc != null)
{
_data.Position = _bootVolDesc.CatalogSector * IsoUtilities.SectorSize;
_bootCatalog = Utilities.ReadFully(_data, IsoUtilities.SectorSize);
}
return _bootCatalog;
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System;
using System.Threading;
using NAppUpdate.Framework.Common;
using NAppUpdate.Framework.FeedReaders;
using NAppUpdate.Framework.Sources;
using NAppUpdate.Framework.Tasks;
using NAppUpdate.Framework.Utils;
namespace NAppUpdate.Framework
{
/// <summary>
/// An UpdateManager class is a singleton class handling the update process from start to end for a consumer application
/// </summary>
public sealed class UpdateManager
{
#region Singleton Stuff
/// <summary>
/// Defaut ctor
/// </summary>
private UpdateManager()
{
IsWorking = false;
State = UpdateProcessState.NotChecked;
UpdatesToApply = new List<IUpdateTask>();
ApplicationPath = Process.GetCurrentProcess().MainModule.FileName;
UpdateFeedReader = new NauXmlFeedReader();
Logger = new Logger();
Config = new NauConfigurations
{
TempFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()),
UpdateProcessName = "NAppUpdateProcess",
UpdateExecutableName = "foo.exe", // Naming it updater.exe seem to trigger the UAC, and we don't want that
};
// Need to do this manually here because the BackupFolder property is protected using the static instance, which we are
// in the middle of creating
string backupPath = Path.Combine(Path.GetDirectoryName(ApplicationPath) ?? string.Empty, "Backup" + DateTime.Now.Ticks);
backupPath = backupPath.TrimEnd(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
Config._backupFolder = Path.IsPathRooted(backupPath) ? backupPath : Path.Combine(Config.TempFolder, backupPath);
}
static UpdateManager() { }
/// <summary>
/// The singleton update manager instance to used by consumer applications
/// </summary>
public static UpdateManager Instance
{
get { return instance; }
}
private static readonly UpdateManager instance = new UpdateManager();
private static Mutex _shutdownMutex;
#endregion
/// <summary>
/// State of the update process
/// </summary>
[Serializable]
public enum UpdateProcessState
{
NotChecked,
Checked,
Prepared,
AfterRestart,
AppliedSuccessfully,
RollbackRequired,
}
internal readonly string ApplicationPath;
public NauConfigurations Config { get; set; }
internal string BaseUrl { get; set; }
internal IList<IUpdateTask> UpdatesToApply { get; private set; }
public int UpdatesAvailable { get { return UpdatesToApply == null ? 0 : UpdatesToApply.Count; } }
public UpdateProcessState State { get; private set; }
public IUpdateSource UpdateSource { get; set; }
public IUpdateFeedReader UpdateFeedReader { get; set; }
public Logger Logger { get; private set; }
public IEnumerable<IUpdateTask> Tasks { get { return UpdatesToApply; } }
internal volatile bool ShouldStop;
public bool IsWorking { get { return _isWorking; } private set { _isWorking = value; } }
private volatile bool _isWorking;
#region Progress reporting
public event ReportProgressDelegate ReportProgress;
private void TaskProgressCallback(UpdateProgressInfo currentStatus, IUpdateTask task)
{
if (ReportProgress == null) return;
currentStatus.TaskDescription = task.Description;
currentStatus.TaskId = UpdatesToApply.IndexOf(task) + 1;
//This was an assumed int, which meant we never reached 100% with an odd number of tasks
float taskPerc = 100F / UpdatesToApply.Count;
currentStatus.Percentage = (int)Math.Round((currentStatus.Percentage * taskPerc / 100) + (currentStatus.TaskId - 1) * taskPerc);
ReportProgress(currentStatus);
}
#endregion
#region Step 1 - Check for updates
/// <summary>
/// Check for update synchronously, using the default update source
/// </summary>
public void CheckForUpdates()
{
CheckForUpdates(UpdateSource);
}
/// <summary>
/// Check for updates synchronouly
/// </summary>
/// <param name="source">Updates source to use</param>
public void CheckForUpdates(IUpdateSource source)
{
if (IsWorking)
throw new InvalidOperationException("Another update process is already in progress");
using (WorkScope.New(isWorking => IsWorking = isWorking))
{
if (UpdateFeedReader == null)
throw new ArgumentException("An update feed reader is required; please set one before checking for updates");
if (source == null)
throw new ArgumentException("An update source was not specified");
if (State != UpdateProcessState.NotChecked)
throw new InvalidOperationException("Already checked for updates; to reset the current state call CleanUp()");
lock (UpdatesToApply)
{
UpdatesToApply.Clear();
var tasks = UpdateFeedReader.Read(source.GetUpdatesFeed());
foreach (var t in tasks)
{
if (ShouldStop)
throw new UserAbortException();
if (t.UpdateConditions == null || t.UpdateConditions.IsMet(t)) // Only execute if all conditions are met
UpdatesToApply.Add(t);
}
}
State = UpdateProcessState.Checked;
}
}
/// <summary>
/// Check for updates asynchronously
/// </summary>
/// <param name="source">Update source to use</param>
/// <param name="callback">Callback function to call when done; can be null</param>
/// <param name="state">Allows the caller to preserve state; can be null</param>
public IAsyncResult BeginCheckForUpdates(IUpdateSource source, AsyncCallback callback, Object state)
{
// Create IAsyncResult object identifying the
// asynchronous operation
var ar = new UpdateProcessAsyncResult(callback, state);
// Use a thread pool thread to perform the operation
ThreadPool.QueueUserWorkItem(o =>
{
try
{
// Perform the operation; if sucessful set the result
CheckForUpdates(source ?? UpdateSource);
ar.SetAsCompleted(null, false);
}
catch (Exception e)
{
// If operation fails, set the exception
ar.SetAsCompleted(e, false);
}
}, ar);
return ar; // Return the IAsyncResult to the caller
}
/// <summary>
/// Check for updates asynchronously
/// </summary>
/// <param name="callback">Callback function to call when done; can be null</param>
/// <param name="state">Allows the caller to preserve state; can be null</param>
public IAsyncResult BeginCheckForUpdates(AsyncCallback callback, Object state)
{
return BeginCheckForUpdates(UpdateSource, callback, state);
}
/// <summary>
/// Block until previously-called CheckForUpdates complete
/// </summary>
/// <param name="asyncResult"></param>
public void EndCheckForUpdates(IAsyncResult asyncResult)
{
// Wait for operation to complete, then return or throw exception
var ar = (UpdateProcessAsyncResult)asyncResult;
ar.EndInvoke();
}
#endregion
#region Step 2 - Prepare to execute update tasks
/// <summary>
/// Prepare updates synchronously
/// </summary>
public void PrepareUpdates()
{
if (IsWorking)
throw new InvalidOperationException("Another update process is already in progress");
using (WorkScope.New(isWorking => IsWorking = isWorking))
{
lock (UpdatesToApply)
{
if (State != UpdateProcessState.Checked)
throw new InvalidOperationException("Invalid state when calling PrepareUpdates(): " + State);
if (UpdatesToApply.Count == 0)
throw new InvalidOperationException("No updates to prepare");
if (!Directory.Exists(Config.TempFolder))
{
Logger.Log("Creating Temp directory {0}", Config.TempFolder);
Directory.CreateDirectory(Config.TempFolder);
}
else
{
Logger.Log("Using existing Temp directory {0}", Config.TempFolder);
}
foreach (var task in UpdatesToApply)
{
if (ShouldStop)
throw new UserAbortException();
var t = task;
task.ProgressDelegate += status => TaskProgressCallback(status, t);
try
{
task.Prepare(UpdateSource);
}
catch (Exception ex)
{
task.ExecutionStatus = TaskExecutionStatus.FailedToPrepare;
Logger.Log(ex);
throw new UpdateProcessFailedException("Failed to prepare task: " + task.Description, ex);
}
task.ExecutionStatus = TaskExecutionStatus.Prepared;
}
State = UpdateProcessState.Prepared;
}
}
}
/// <summary>
/// Prepare updates asynchronously
/// </summary>
/// <param name="callback">Callback function to call when done; can be null</param>
/// <param name="state">Allows the caller to preserve state; can be null</param>
public IAsyncResult BeginPrepareUpdates(AsyncCallback callback, Object state)
{
// Create IAsyncResult object identifying the
// asynchronous operation
var ar = new UpdateProcessAsyncResult(callback, state);
// Use a thread pool thread to perform the operation
ThreadPool.QueueUserWorkItem(o =>
{
try
{
// Perform the operation; if sucessful set the result
PrepareUpdates();
ar.SetAsCompleted(null, false);
}
catch (Exception e)
{
// If operation fails, set the exception
ar.SetAsCompleted(e, false);
}
}, ar);
return ar; // Return the IAsyncResult to the caller
}
/// <summary>
/// Block until previously-called PrepareUpdates complete
/// </summary>
/// <param name="asyncResult"></param>
public void EndPrepareUpdates(IAsyncResult asyncResult)
{
// Wait for operation to complete, then return or throw exception
var ar = (UpdateProcessAsyncResult)asyncResult;
ar.EndInvoke();
}
#endregion
#region Step 3 - Apply updates
/// <summary>
/// Starts the updater executable and sends update data to it, and relaunch the caller application as soon as its done
/// </summary>
/// <returns>True if successful (unless a restart was required</returns>
public void ApplyUpdates()
{
ApplyUpdates(true);
}
/// <summary>
/// Starts the updater executable and sends update data to it
/// </summary>
/// <param name="relaunchApplication">true if relaunching the caller application is required; false otherwise</param>
/// <returns>True if successful (unless a restart was required</returns>
public void ApplyUpdates(bool relaunchApplication)
{
ApplyUpdates(relaunchApplication, false, false);
}
/// <summary>
/// Starts the updater executable and sends update data to it
/// </summary>
/// <param name="relaunchApplication">true if relaunching the caller application is required; false otherwise</param>
/// <param name="updaterDoLogging">true if the updater writes to a log file; false otherwise</param>
/// <param name="updaterShowConsole">true if the updater shows the console window; false otherwise</param>
/// <returns>True if successful (unless a restart was required</returns>
public void ApplyUpdates(bool relaunchApplication, bool updaterDoLogging, bool updaterShowConsole)
{
if (IsWorking)
throw new InvalidOperationException("Another update process is already in progress");
lock (UpdatesToApply)
{
using (WorkScope.New(isWorking => IsWorking = isWorking))
{
bool revertToDefaultBackupPath = true;
// Set current directory the the application directory
// this prevents the updater from writing to e.g. c:\windows\system32
// if the process is started by autorun on windows logon.
Environment.CurrentDirectory = Path.GetDirectoryName(ApplicationPath);
// Make sure the current backup folder is accessible for writing from this process
string backupParentPath = Path.GetDirectoryName(Config.BackupFolder) ?? string.Empty;
if (Directory.Exists(backupParentPath) && Utils.PermissionsCheck.HaveWritePermissionsForFolder(backupParentPath))
{
// Remove old backup folder, in case this same folder was used previously,
// and it wasn't removed for some reason
try
{
if (Directory.Exists(Config.BackupFolder))
Utils.FileSystem.DeleteDirectory(Config.BackupFolder);
revertToDefaultBackupPath = false;
}
catch (UnauthorizedAccessException)
{
}
// Attempt to (re-)create the backup folder
try
{
Directory.CreateDirectory(Config.BackupFolder);
if (!Utils.PermissionsCheck.HaveWritePermissionsForFolder(Config.BackupFolder))
revertToDefaultBackupPath = true;
}
catch (UnauthorizedAccessException)
{
// We're having permissions issues with this folder, so we'll attempt
// using a backup in a default location
revertToDefaultBackupPath = true;
}
}
if (revertToDefaultBackupPath)
{
Config._backupFolder = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
Config.UpdateProcessName + "UpdateBackups" + DateTime.UtcNow.Ticks);
try
{
Directory.CreateDirectory(Config.BackupFolder);
}
catch (UnauthorizedAccessException ex)
{
// We can't backup, so we abort
throw new UpdateProcessFailedException("Could not create backup folder " + Config.BackupFolder, ex);
}
}
bool runPrivileged = false, hasColdUpdates = false;
State = UpdateProcessState.RollbackRequired;
foreach (var task in UpdatesToApply)
{
IUpdateTask t = task;
task.ProgressDelegate += status => TaskProgressCallback(status, t);
try
{
// Execute the task
task.ExecutionStatus = task.Execute(false);
}
catch (Exception ex)
{
task.ExecutionStatus = TaskExecutionStatus.Failed; // mark the failing task before rethrowing
throw new UpdateProcessFailedException("Update task execution failed: " + task.Description, ex);
}
if (task.ExecutionStatus == TaskExecutionStatus.RequiresAppRestart
|| task.ExecutionStatus == TaskExecutionStatus.RequiresPrivilegedAppRestart)
{
// Record that we have cold updates to run, and if required to run any of them privileged
runPrivileged = runPrivileged || task.ExecutionStatus == TaskExecutionStatus.RequiresPrivilegedAppRestart;
hasColdUpdates = true;
continue;
}
// We are being quite explicit here - only Successful return values are considered
// to be Ok (cold updates are already handled above)
if (task.ExecutionStatus != TaskExecutionStatus.Successful)
throw new UpdateProcessFailedException("Update task execution failed: " + task.Description);
}
// If an application restart is required
if (hasColdUpdates)
{
var dto = new NauIpc.NauDto
{
Configs = Instance.Config,
Tasks = Instance.UpdatesToApply,
AppPath = ApplicationPath,
WorkingDirectory = Environment.CurrentDirectory,
RelaunchApplication = relaunchApplication,
LogItems = Logger.LogItems,
};
NauIpc.ExtractUpdaterFromResource(Config.TempFolder, Instance.Config.UpdateExecutableName);
var info = new ProcessStartInfo
{
UseShellExecute = true,
WorkingDirectory = Environment.CurrentDirectory,
FileName = Path.Combine(Config.TempFolder, Instance.Config.UpdateExecutableName),
Arguments =
string.Format(@"""{0}"" {1} {2}", Config.UpdateProcessName,
updaterShowConsole ? "-showConsole" : string.Empty,
updaterDoLogging ? "-log" : string.Empty),
};
if (!updaterShowConsole)
{
info.WindowStyle = ProcessWindowStyle.Hidden;
info.CreateNoWindow = true;
}
// If we can't write to the destination folder, then lets try elevating priviledges.
if (runPrivileged || !PermissionsCheck.HaveWritePermissionsForFolder(Environment.CurrentDirectory))
{
info.Verb = "runas";
}
bool createdNew;
_shutdownMutex = new Mutex(true, Config.UpdateProcessName + "Mutex", out createdNew);
if (NauIpc.LaunchProcessAndSendDto(dto, info, Config.UpdateProcessName) == null)
throw new UpdateProcessFailedException("Could not launch cold update process");
Environment.Exit(0);
}
State = UpdateProcessState.AppliedSuccessfully;
UpdatesToApply.Clear();
}
}
}
#endregion
public void ReinstateIfRestarted()
{
lock (UpdatesToApply)
{
var dto = NauIpc.ReadDto(Config.UpdateProcessName) as NauIpc.NauDto;
if (dto != null)
{
Config = dto.Configs;
UpdatesToApply = dto.Tasks;
Logger = new Logger(dto.LogItems);
State = UpdateProcessState.AfterRestart;
}
}
}
/// <summary>
/// Rollback executed updates in case of an update failure
/// </summary>
public void RollbackUpdates()
{
if (IsWorking) return;
lock (UpdatesToApply)
{
foreach (var task in UpdatesToApply)
{
task.Rollback();
}
State = UpdateProcessState.NotChecked;
}
}
/// <summary>
/// Abort update process, cancelling whatever background process currently taking place without waiting for it to complete
/// </summary>
public void Abort()
{
Abort(false);
}
/// <summary>
/// Abort update process, cancelling whatever background process currently taking place
/// </summary>
/// <param name="waitForTermination">If true, blocks the calling thread until the current process terminates</param>
public void Abort(bool waitForTermination)
{
ShouldStop = true;
}
/// <summary>
/// Delete the temp folder as a whole and fail silently
/// </summary>
public void CleanUp()
{
Abort(true);
lock (UpdatesToApply)
{
UpdatesToApply.Clear();
State = UpdateProcessState.NotChecked;
try
{
if (Directory.Exists(Config.TempFolder))
Utils.FileSystem.DeleteDirectory(Config.TempFolder);
}
catch { }
try
{
if (Directory.Exists(Config.BackupFolder))
Utils.FileSystem.DeleteDirectory(Config.BackupFolder);
}
catch { }
ShouldStop = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Abp.Authorization.Roles;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.IdentityFramework;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Runtime.Caching;
using Abp.Runtime.Security;
using Abp.Runtime.Session;
using Abp.Timing;
using Abp.Zero;
using Abp.Zero.Configuration;
using Microsoft.AspNet.Identity;
namespace Abp.Authorization.Users
{
/// <summary>
/// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework.
/// </summary>
public abstract class AbpUserManager<TTenant, TRole, TUser>
: UserManager<TUser, long>,
ITransientDependency
where TTenant : AbpTenant<TTenant, TUser>
where TRole : AbpRole<TTenant, TUser>, new()
where TUser : AbpUser<TTenant, TUser>
{
private IUserPermissionStore<TTenant, TUser> UserPermissionStore
{
get
{
if (!(Store is IUserPermissionStore<TTenant, TUser>))
{
throw new AbpException("Store is not IUserPermissionStore");
}
return Store as IUserPermissionStore<TTenant, TUser>;
}
}
public ILocalizationManager LocalizationManager { get; set; }
public IAbpSession AbpSession { get; set; }
protected AbpRoleManager<TTenant, TRole, TUser> RoleManager { get; private set; }
protected ISettingManager SettingManager { get; private set; }
protected AbpUserStore<TTenant, TRole, TUser> AbpStore { get; private set; }
private readonly IPermissionManager _permissionManager;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly IUserManagementConfig _userManagementConfig;
private readonly IIocResolver _iocResolver;
private readonly IRepository<TTenant> _tenantRepository;
private readonly IMultiTenancyConfig _multiTenancyConfig;
private readonly ITypedCache<long, UserPermissionCacheItem> _userPermissionCache;
protected AbpUserManager(
AbpUserStore<TTenant, TRole, TUser> userStore,
AbpRoleManager<TTenant, TRole, TUser> roleManager,
IRepository<TTenant> tenantRepository,
IMultiTenancyConfig multiTenancyConfig,
IPermissionManager permissionManager,
IUnitOfWorkManager unitOfWorkManager,
ISettingManager settingManager,
IUserManagementConfig userManagementConfig,
IIocResolver iocResolver,
ICacheManager cacheManager)
: base(userStore)
{
AbpStore = userStore;
RoleManager = roleManager;
SettingManager = settingManager;
_tenantRepository = tenantRepository;
_multiTenancyConfig = multiTenancyConfig;
_permissionManager = permissionManager;
_unitOfWorkManager = unitOfWorkManager;
_userManagementConfig = userManagementConfig;
_iocResolver = iocResolver;
_userPermissionCache = cacheManager.GetUserPermissionCache();
LocalizationManager = NullLocalizationManager.Instance;
}
public override async Task<IdentityResult> CreateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
if (AbpSession.TenantId.HasValue)
{
user.TenantId = AbpSession.TenantId.Value;
}
return await base.CreateAsync(user);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permissionName">Permission name</param>
public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName)
{
return await IsGrantedAsync(
userId,
_permissionManager.GetPermission(permissionName)
);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission)
{
return IsGrantedAsync(user.Id, permission);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permission">Permission</param>
public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission)
{
//Check for multi-tenancy side
if (!permission.MultiTenancySides.HasFlag(AbpSession.MultiTenancySide))
{
return false;
}
//Get cached user permissions
var cacheItem = await GetUserPermissionCacheItemAsync(userId);
//Check for user-specific value
if (cacheItem.GrantedPermissions.Contains(permission.Name))
{
return true;
}
if (cacheItem.ProhibitedPermissions.Contains(permission.Name))
{
return false;
}
//Check for roles
foreach (var roleId in cacheItem.RoleIds)
{
if (await RoleManager.IsGrantedAsync(roleId, permission))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets granted permissions for a user.
/// </summary>
/// <param name="user">Role</param>
/// <returns>List of granted permissions</returns>
public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user)
{
var permissionList = new List<Permission>();
foreach (var permission in _permissionManager.GetAllPermissions())
{
if (await IsGrantedAsync(user.Id, permission))
{
permissionList.Add(permission);
}
}
return permissionList;
}
/// <summary>
/// Sets all granted permissions of a user at once.
/// Prohibits all other permissions.
/// </summary>
/// <param name="user">The user</param>
/// <param name="permissions">Permissions</param>
public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions)
{
var oldPermissions = await GetGrantedPermissionsAsync(user);
var newPermissions = permissions.ToArray();
foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p)))
{
await ProhibitPermissionAsync(user, permission);
}
foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p)))
{
await GrantPermissionAsync(user, permission);
}
}
/// <summary>
/// Prohibits all permissions for a user.
/// </summary>
/// <param name="user">User</param>
public async Task ProhibitAllPermissionsAsync(TUser user)
{
foreach (var permission in _permissionManager.GetAllPermissions())
{
await ProhibitPermissionAsync(user, permission);
}
}
/// <summary>
/// Resets all permission settings for a user.
/// It removes all permission settings for the user.
/// User will have permissions according to his roles.
/// This method does not prohibit all permissions.
/// For that, use <see cref="ProhibitAllPermissionsAsync"/>.
/// </summary>
/// <param name="user">User</param>
public async Task ResetAllPermissionsAsync(TUser user)
{
await UserPermissionStore.RemoveAllPermissionSettingsAsync(user);
}
/// <summary>
/// Grants a permission for a user if not already granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task GrantPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
if (await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
}
/// <summary>
/// Prohibits a permission for a user if it's granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
if (!await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
}
public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress)
{
return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress);
}
public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login)
{
return AbpStore.FindAllAsync(login);
}
[UnitOfWork]
public virtual async Task<AbpLoginResult> LoginAsync(UserLoginInfo login, string tenancyName = null)
{
if (login == null || login.LoginProvider.IsNullOrEmpty() || login.ProviderKey.IsNullOrEmpty())
{
throw new ArgumentException("login");
}
//Get and check tenant
TTenant tenant = null;
if (!_multiTenancyConfig.IsEnabled)
{
tenant = await GetDefaultTenantAsync();
}
else if (!string.IsNullOrWhiteSpace(tenancyName))
{
tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);
if (tenant == null)
{
return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName);
}
if (!tenant.IsActive)
{
return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive);
}
}
using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
{
var user = await AbpStore.FindAsync(tenant == null ? (int?)null : tenant.Id, login);
if (user == null)
{
return new AbpLoginResult(AbpLoginResultType.UnknownExternalLogin);
}
return await CreateLoginResultAsync(user);
}
}
[UnitOfWork]
public virtual async Task<AbpLoginResult> LoginAsync(string userNameOrEmailAddress, string plainPassword, string tenancyName = null)
{
if (userNameOrEmailAddress.IsNullOrEmpty())
{
throw new ArgumentNullException("userNameOrEmailAddress");
}
if (plainPassword.IsNullOrEmpty())
{
throw new ArgumentNullException("plainPassword");
}
//Get and check tenant
TTenant tenant = null;
if (!_multiTenancyConfig.IsEnabled)
{
tenant = await GetDefaultTenantAsync();
}
else if (!string.IsNullOrWhiteSpace(tenancyName))
{
tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);
if (tenant == null)
{
return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName);
}
if (!tenant.IsActive)
{
return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive);
}
}
using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
{
var loggedInFromExternalSource = await TryLoginFromExternalAuthenticationSources(userNameOrEmailAddress, plainPassword, tenant);
var user = await AbpStore.FindByNameOrEmailAsync(tenant == null ? (int?)null : tenant.Id, userNameOrEmailAddress);
if (user == null)
{
return new AbpLoginResult(AbpLoginResultType.InvalidUserNameOrEmailAddress);
}
if (!loggedInFromExternalSource)
{
var verificationResult = new PasswordHasher().VerifyHashedPassword(user.Password, plainPassword);
if (verificationResult != PasswordVerificationResult.Success)
{
return new AbpLoginResult(AbpLoginResultType.InvalidPassword);
}
}
return await CreateLoginResultAsync(user);
}
}
private async Task<AbpLoginResult> CreateLoginResultAsync(TUser user)
{
if (!user.IsActive)
{
return new AbpLoginResult(AbpLoginResultType.UserIsNotActive);
}
if (await IsEmailConfirmationRequiredForLoginAsync(user.TenantId) && !user.IsEmailConfirmed)
{
return new AbpLoginResult(AbpLoginResultType.UserEmailIsNotConfirmed);
}
user.LastLoginTime = Clock.Now;
await Store.UpdateAsync(user);
await _unitOfWorkManager.Current.SaveChangesAsync();
return new AbpLoginResult(user, await CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie));
}
private async Task<bool> TryLoginFromExternalAuthenticationSources(string userNameOrEmailAddress, string plainPassword, TTenant tenant)
{
if (!_userManagementConfig.ExternalAuthenticationSources.Any())
{
return false;
}
foreach (var sourceType in _userManagementConfig.ExternalAuthenticationSources)
{
using (var source = _iocResolver.ResolveAsDisposable<IExternalAuthenticationSource<TTenant, TUser>>(sourceType))
{
if (await source.Object.TryAuthenticateAsync(userNameOrEmailAddress, plainPassword, tenant))
{
var tenantId = tenant == null ? (int?)null : tenant.Id;
var user = await AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress);
if (user == null)
{
user = await source.Object.CreateUserAsync(userNameOrEmailAddress, tenant);
user.Tenant = tenant;
user.AuthenticationSource = source.Object.Name;
user.Password = new PasswordHasher().HashPassword(Guid.NewGuid().ToString("N").Left(16)); //Setting a random password since it will not be used
user.Roles = new List<UserRole>();
foreach (var defaultRole in RoleManager.Roles.Where(r => r.TenantId == tenantId && r.IsDefault).ToList())
{
user.Roles.Add(new UserRole { RoleId = defaultRole.Id });
}
await Store.CreateAsync(user);
}
else
{
await source.Object.UpdateUserAsync(user, tenant);
user.AuthenticationSource = source.Object.Name;
await Store.UpdateAsync(user);
}
await _unitOfWorkManager.Current.SaveChangesAsync();
return true;
}
}
}
return false;
}
/// <summary>
/// Gets a user by given id.
/// Throws exception if no user found with given id.
/// </summary>
/// <param name="userId">User id</param>
/// <returns>User</returns>
/// <exception cref="AbpException">Throws exception if no user found with given id</exception>
public virtual async Task<TUser> GetUserByIdAsync(long userId)
{
var user = await FindByIdAsync(userId);
if (user == null)
{
throw new AbpException("There is no user with id: " + userId);
}
return user;
}
public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType)
{
var identity = await base.CreateIdentityAsync(user, authenticationType);
if (user.TenantId.HasValue)
{
identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture)));
}
return identity;
}
public async override Task<IdentityResult> UpdateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
var oldUserName = (await GetUserByIdAsync(user.Id)).UserName;
if (oldUserName == AbpUser<TTenant, TUser>.AdminUserName && user.UserName != AbpUser<TTenant, TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TTenant, TUser>.AdminUserName));
}
return await base.UpdateAsync(user);
}
public async override Task<IdentityResult> DeleteAsync(TUser user)
{
if (user.UserName == AbpUser<TTenant, TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TTenant, TUser>.AdminUserName));
}
return await base.DeleteAsync(user);
}
public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword)
{
var result = await PasswordValidator.ValidateAsync(newPassword);
if (!result.Succeeded)
{
return result;
}
await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword));
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
{
var user = (await FindByNameAsync(userName));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateName"), userName));
}
user = (await FindByEmailAsync(emailAddress));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress));
}
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames)
{
//Remove from removed roles
foreach (var userRole in user.Roles.ToList())
{
var role = await RoleManager.FindByIdAsync(userRole.RoleId);
if (roleNames.All(roleName => role.Name != roleName))
{
var result = await RemoveFromRoleAsync(user.Id, role.Name);
if (!result.Succeeded)
{
return result;
}
}
}
//Add to added roles
foreach (var roleName in roleNames)
{
var role = await RoleManager.GetRoleByNameAsync(roleName);
if (user.Roles.All(ur => ur.RoleId != role.Id))
{
var result = await AddToRoleAsync(user.Id, roleName);
if (!result.Succeeded)
{
return result;
}
}
}
return IdentityResult.Success;
}
private async Task<bool> IsEmailConfirmationRequiredForLoginAsync(int? tenantId)
{
if (tenantId.HasValue)
{
return await SettingManager.GetSettingValueForTenantAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin, tenantId.Value);
}
return await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);
}
private async Task<TTenant> GetDefaultTenantAsync()
{
var tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == AbpTenant<TTenant, TUser>.DefaultTenantName);
if (tenant == null)
{
throw new AbpException("There should be a 'Default' tenant if multi-tenancy is disabled!");
}
return tenant;
}
private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId)
{
return await _userPermissionCache.GetAsync(userId, async () =>
{
var newCacheItem = new UserPermissionCacheItem(userId);
foreach (var roleName in await GetRolesAsync(userId))
{
newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id);
}
foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId))
{
if (permissionInfo.IsGranted)
{
newCacheItem.GrantedPermissions.Add(permissionInfo.Name);
}
else
{
newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name);
}
}
return newCacheItem;
});
}
private string L(string name)
{
return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name);
}
public class AbpLoginResult
{
public AbpLoginResultType Result { get; private set; }
public TUser User { get; private set; }
public ClaimsIdentity Identity { get; private set; }
public AbpLoginResult(AbpLoginResultType result)
{
Result = result;
}
public AbpLoginResult(TUser user, ClaimsIdentity identity)
: this(AbpLoginResultType.Success)
{
User = user;
Identity = identity;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Tests.Brokerages
{
public abstract class BrokerageTests
{
// ideally this class would be abstract, but I wanted to keep the order test cases here which use the
// various parameters required from derived types
private IBrokerage _brokerage;
private OrderProvider _orderProvider;
private SecurityProvider _securityProvider;
/// <summary>
/// Provides the data required to test each order type in various cases
/// </summary>
public virtual TestCaseData[] OrderParameters
{
get
{
return new []
{
new TestCaseData(new MarketOrderTestParameters(Symbol)).SetName("MarketOrder"),
new TestCaseData(new LimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("LimitOrder"),
new TestCaseData(new StopMarketOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopMarketOrder"),
new TestCaseData(new StopLimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopLimitOrder")
};
}
}
#region Test initialization and cleanup
[SetUp]
public void Setup()
{
Log.Trace("");
Log.Trace("");
Log.Trace("--- SETUP ---");
Log.Trace("");
Log.Trace("");
// we want to regenerate these for each test
_brokerage = null;
_orderProvider = null;
_securityProvider = null;
Thread.Sleep(1000);
CancelOpenOrders();
LiquidateHoldings();
Thread.Sleep(1000);
}
[TearDown]
public void Teardown()
{
try
{
Log.Trace("");
Log.Trace("");
Log.Trace("--- TEARDOWN ---");
Log.Trace("");
Log.Trace("");
Thread.Sleep(1000);
CancelOpenOrders();
LiquidateHoldings();
Thread.Sleep(1000);
}
finally
{
if (_brokerage != null)
{
DisposeBrokerage(_brokerage);
}
}
}
public IBrokerage Brokerage
{
get
{
if (_brokerage == null)
{
_brokerage = InitializeBrokerage();
}
return _brokerage;
}
}
private IBrokerage InitializeBrokerage()
{
Log.Trace("");
Log.Trace("- INITIALIZING BROKERAGE -");
Log.Trace("");
var brokerage = CreateBrokerage(OrderProvider, SecurityProvider);
brokerage.Connect();
if (!brokerage.IsConnected)
{
Assert.Fail("Failed to connect to brokerage");
}
Log.Trace("");
Log.Trace("GET OPEN ORDERS");
Log.Trace("");
foreach (var openOrder in brokerage.GetOpenOrders())
{
OrderProvider.Add(openOrder);
}
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
foreach (var accountHolding in brokerage.GetAccountHoldings())
{
// these securities don't need to be real, just used for the ISecurityProvider impl, required
// by brokerages to track holdings
SecurityProvider[accountHolding.Symbol] = CreateSecurity(accountHolding.Symbol);
}
brokerage.OrderStatusChanged += (sender, args) =>
{
Log.Trace("");
Log.Trace("ORDER STATUS CHANGED: " + args);
Log.Trace("");
// we need to keep this maintained properly
if (args.Status == OrderStatus.Filled || args.Status == OrderStatus.PartiallyFilled)
{
Log.Trace("FILL EVENT: " + args.FillQuantity + " units of " + args.Symbol.ToString());
Security security;
if (_securityProvider.TryGetValue(args.Symbol, out security))
{
var holding = _securityProvider[args.Symbol].Holdings;
holding.SetHoldings(args.FillPrice, holding.Quantity + args.FillQuantity);
}
else
{
_securityProvider[args.Symbol] = CreateSecurity(args.Symbol);
_securityProvider[args.Symbol].Holdings.SetHoldings(args.FillPrice, args.FillQuantity);
}
Log.Trace("--HOLDINGS: " + _securityProvider[args.Symbol]);
// update order mapping
var order = _orderProvider.GetOrderById(args.OrderId);
order.Status = args.Status;
}
};
return brokerage;
}
internal static Security CreateSecurity(Symbol symbol)
{
return new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
new SubscriptionDataConfig(typeof (TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, false, false, false),
new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));
}
public OrderProvider OrderProvider
{
get { return _orderProvider ?? (_orderProvider = new OrderProvider()); }
}
public SecurityProvider SecurityProvider
{
get { return _securityProvider ?? (_securityProvider = new SecurityProvider()); }
}
/// <summary>
/// Creates the brokerage under test and connects it
/// </summary>
/// <returns>A connected brokerage instance</returns>
protected abstract IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider);
/// <summary>
/// Disposes of the brokerage and any external resources started in order to create it
/// </summary>
/// <param name="brokerage">The brokerage instance to be disposed of</param>
protected virtual void DisposeBrokerage(IBrokerage brokerage)
{
}
/// <summary>
/// This is used to ensure each test starts with a clean, known state.
/// </summary>
protected void LiquidateHoldings()
{
Log.Trace("");
Log.Trace("LIQUIDATE HOLDINGS");
Log.Trace("");
var holdings = Brokerage.GetAccountHoldings();
foreach (var holding in holdings)
{
if (holding.Quantity == 0) continue;
Log.Trace("Liquidating: " + holding);
var order = new MarketOrder(holding.Symbol, (int)-holding.Quantity, DateTime.Now);
_orderProvider.Add(order);
PlaceOrderWaitForStatus(order, OrderStatus.Filled);
}
}
protected void CancelOpenOrders()
{
Log.Trace("");
Log.Trace("CANCEL OPEN ORDERS");
Log.Trace("");
var openOrders = Brokerage.GetOpenOrders();
foreach (var openOrder in openOrders)
{
Log.Trace("Canceling: " + openOrder);
Brokerage.CancelOrder(openOrder);
}
}
#endregion
/// <summary>
/// Gets the symbol to be traded, must be shortable
/// </summary>
protected abstract Symbol Symbol { get; }
/// <summary>
/// Gets the security type associated with the <see cref="Symbol"/>
/// </summary>
protected abstract SecurityType SecurityType { get; }
/// <summary>
/// Gets a high price for the specified symbol so a limit sell won't fill
/// </summary>
protected abstract decimal HighPrice { get; }
/// <summary>
/// Gets a low price for the specified symbol so a limit buy won't fill
/// </summary>
protected abstract decimal LowPrice { get; }
/// <summary>
/// Gets the current market price of the specified security
/// </summary>
protected abstract decimal GetAskPrice(Symbol symbol);
/// <summary>
/// Gets the default order quantity
/// </summary>
protected virtual int GetDefaultQuantity()
{
return 1;
}
[Test]
public void IsConnected()
{
Assert.IsTrue(Brokerage.IsConnected);
}
[Test, TestCaseSource("OrderParameters")]
public void LongFromZero(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("LONG FROM ZERO");
Log.Trace("");
PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void CloseFromLong(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("CLOSE FROM LONG");
Log.Trace("");
// first go long
PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);
// now close it
PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void ShortFromZero(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("SHORT FROM ZERO");
Log.Trace("");
PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void CloseFromShort(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("CLOSE FROM SHORT");
Log.Trace("");
// first go short
PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);
// now close it
PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void ShortFromLong(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("SHORT FROM LONG");
Log.Trace("");
// first go long
PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()));
// now go net short
var order = PlaceOrderWaitForStatus(parameters.CreateShortOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);
if (parameters.ModifyUntilFilled)
{
ModifyOrderUntilFilled(order, parameters);
}
}
[Test, TestCaseSource("OrderParameters")]
public void LongFromShort(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("LONG FROM SHORT");
Log.Trace("");
// first fo short
PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(-GetDefaultQuantity()), OrderStatus.Filled);
// now go long
var order = PlaceOrderWaitForStatus(parameters.CreateLongOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);
if (parameters.ModifyUntilFilled)
{
ModifyOrderUntilFilled(order, parameters);
}
}
[Test]
public void GetCashBalanceContainsUSD()
{
Log.Trace("");
Log.Trace("GET CASH BALANCE");
Log.Trace("");
var balance = Brokerage.GetCashBalance();
Assert.AreEqual(1, balance.Count(x => x.Symbol == "USD"));
}
[Test]
public void GetAccountHoldings()
{
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
var before = Brokerage.GetAccountHoldings();
PlaceOrderWaitForStatus(new MarketOrder(Symbol, GetDefaultQuantity(), DateTime.Now));
var after = Brokerage.GetAccountHoldings();
var beforeHoldings = before.FirstOrDefault(x => x.Symbol == Symbol);
var afterHoldings = after.FirstOrDefault(x => x.Symbol == Symbol);
var beforeQuantity = beforeHoldings == null ? 0 : beforeHoldings.Quantity;
var afterQuantity = afterHoldings == null ? 0 : afterHoldings.Quantity;
Assert.AreEqual(GetDefaultQuantity(), afterQuantity - beforeQuantity);
}
[Test, Ignore("This test requires reading the output and selection of a low volume security for the Brokerageage")]
public void PartialFills()
{
var manualResetEvent = new ManualResetEvent(false);
var qty = 1000000;
var remaining = qty;
var sync = new object();
Brokerage.OrderStatusChanged += (sender, orderEvent) =>
{
lock (sync)
{
remaining -= orderEvent.FillQuantity;
Console.WriteLine("Remaining: " + remaining + " FillQuantity: " + orderEvent.FillQuantity);
if (orderEvent.Status == OrderStatus.Filled)
{
manualResetEvent.Set();
}
}
};
// pick a security with low, but some, volume
var symbol = Symbols.EURUSD;
var order = new MarketOrder(symbol, qty, DateTime.UtcNow) { Id = 1 };
Brokerage.PlaceOrder(order);
// pause for a while to wait for fills to come in
manualResetEvent.WaitOne(2500);
manualResetEvent.WaitOne(2500);
manualResetEvent.WaitOne(2500);
Console.WriteLine("Remaining: " + remaining);
Assert.AreEqual(0, remaining);
}
/// <summary>
/// Updates the specified order in the brokerage until it fills or reaches a timeout
/// </summary>
/// <param name="order">The order to be modified</param>
/// <param name="parameters">The order test parameters that define how to modify the order</param>
/// <param name="secondsTimeout">Maximum amount of time to wait until the order fills</param>
protected void ModifyOrderUntilFilled(Order order, OrderTestParameters parameters, double secondsTimeout = 90)
{
if (order.Status == OrderStatus.Filled)
{
return;
}
var filledResetEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
{
if (args.Status == OrderStatus.Filled)
{
filledResetEvent.Set();
}
if (args.Status == OrderStatus.Canceled || args.Status == OrderStatus.Invalid)
{
Log.Trace("ModifyOrderUntilFilled(): " + order);
Assert.Fail("Unexpected order status: " + args.Status);
}
};
Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;
Log.Trace("");
Log.Trace("MODIFY UNTIL FILLED: " + order);
Log.Trace("");
var stopwatch = Stopwatch.StartNew();
while (!filledResetEvent.WaitOne(3000) && stopwatch.Elapsed.TotalSeconds < secondsTimeout)
{
filledResetEvent.Reset();
if (order.Status == OrderStatus.PartiallyFilled) continue;
var marketPrice = GetAskPrice(order.Symbol);
Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): Ask: " + marketPrice);
var updateOrder = parameters.ModifyOrderToFill(Brokerage, order, marketPrice);
if (updateOrder)
{
if (order.Status == OrderStatus.Filled) break;
Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): " + order);
if (!Brokerage.UpdateOrder(order))
{
Assert.Fail("Brokerage failed to update the order");
}
}
}
Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
}
/// <summary>
/// Places the specified order with the brokerage and wait until we get the <paramref name="expectedStatus"/> back via an OrderStatusChanged event.
/// This function handles adding the order to the <see cref="IOrderProvider"/> instance as well as incrementing the order ID.
/// </summary>
/// <param name="order">The order to be submitted</param>
/// <param name="expectedStatus">The status to wait for</param>
/// <param name="secondsTimeout">Maximum amount of time to wait for <paramref name="expectedStatus"/></param>
/// <returns>The same order that was submitted.</returns>
protected Order PlaceOrderWaitForStatus(Order order, OrderStatus expectedStatus = OrderStatus.Filled, double secondsTimeout = 10.0, bool allowFailedSubmission = false)
{
var requiredStatusEvent = new ManualResetEvent(false);
var desiredStatusEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
{
// no matter what, every order should fire at least one of these
if (args.Status == OrderStatus.Submitted || args.Status == OrderStatus.Invalid)
{
Log.Trace("");
Log.Trace("SUBMITTED: " + args);
Log.Trace("");
requiredStatusEvent.Set();
}
// make sure we fire the status we're expecting
if (args.Status == expectedStatus)
{
Log.Trace("");
Log.Trace("EXPECTED: " + args);
Log.Trace("");
desiredStatusEvent.Set();
}
};
Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;
OrderProvider.Add(order);
if (!Brokerage.PlaceOrder(order) && !allowFailedSubmission)
{
Assert.Fail("Brokerage failed to place the order: " + order);
}
requiredStatusEvent.WaitOneAssertFail((int) (1000*secondsTimeout), "Expected every order to fire a submitted or invalid status event");
desiredStatusEvent.WaitOneAssertFail((int) (1000*secondsTimeout), "OrderStatus " + expectedStatus + " was not encountered within the timeout.");
Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
return order;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.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 OpenSimulator 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.Xml;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes.Scripting;
using OpenSim.Region.Framework.Scenes.Serialization;
namespace OpenSim.Region.Framework.Scenes
{
public class SceneObjectPartInventory : IEntityInventory
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_inventoryFileName = String.Empty;
private byte[] m_inventoryFileData = new byte[0];
private uint m_inventoryFileNameSerial = 0;
/// <value>
/// The part to which the inventory belongs.
/// </value>
private SceneObjectPart m_part;
/// <summary>
/// Serial count for inventory file , used to tell if inventory has changed
/// no need for this to be part of Database backup
/// </summary>
protected uint m_inventorySerial = 0;
/// <summary>
/// Holds in memory prim inventory
/// </summary>
protected TaskInventoryDictionary m_items = new TaskInventoryDictionary();
/// <summary>
/// Tracks whether inventory has changed since the last persistent backup
/// </summary>
internal bool HasInventoryChanged;
/// <value>
/// Inventory serial number
/// </value>
protected internal uint Serial
{
get { return m_inventorySerial; }
set { m_inventorySerial = value; }
}
/// <value>
/// Raw inventory data
/// </value>
protected internal TaskInventoryDictionary Items
{
get { return m_items; }
set
{
m_items = value;
m_inventorySerial++;
QueryScriptStates();
}
}
public int Count
{
get
{
lock (m_items)
return m_items.Count;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="part">
/// A <see cref="SceneObjectPart"/>
/// </param>
public SceneObjectPartInventory(SceneObjectPart part)
{
m_part = part;
}
/// <summary>
/// Force the task inventory of this prim to persist at the next update sweep
/// </summary>
public void ForceInventoryPersistence()
{
HasInventoryChanged = true;
}
/// <summary>
/// Reset UUIDs for all the items in the prim's inventory.
/// </summary>
/// <remarks>
/// This involves either generating
/// new ones or setting existing UUIDs to the correct parent UUIDs.
///
/// If this method is called and there are inventory items, then we regard the inventory as having changed.
/// </remarks>
public void ResetInventoryIDs()
{
if (null == m_part)
return;
lock (m_items)
{
if (0 == m_items.Count)
return;
IList<TaskInventoryItem> items = GetInventoryItems();
m_items.Clear();
foreach (TaskInventoryItem item in items)
{
item.ResetIDs(m_part.UUID);
m_items.Add(item.ItemID, item);
}
}
}
public void ResetObjectID()
{
lock (Items)
{
IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
Items.Clear();
foreach (TaskInventoryItem item in items)
{
item.ParentPartID = m_part.UUID;
item.ParentID = m_part.UUID;
Items.Add(item.ItemID, item);
}
}
}
/// <summary>
/// Change every item in this inventory to a new owner.
/// </summary>
/// <param name="ownerId"></param>
public void ChangeInventoryOwner(UUID ownerId)
{
lock (Items)
{
if (0 == Items.Count)
{
return;
}
}
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
List<TaskInventoryItem> items = GetInventoryItems();
foreach (TaskInventoryItem item in items)
{
if (ownerId != item.OwnerID)
item.LastOwnerID = item.OwnerID;
item.OwnerID = ownerId;
item.PermsMask = 0;
item.PermsGranter = UUID.Zero;
item.OwnerChanged = true;
}
}
/// <summary>
/// Change every item in this inventory to a new group.
/// </summary>
/// <param name="groupID"></param>
public void ChangeInventoryGroup(UUID groupID)
{
lock (Items)
{
if (0 == Items.Count)
{
return;
}
}
// Don't let this set the HasGroupChanged flag for attachments
// as this happens during rez and we don't want a new asset
// for each attachment each time
if (!m_part.ParentGroup.IsAttachment)
{
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
List<TaskInventoryItem> items = GetInventoryItems();
foreach (TaskInventoryItem item in items)
{
if (groupID != item.GroupID)
item.GroupID = groupID;
}
}
private void QueryScriptStates()
{
if (m_part == null || m_part.ParentGroup == null || m_part.ParentGroup.Scene == null)
return;
lock (Items)
{
foreach (TaskInventoryItem item in Items.Values)
{
bool running;
if (TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running))
item.ScriptRunning = running;
}
}
}
public bool TryGetScriptInstanceRunning(UUID itemId, out bool running)
{
running = false;
TaskInventoryItem item = GetInventoryItem(itemId);
if (item == null)
return false;
return TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running);
}
public static bool TryGetScriptInstanceRunning(Scene scene, TaskInventoryItem item, out bool running)
{
running = false;
if (item.InvType != (int)InventoryType.LSL)
return false;
IScriptModule[] engines = scene.RequestModuleInterfaces<IScriptModule>();
if (engines == null) // No engine at all
return false;
foreach (IScriptModule e in engines)
{
if (e.HasScript(item.ItemID, out running))
return true;
}
return false;
}
public int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource)
{
int scriptsValidForStarting = 0;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
if (CreateScriptInstance(item, startParam, postOnRez, engine, stateSource))
scriptsValidForStarting++;
return scriptsValidForStarting;
}
public ArrayList GetScriptErrors(UUID itemID)
{
ArrayList ret = new ArrayList();
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
foreach (IScriptModule e in engines)
{
if (e != null)
{
ArrayList errors = e.GetScriptErrors(itemID);
foreach (Object line in errors)
ret.Add(line);
}
}
return ret;
}
/// <summary>
/// Stop and remove all the scripts in this prim.
/// </summary>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if these scripts are being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void RemoveScriptInstances(bool sceneObjectBeingDeleted)
{
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted);
}
/// <summary>
/// Stop all the scripts in this prim.
/// </summary>
public void StopScriptInstances()
{
GetInventoryItems(InventoryType.LSL).ForEach(i => StopScriptInstance(i));
}
/// <summary>
/// Start a script which is in this prim's inventory.
/// </summary>
/// <param name="item"></param>
/// <returns>true if the script instance was created, false otherwise</returns>
public bool CreateScriptInstance(TaskInventoryItem item, int startParam, bool postOnRez, string engine, int stateSource)
{
// m_log.DebugFormat("[PRIM INVENTORY]: Starting script {0} {1} in prim {2} {3} in {4}",
// item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName);
if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID))
return false;
m_part.AddFlag(PrimFlags.Scripted);
if (m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts)
return false;
if (stateSource == 2 && // Prim crossing
m_part.ParentGroup.Scene.m_trustBinaries)
{
lock (m_items)
{
m_items[item.ItemID].PermsMask = 0;
m_items[item.ItemID].PermsGranter = UUID.Zero;
}
m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource);
m_part.ParentGroup.AddActiveScriptCount(1);
m_part.ScheduleFullUpdate();
return true;
}
AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString());
if (null == asset)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
item.Name, item.ItemID, m_part.AbsolutePosition,
m_part.ParentGroup.Scene.RegionInfo.RegionName, item.AssetID);
return false;
}
else
{
if (m_part.ParentGroup.m_savedScriptState != null)
item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID);
lock (m_items)
{
m_items[item.ItemID].OldItemID = item.OldItemID;
m_items[item.ItemID].PermsMask = 0;
m_items[item.ItemID].PermsGranter = UUID.Zero;
}
string script = Utils.BytesToString(asset.Data);
m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource);
if (!item.ScriptRunning)
m_part.ParentGroup.Scene.EventManager.TriggerStopScript(
m_part.LocalId, item.ItemID);
m_part.ParentGroup.AddActiveScriptCount(1);
m_part.ScheduleFullUpdate();
return true;
}
}
private UUID RestoreSavedScriptState(UUID loadedID, UUID oldID, UUID newID)
{
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0) // No engine at all
return oldID;
UUID stateID = oldID;
if (!m_part.ParentGroup.m_savedScriptState.ContainsKey(oldID))
stateID = loadedID;
if (m_part.ParentGroup.m_savedScriptState.ContainsKey(stateID))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(m_part.ParentGroup.m_savedScriptState[stateID]);
////////// CRUFT WARNING ///////////////////////////////////
//
// Old objects will have <ScriptState><State> ...
// This format is XEngine ONLY
//
// New objects have <State Engine="...." ...><ScriptState>...
// This can be passed to any engine
//
XmlNode n = doc.SelectSingleNode("ScriptState");
if (n != null) // Old format data
{
XmlDocument newDoc = new XmlDocument();
XmlElement rootN = newDoc.CreateElement("", "State", "");
XmlAttribute uuidA = newDoc.CreateAttribute("", "UUID", "");
uuidA.Value = stateID.ToString();
rootN.Attributes.Append(uuidA);
XmlAttribute engineA = newDoc.CreateAttribute("", "Engine", "");
engineA.Value = "XEngine";
rootN.Attributes.Append(engineA);
newDoc.AppendChild(rootN);
XmlNode stateN = newDoc.ImportNode(n, true);
rootN.AppendChild(stateN);
// This created document has only the minimun data
// necessary for XEngine to parse it successfully
m_part.ParentGroup.m_savedScriptState[stateID] = newDoc.OuterXml;
}
foreach (IScriptModule e in engines)
{
if (e != null)
{
if (e.SetXMLState(newID, m_part.ParentGroup.m_savedScriptState[stateID]))
break;
}
}
m_part.ParentGroup.m_savedScriptState.Remove(stateID);
}
return stateID;
}
public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
{
TaskInventoryItem item = GetInventoryItem(itemId);
if (item != null)
{
return CreateScriptInstance(item, startParam, postOnRez, engine, stateSource);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
itemId, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
return false;
}
}
/// <summary>
/// Stop and remove a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if this script is being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted)
{
bool scriptPresent = false;
lock (m_items)
{
if (m_items.ContainsKey(itemId))
scriptPresent = true;
}
if (scriptPresent)
{
if (!sceneObjectBeingDeleted)
m_part.RemoveScriptEvents(itemId);
m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemId);
m_part.ParentGroup.AddActiveScriptCount(-1);
}
else
{
m_log.WarnFormat(
"[PRIM INVENTORY]: " +
"Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
itemId, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
}
/// <summary>
/// Stop a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if this script is being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void StopScriptInstance(UUID itemId)
{
TaskInventoryItem scriptItem;
lock (m_items)
m_items.TryGetValue(itemId, out scriptItem);
if (scriptItem != null)
{
StopScriptInstance(scriptItem);
}
else
{
m_log.WarnFormat(
"[PRIM INVENTORY]: " +
"Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
itemId, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
}
/// <summary>
/// Stop a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if this script is being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void StopScriptInstance(TaskInventoryItem item)
{
m_part.ParentGroup.Scene.EventManager.TriggerStopScript(m_part.LocalId, item.ItemID);
// At the moment, even stopped scripts are counted as active, which is probably wrong.
// m_part.ParentGroup.AddActiveScriptCount(-1);
}
/// <summary>
/// Check if the inventory holds an item with a given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private bool InventoryContainsName(string name)
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Name == name)
return true;
}
}
return false;
}
/// <summary>
/// For a given item name, return that name if it is available. Otherwise, return the next available
/// similar name (which is currently the original name with the next available numeric suffix).
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private string FindAvailableInventoryName(string name)
{
if (!InventoryContainsName(name))
return name;
int suffix=1;
while (suffix < 256)
{
string tryName=String.Format("{0} {1}", name, suffix);
if (!InventoryContainsName(tryName))
return tryName;
suffix++;
}
return String.Empty;
}
/// <summary>
/// Add an item to this prim's inventory. If an item with the same name already exists, then an alternative
/// name is chosen.
/// </summary>
/// <param name="item"></param>
public void AddInventoryItem(TaskInventoryItem item, bool allowedDrop)
{
AddInventoryItem(item.Name, item, allowedDrop);
}
/// <summary>
/// Add an item to this prim's inventory. If an item with the same name already exists, it is replaced.
/// </summary>
/// <param name="item"></param>
public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop)
{
List<TaskInventoryItem> il = GetInventoryItems();
foreach (TaskInventoryItem i in il)
{
if (i.Name == item.Name)
{
if (i.InvType == (int)InventoryType.LSL)
RemoveScriptInstance(i.ItemID, false);
RemoveInventoryItem(i.ItemID);
break;
}
}
AddInventoryItem(item.Name, item, allowedDrop);
}
/// <summary>
/// Add an item to this prim's inventory.
/// </summary>
/// <param name="name">The name that the new item should have.</param>
/// <param name="item">
/// The item itself. The name within this structure is ignored in favour of the name
/// given in this method's arguments
/// </param>
/// <param name="allowedDrop">
/// Item was only added to inventory because AllowedDrop is set
/// </param>
protected void AddInventoryItem(string name, TaskInventoryItem item, bool allowedDrop)
{
name = FindAvailableInventoryName(name);
if (name == String.Empty)
return;
item.ParentID = m_part.UUID;
item.ParentPartID = m_part.UUID;
item.Name = name;
item.GroupID = m_part.GroupID;
lock (m_items)
m_items.Add(item.ItemID, item);
if (allowedDrop)
m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP);
else
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
m_inventorySerial++;
//m_inventorySerial += 2;
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
/// <summary>
/// Restore a whole collection of items to the prim's inventory at once.
/// We assume that the items already have all their fields correctly filled out.
/// The items are not flagged for persistence to the database, since they are being restored
/// from persistence rather than being newly added.
/// </summary>
/// <param name="items"></param>
public void RestoreInventoryItems(ICollection<TaskInventoryItem> items)
{
lock (m_items)
{
foreach (TaskInventoryItem item in items)
{
m_items.Add(item.ItemID, item);
// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
}
m_inventorySerial++;
}
}
/// <summary>
/// Returns an existing inventory item. Returns the original, so any changes will be live.
/// </summary>
/// <param name="itemID"></param>
/// <returns>null if the item does not exist</returns>
public TaskInventoryItem GetInventoryItem(UUID itemId)
{
TaskInventoryItem item;
lock (m_items)
m_items.TryGetValue(itemId, out item);
return item;
}
public TaskInventoryItem GetInventoryItem(string name)
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Name == name)
return item;
}
}
return null;
}
public List<TaskInventoryItem> GetInventoryItems(string name)
{
List<TaskInventoryItem> items = new List<TaskInventoryItem>();
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Name == name)
items.Add(item);
}
}
return items;
}
public SceneObjectGroup GetRezReadySceneObject(TaskInventoryItem item)
{
AssetBase rezAsset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString());
if (null == rezAsset)
{
m_log.WarnFormat(
"[PRIM INVENTORY]: Could not find asset {0} for inventory item {1} in {2}",
item.AssetID, item.Name, m_part.Name);
return null;
}
string xmlData = Utils.BytesToString(rezAsset.Data);
SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData);
group.ResetIDs();
SceneObjectPart rootPart = group.GetPart(group.UUID);
// Since renaming the item in the inventory does not affect the name stored
// in the serialization, transfer the correct name from the inventory to the
// object itself before we rez.
rootPart.Name = item.Name;
rootPart.Description = item.Description;
SceneObjectPart[] partList = group.Parts;
group.SetGroup(m_part.GroupID, null);
// TODO: Remove magic number badness
if ((rootPart.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0) // Magic number
{
if (m_part.ParentGroup.Scene.Permissions.PropagatePermissions())
{
foreach (SceneObjectPart part in partList)
{
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0)
part.EveryoneMask = item.EveryonePermissions;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0)
part.NextOwnerMask = item.NextPermissions;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0)
part.GroupMask = item.GroupPermissions;
}
group.ApplyNextOwnerPermissions();
}
}
foreach (SceneObjectPart part in partList)
{
// TODO: Remove magic number badness
if ((part.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0) // Magic number
{
part.LastOwnerID = part.OwnerID;
part.OwnerID = item.OwnerID;
part.Inventory.ChangeInventoryOwner(item.OwnerID);
}
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0)
part.EveryoneMask = item.EveryonePermissions;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0)
part.NextOwnerMask = item.NextPermissions;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0)
part.GroupMask = item.GroupPermissions;
}
rootPart.TrimPermissions();
return group;
}
/// <summary>
/// Update an existing inventory item.
/// </summary>
/// <param name="item">The updated item. An item with the same id must already exist
/// in this prim's inventory.</param>
/// <returns>false if the item did not exist, true if the update occurred successfully</returns>
public bool UpdateInventoryItem(TaskInventoryItem item)
{
return UpdateInventoryItem(item, true, true);
}
public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents)
{
return UpdateInventoryItem(item, fireScriptEvents, true);
}
public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged)
{
TaskInventoryItem it = GetInventoryItem(item.ItemID);
if (it != null)
{
// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name);
item.ParentID = m_part.UUID;
item.ParentPartID = m_part.UUID;
// If group permissions have been set on, check that the groupID is up to date in case it has
// changed since permissions were last set.
if (item.GroupPermissions != (uint)PermissionMask.None)
item.GroupID = m_part.GroupID;
if (item.AssetID == UUID.Zero)
item.AssetID = it.AssetID;
lock (m_items)
{
m_items[item.ItemID] = item;
m_inventorySerial++;
}
if (fireScriptEvents)
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
if (considerChanged)
{
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory",
item.ItemID, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
return false;
}
/// <summary>
/// Remove an item from this prim's inventory
/// </summary>
/// <param name="itemID"></param>
/// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist
/// in this prim's inventory.</returns>
public int RemoveInventoryItem(UUID itemID)
{
TaskInventoryItem item = GetInventoryItem(itemID);
if (item != null)
{
int type = m_items[itemID].InvType;
if (type == 10) // Script
{
m_part.RemoveScriptEvents(itemID);
m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID);
}
m_items.Remove(itemID);
m_inventorySerial++;
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
if (!ContainsScripts())
m_part.RemFlag(PrimFlags.Scripted);
m_part.ScheduleFullUpdate();
return type;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Tried to remove item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory",
itemID, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
return -1;
}
private bool CreateInventoryFile()
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}",
// m_part.Name, m_part.UUID, m_part.LocalId, m_inventorySerial);
if (m_inventoryFileName == String.Empty ||
m_inventoryFileNameSerial < m_inventorySerial)
{
// Something changed, we need to create a new file
m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp";
m_inventoryFileNameSerial = m_inventorySerial;
InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Adding item {0} {1} for serial {2} on prim {3} {4} {5}",
// item.Name, item.ItemID, m_inventorySerial, m_part.Name, m_part.UUID, m_part.LocalId);
UUID ownerID = item.OwnerID;
uint everyoneMask = 0;
uint baseMask = item.BasePermissions;
uint ownerMask = item.CurrentPermissions;
uint groupMask = item.GroupPermissions;
invString.AddItemStart();
invString.AddNameValueLine("item_id", item.ItemID.ToString());
invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
invString.AddPermissionsStart();
invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
invString.AddNameValueLine("owner_id", ownerID.ToString());
invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
invString.AddNameValueLine("group_id", item.GroupID.ToString());
invString.AddSectionEnd();
invString.AddNameValueLine("asset_id", item.AssetID.ToString());
invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
invString.AddSaleStart();
invString.AddNameValueLine("sale_type", "not");
invString.AddNameValueLine("sale_price", "0");
invString.AddSectionEnd();
invString.AddNameValueLine("name", item.Name + "|");
invString.AddNameValueLine("desc", item.Description + "|");
invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
invString.AddSectionEnd();
}
}
m_inventoryFileData = Utils.StringToBytes(invString.BuildString);
return true;
}
// No need to recreate, the existing file is fine
return false;
}
/// <summary>
/// Serialize all the metadata for the items in this prim's inventory ready for sending to the client
/// </summary>
/// <param name="xferManager"></param>
public void RequestInventoryFile(IClientAPI client, IXfer xferManager)
{
lock (m_items)
{
// Don't send a inventory xfer name if there are no items. Doing so causes viewer 3 to crash when rezzing
// a new script if any previous deletion has left the prim inventory empty.
if (m_items.Count == 0) // No inventory
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Not sending inventory data for part {0} {1} {2} for {3} since no items",
// m_part.Name, m_part.LocalId, m_part.UUID, client.Name);
client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
return;
}
CreateInventoryFile();
// In principle, we should only do the rest if the inventory changed;
// by sending m_inventorySerial to the client, it ought to know
// that nothing changed and that it doesn't need to request the file.
// Unfortunately, it doesn't look like the client optimizes this;
// the client seems to always come back and request the Xfer,
// no matter what value m_inventorySerial has.
// FIXME: Could probably be > 0 here rather than > 2
if (m_inventoryFileData.Length > 2)
{
// Add the file for Xfer
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Adding inventory file {0} (length {1}) for transfer on {2} {3} {4}",
// m_inventoryFileName, m_inventoryFileData.Length, m_part.Name, m_part.UUID, m_part.LocalId);
xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData);
}
// Tell the client we're ready to Xfer the file
client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
Util.StringToBytes256(m_inventoryFileName));
}
}
/// <summary>
/// Process inventory backup
/// </summary>
/// <param name="datastore"></param>
public void ProcessInventoryBackup(ISimulationDataService datastore)
{
if (HasInventoryChanged)
{
HasInventoryChanged = false;
List<TaskInventoryItem> items = GetInventoryItems();
datastore.StorePrimInventory(m_part.UUID, items);
}
}
public class InventoryStringBuilder
{
public string BuildString = String.Empty;
public InventoryStringBuilder(UUID folderID, UUID parentID)
{
BuildString += "\tinv_object\t0\n\t{\n";
AddNameValueLine("obj_id", folderID.ToString());
AddNameValueLine("parent_id", parentID.ToString());
AddNameValueLine("type", "category");
AddNameValueLine("name", "Contents|");
AddSectionEnd();
}
public void AddItemStart()
{
BuildString += "\tinv_item\t0\n";
AddSectionStart();
}
public void AddPermissionsStart()
{
BuildString += "\tpermissions 0\n";
AddSectionStart();
}
public void AddSaleStart()
{
BuildString += "\tsale_info\t0\n";
AddSectionStart();
}
protected void AddSectionStart()
{
BuildString += "\t{\n";
}
public void AddSectionEnd()
{
BuildString += "\t}\n";
}
public void AddLine(string addLine)
{
BuildString += addLine;
}
public void AddNameValueLine(string name, string value)
{
BuildString += "\t\t";
BuildString += name + "\t";
BuildString += value + "\n";
}
public void Close()
{
}
}
public uint MaskEffectivePermissions()
{
uint mask=0x7fffffff;
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
mask &= ~((uint)PermissionMask.Copy >> 13);
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
mask &= ~((uint)PermissionMask.Transfer >> 13);
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
mask &= ~((uint)PermissionMask.Modify >> 13);
if (item.InvType != (int)InventoryType.Object)
{
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
mask &= ~((uint)PermissionMask.Copy >> 13);
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
mask &= ~((uint)PermissionMask.Transfer >> 13);
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
mask &= ~((uint)PermissionMask.Modify >> 13);
}
else
{
if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
mask &= ~((uint)PermissionMask.Copy >> 13);
if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
mask &= ~((uint)PermissionMask.Transfer >> 13);
if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
mask &= ~((uint)PermissionMask.Modify >> 13);
}
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
mask &= ~(uint)PermissionMask.Copy;
if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
mask &= ~(uint)PermissionMask.Transfer;
if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
mask &= ~(uint)PermissionMask.Modify;
}
}
return mask;
}
public void ApplyNextOwnerPermissions()
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
// m_log.DebugFormat (
// "[SCENE OBJECT PART INVENTORY]: Applying next permissions {0} to {1} in {2} with current {3}, base {4}, everyone {5}",
// item.NextPermissions, item.Name, m_part.Name, item.CurrentPermissions, item.BasePermissions, item.EveryonePermissions);
if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
{
if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
}
item.CurrentPermissions &= item.NextPermissions;
item.BasePermissions &= item.NextPermissions;
item.EveryonePermissions &= item.NextPermissions;
item.OwnerChanged = true;
item.PermsMask = 0;
item.PermsGranter = UUID.Zero;
}
}
}
public void ApplyGodPermissions(uint perms)
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
item.CurrentPermissions = perms;
item.BasePermissions = perms;
}
}
m_inventorySerial++;
HasInventoryChanged = true;
}
/// <summary>
/// Returns true if this part inventory contains any scripts. False otherwise.
/// </summary>
/// <returns></returns>
public bool ContainsScripts()
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
{
return true;
}
}
}
return false;
}
/// <summary>
/// Returns the count of scripts in this parts inventory.
/// </summary>
/// <returns></returns>
public int ScriptCount()
{
int count = 0;
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
{
count++;
}
}
}
return count;
}
/// <summary>
/// Returns the count of running scripts in this parts inventory.
/// </summary>
/// <returns></returns>
public int RunningScriptCount()
{
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0)
return 0;
int count = 0;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
{
foreach (IScriptModule engine in engines)
{
if (engine != null)
{
if (engine.GetScriptState(item.ItemID))
{
count++;
}
}
}
}
return count;
}
public List<UUID> GetInventoryList()
{
List<UUID> ret = new List<UUID>();
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
ret.Add(item.ItemID);
}
return ret;
}
public List<TaskInventoryItem> GetInventoryItems()
{
List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
lock (m_items)
ret = new List<TaskInventoryItem>(m_items.Values);
return ret;
}
public List<TaskInventoryItem> GetInventoryItems(InventoryType type)
{
List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
if (item.InvType == (int)type)
ret.Add(item);
}
return ret;
}
public Dictionary<UUID, string> GetScriptStates()
{
Dictionary<UUID, string> ret = new Dictionary<UUID, string>();
if (m_part.ParentGroup.Scene == null) // Group not in a scene
return ret;
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0) // No engine at all
return ret;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
{
foreach (IScriptModule e in engines)
{
if (e != null)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Getting script state from engine {0} for {1} in part {2} in group {3} in {4}",
// e.Name, item.Name, m_part.Name, m_part.ParentGroup.Name, m_part.ParentGroup.Scene.Name);
string n = e.GetXMLState(item.ItemID);
if (n != String.Empty)
{
if (!ret.ContainsKey(item.ItemID))
ret[item.ItemID] = n;
break;
}
}
}
}
return ret;
}
public void ResumeScripts()
{
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0)
return;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
{
foreach (IScriptModule engine in engines)
{
if (engine != null)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Resuming script {0} {1} for {2}, OwnerChanged {3}",
// item.Name, item.ItemID, item.OwnerID, item.OwnerChanged);
engine.ResumeScript(item.ItemID);
if (item.OwnerChanged)
engine.PostScriptEvent(item.ItemID, "changed", new Object[] { (int)Changed.OWNER });
item.OwnerChanged = false;
}
}
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A dry-cleaning business.
/// </summary>
public class DryCleaningOrLaundry_Core : TypeCore, ILocalBusiness
{
public DryCleaningOrLaundry_Core()
{
this._TypeId = 77;
this._Id = "DryCleaningOrLaundry";
this._Schema_Org_Url = "http://schema.org/DryCleaningOrLaundry";
string label = "";
GetLabel(out label, "DryCleaningOrLaundry", typeof(DryCleaningOrLaundry_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{155};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
#region License
/*
Copyright (c) 2010-2014 Danko Kozar
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 License
using System;
using System.Globalization;
using System.Reflection;
using UnityEngine;
namespace eDriven.Core.Reflection
{
/// <summary>
/// The wrapper around the class member<br/>
/// The main idea behind this approach is that whis wrapper could be cached<br/>
/// and reused per class basis
/// </summary>
public class MemberWrapper
{
#if DEBUG
// ReSharper disable UnassignedField.Global
/// <summary>
/// Debug mode
/// </summary>
public static bool DebugMode;
// ReSharper restore UnassignedField.Global
#endif
private readonly bool _isField;
private readonly FieldInfo _fieldInfo;
private readonly PropertyInfo _propertyInfo;
private static bool _found;
/// <summary>
/// A flag indicating this is a nullable type, so we'll need the conversion when setting the value
/// </summary>
private readonly Type _nullableType;
private readonly Type _memberType;
/// <summary>
/// Member type resolved by this wrapper
/// </summary>
public Type MemberType
{
get
{
return _memberType;
}
}
/// <summary>
/// Constructor (empty)
/// Because of type params
/// </summary>
public MemberWrapper()
{
// do nothing
throw new Exception("Do not use this constructor");
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Target type</param>
/// <param name="name">Variable name</param>
public MemberWrapper(Type type, string name)
{
#if DEBUG
if (DebugMode)
{
Debug.Log(string.Format("Creating MemberWrapper [{0}, {1}]", type, name));
}
#endif
_found = false;
// 1. properties
_propertyInfo = type.GetProperty(name); //, /*BindingFlags.Instance | */BindingFlags.Public/* | BindingFlags.NonPublic*/);
if (null != _propertyInfo)
{
_memberType = _propertyInfo.PropertyType;
_found = true;
}
else
{
// 2.a. public fields, 2.b, private fields
_fieldInfo = type.GetField(name) ?? type.GetField(name, BindingFlags.Instance | BindingFlags.NonPublic);
if (null != _fieldInfo)
{
_memberType = _fieldInfo.FieldType;
_isField = true;
_found = true;
}
}
/*Debug.Log("* " + _memberType.Name + " (" + _memberType.FullName + ")");
if (null == _memberType)
throw new Exception("Couldn't reflect member: " + _memberType);*/
if (null != _memberType)
_nullableType = Nullable.GetUnderlyingType(_memberType);
if (!_found)
throw new MemberNotFoundException(string.Format(@"Couldn't find property nor field named ""{0}"" [{1}]", name, type));
#if DEBUG
if (DebugMode)
{
Debug.Log(string.Format(" -> Created: {0}, {1} [{2}]", type, name, _isField));
}
#endif
}
/// <summary>
/// Sets value on specified target
/// </summary>
/// <param name="target"></param>
/// <param name="value"></param>
public void SetValue(object target, object value)
{
if (_isField)
{
#if DEBUG
if (DebugMode)
{
Debug.Log(string.Format("Setting FIELD value {0} for {1} on target {2}", value, _propertyInfo.Name, target));
}
#endif
try
{
if (null != _nullableType)
{
try
{
_fieldInfo.SetValue(
target,
null != value ? Convert.ChangeType(value, _nullableType) : null
);
}
catch (Exception ex)
{
throw new Exception("Cannot convert to nullable type", ex);
}
}
else
{
_fieldInfo.SetValue(target, value
/*, BindingFlags.Public | BindingFlags.NonPublic, null, CultureInfo.CurrentCulture*/);
}
}
catch (Exception ex)
{
throw new Exception("Cannot set value", ex);
}
}
else
{
#if DEBUG
if (DebugMode)
{
Debug.Log(string.Format("Setting PROPERTY value {0} for {1} on target {2}", value, _propertyInfo.Name, target));
}
#endif
if (null != _nullableType)
{
try
{
_propertyInfo.SetValue(
target,
null != value ? Convert.ChangeType(value, _nullableType) : null,
null
);
}
catch (Exception ex)
{
throw new Exception("Cannot convert to nullable type: " + ex);
}
}
else
{
_propertyInfo.SetValue(target, value, null);
}
}
}
/// <summary>
/// Gets value from specified target
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public object GetValue(object target)
{
if (_isField)
{
return _fieldInfo.GetValue(target);
}
return _propertyInfo.GetValue(target, null);
}
/// <summary>
/// Returns the member info
/// </summary>
public MemberInfo MemberInfo
{
get
{
if (_isField)
{
return _fieldInfo;
}
return _propertyInfo;
}
}
public override string ToString()
{
return string.Format("MemberType: {0}, IsField: {1}", _memberType, _isField);
}
}
}
| |
#region Copyright
//
// Nini Configuration Project.
// Copyright (C) 2006 Brent R. Matzelle. All rights reserved.
//
// This software is published under the terms of the MIT X11 license, a copy of
// which has been included with this distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.Collections;
namespace Nini.Config
{
#region ConfigEventHandler class
/// <include file='ConfigEventArgs.xml' path='//Delegate[@name="ConfigEventHandler"]/docs/*' />
public delegate void ConfigEventHandler (object sender, ConfigEventArgs e);
/// <include file='ConfigEventArgs.xml' path='//Class[@name="ConfigEventArgs"]/docs/*' />
public class ConfigEventArgs : EventArgs
{
IConfig config = null;
/// <include file='ConfigEventArgs.xml' path='//Constructor[@name="ConstructorIConfig"]/docs/*' />
public ConfigEventArgs (IConfig config)
{
this.config = config;
}
/// <include file='ConfigEventArgs.xml' path='//Property[@name="Config"]/docs/*' />
public IConfig Config
{
get { return config; }
}
}
#endregion
/// <include file='ConfigCollection.xml' path='//Class[@name="ConfigCollection"]/docs/*' />
public class ConfigCollection : ICollection, IEnumerable, IList
{
#region Private variables
ArrayList configList = new ArrayList ();
ConfigSourceBase owner = null;
#endregion
#region Constructors
/// <include file='ConfigCollection.xml' path='//Constructor[@name="Constructor"]/docs/*' />
public ConfigCollection (ConfigSourceBase owner)
{
this.owner = owner;
}
#endregion
#region Public properties
/// <include file='ConfigCollection.xml' path='//Property[@name="Count"]/docs/*' />
public int Count
{
get { return configList.Count; }
}
/// <include file='ConfigCollection.xml' path='//Property[@name="IsSynchronized"]/docs/*' />
public bool IsSynchronized
{
get { return false; }
}
/// <include file='ConfigCollection.xml' path='//Property[@name="SyncRoot"]/docs/*' />
public object SyncRoot
{
get { return this; }
}
/// <include file='ConfigCollection.xml' path='//Property[@name="ItemIndex"]/docs/*' />
public IConfig this[int index]
{
get { return (IConfig)configList[index]; }
}
/// <include file='ConfigCollection.xml' path='//Property[@name="ItemIndex"]/docs/*' />
object IList.this[int index]
{
get { return configList[index]; }
set { }
}
/// <include file='ConfigCollection.xml' path='//Property[@name="ItemName"]/docs/*' />
public IConfig this[string configName]
{
get
{
IConfig result = null;
foreach (IConfig config in configList)
{
if (config.Name == configName) {
result = config;
break;
}
}
return result;
}
}
/// <include file='ConfigCollection.xml' path='//Property[@name="IsFixedSize"]/docs/*' />
public bool IsFixedSize
{
get { return false; }
}
/// <include file='ConfigCollection.xml' path='//Property[@name="IsReadOnly"]/docs/*' />
public bool IsReadOnly
{
get { return false; }
}
#endregion
#region Public methods
/// <include file='ConfigCollection.xml' path='//Method[@name="Add"]/docs/*' />
public void Add (IConfig config)
{
if (configList.Contains (config)) {
throw new ArgumentException ("IConfig already exists");
}
IConfig existingConfig = this[config.Name];
if (existingConfig != null) {
// Set all new keys
string[] keys = config.GetKeys ();
for (int i = 0; i < keys.Length; i++)
{
existingConfig.Set (keys[i], config.Get (keys[i]));
}
} else {
configList.Add (config);
OnConfigAdded (new ConfigEventArgs (config));
}
}
/// <include file='ConfigCollection.xml' path='//Method[@name="Add"]/docs/*' />
int IList.Add (object config)
{
IConfig newConfig = config as IConfig;
if (newConfig == null) {
throw new Exception ("Must be an IConfig");
} else {
this.Add (newConfig);
return IndexOf (newConfig);
}
}
/// <include file='ConfigCollection.xml' path='//Method[@name="AddName"]/docs/*' />
public IConfig Add (string name)
{
ConfigBase result = null;
if (this[name] == null) {
result = new ConfigBase (name, owner);
configList.Add (result);
OnConfigAdded (new ConfigEventArgs (result));
} else {
//throw new ArgumentException ("An IConfig of that name already exists");
return this[name];
}
return result;
}
/// <include file='ConfigCollection.xml' path='//Method[@name="Remove"]/docs/*' />
public void Remove (IConfig config)
{
configList.Remove (config);
OnConfigRemoved (new ConfigEventArgs (config));
}
/// <include file='ConfigCollection.xml' path='//Method[@name="Remove"]/docs/*' />
public void Remove (object config)
{
configList.Remove (config);
OnConfigRemoved (new ConfigEventArgs ((IConfig)config));
}
/// <include file='ConfigCollection.xml' path='//Method[@name="RemoveAt"]/docs/*' />
public void RemoveAt (int index)
{
IConfig config = (IConfig)configList[index];
configList.RemoveAt (index);
OnConfigRemoved (new ConfigEventArgs (config));
}
/// <include file='ConfigCollection.xml' path='//Method[@name="Clear"]/docs/*' />
public void Clear ()
{
configList.Clear ();
}
/// <include file='ConfigCollection.xml' path='//Method[@name="GetEnumerator"]/docs/*' />
IEnumerator IEnumerable.GetEnumerator()
{
return configList.GetEnumerator ();
}
/// <include file='ConfigCollection.xml' path='//Method[@name="CopyTo"]/docs/*' />
public void CopyTo (Array array, int index)
{
configList.CopyTo (array, index);
}
/// <include file='ConfigCollection.xml' path='//Method[@name="CopyToStrong"]/docs/*' />
public void CopyTo (IConfig[] array, int index)
{
((ICollection)configList).CopyTo (array, index);
}
/// <include file='ConfigCollection.xml' path='//Method[@name="Contains"]/docs/*' />
public bool Contains (object config)
{
return configList.Contains (config);
}
/// <include file='ConfigCollection.xml' path='//Method[@name="IndexOf"]/docs/*' />
public int IndexOf (object config)
{
return configList.IndexOf (config);
}
/// <include file='ConfigCollection.xml' path='//Method[@name="Insert"]/docs/*' />
public void Insert (int index, object config)
{
configList.Insert (index, config);
}
#endregion
#region Public events
/// <include file='ConfigCollection.xml' path='//Event[@name="ConfigAdded"]/docs/*' />
public event ConfigEventHandler ConfigAdded;
/// <include file='ConfigCollection.xml' path='//Event[@name="ConfigRemoved"]/docs/*' />
public event ConfigEventHandler ConfigRemoved;
#endregion
#region Protected methods
/// <include file='ConfigCollection.xml' path='//Method[@name="OnConfigAdded"]/docs/*' />
protected void OnConfigAdded (ConfigEventArgs e)
{
if (ConfigAdded != null) {
ConfigAdded (this, e);
}
}
/// <include file='ConfigCollection.xml' path='//Method[@name="OnConfigRemoved"]/docs/*' />
protected void OnConfigRemoved (ConfigEventArgs e)
{
if (ConfigRemoved != null) {
ConfigRemoved (this, e);
}
}
#endregion
#region Private methods
#endregion
}
}
| |
// 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.
/*============================================================
**
** Class: EqualityComparer<T>
**
===========================================================*/
using System;
using System.Collections;
namespace System.Collections.Generic
{
public abstract class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T>
{
protected EqualityComparer()
{
}
// .NET Native for UWP toolchain overwrites the Default property with optimized
// instantiation-specific implementation. It depends on subtle implementation details of this
// class to do so. Once the packaging infrastructure allows it, the implementation
// of EqualityComparer<T> should be moved to CoreRT repo to avoid the fragile dependency.
// Until that happens, nothing in this class can change.
// TODO: Change the _default field to non-volatile and initialize it via implicit static
// constructor for better performance (https://github.com/dotnet/coreclr/pull/4340).
public static EqualityComparer<T> Default
{
get
{
if (_default == null)
{
object comparer;
// NUTC compiler is able to static evaluate the conditions and only put the necessary branches in finally binary code,
// even casting to EqualityComparer<T> can be removed.
// For example: for Byte, the code generated is
// if (_default == null) _default = new EqualityComparerForByte(); return _default;
// For classes, due to generic sharing, the code generated is:
// if (_default == null) { if (handle == typeof(string).RuntimeTypeHandle) comparer = new EqualityComparerForString(); else comparer = new LastResortEqalityComparer<T>; ...
if (typeof(T) == typeof(SByte))
comparer = new EqualityComparerForSByte();
else if (typeof(T) == typeof(Byte))
comparer = new EqualityComparerForByte();
else if (typeof(T) == typeof(Int16))
comparer = new EqualityComparerForInt16();
else if (typeof(T) == typeof(UInt16))
comparer = new EqualityComparerForUInt16();
else if (typeof(T) == typeof(Int32))
comparer = new EqualityComparerForInt32();
else if (typeof(T) == typeof(UInt32))
comparer = new EqualityComparerForUInt32();
else if (typeof(T) == typeof(Int64))
comparer = new EqualityComparerForInt64();
else if (typeof(T) == typeof(UInt64))
comparer = new EqualityComparerForUInt64();
else if (typeof(T) == typeof(IntPtr))
comparer = new EqualityComparerForIntPtr();
else if (typeof(T) == typeof(UIntPtr))
comparer = new EqualityComparerForUIntPtr();
else if (typeof(T) == typeof(Single))
comparer = new EqualityComparerForSingle();
else if (typeof(T) == typeof(Double))
comparer = new EqualityComparerForDouble();
else if (typeof(T) == typeof(Decimal))
comparer = new EqualityComparerForDecimal();
else if (typeof(T) == typeof(String))
comparer = new EqualityComparerForString();
else
comparer = new LastResortEqualityComparer<T>();
_default = (EqualityComparer<T>)comparer;
}
return _default;
}
}
private static volatile EqualityComparer<T> _default;
public abstract bool Equals(T x, T y);
public abstract int GetHashCode(T obj);
int IEqualityComparer.GetHashCode(object obj)
{
if (obj == null)
return 0;
if (obj is T)
return GetHashCode((T)obj);
throw new ArgumentException(SR.Argument_InvalidArgumentForComparison, nameof(obj));
}
bool IEqualityComparer.Equals(object x, object y)
{
if (x == y)
return true;
if (x == null || y == null)
return false;
if ((x is T) && (y is T))
return Equals((T)x, (T)y);
throw new ArgumentException(SR.Argument_InvalidArgumentForComparison);
}
}
//
// ProjectN compatibility notes:
//
// Unlike the full desktop, we make no attempt to use the IEquatable<T> interface on T. Because we can't generate
// code at runtime, we derive no performance benefit from using the type-specific Equals(). We can't even
// perform the check for IEquatable<> at the time the type-specific constructor is created (due to the removable of Type.IsAssignableFrom).
// We would thus be incurring an interface cast check on each call to Equals() for no performance gain.
//
// This should not cause a compat problem unless some type implements an IEquatable.Equals() that is semantically
// incompatible with Object.Equals(). That goes specifically against the documented guidelines (and would in any case,
// break any hashcode-dependent collection.)
//
internal sealed class LastResortEqualityComparer<T> : EqualityComparer<T>
{
public LastResortEqualityComparer()
{
}
public sealed override bool Equals(T x, T y)
{
if (x == null)
return y == null;
if (y == null)
return false;
return x.Equals(y);
}
public sealed override int GetHashCode(T obj)
{
if (obj == null)
return 0;
return obj.GetHashCode();
}
}
internal sealed class EqualityComparerForSByte : EqualityComparer<SByte>
{
public override bool Equals(SByte x, SByte y)
{
return x == y;
}
public override int GetHashCode(SByte x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForByte : EqualityComparer<Byte>
{
public override bool Equals(Byte x, Byte y)
{
return x == y;
}
public override int GetHashCode(Byte x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForInt16 : EqualityComparer<Int16>
{
public override bool Equals(Int16 x, Int16 y)
{
return x == y;
}
public override int GetHashCode(Int16 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForUInt16 : EqualityComparer<UInt16>
{
public override bool Equals(UInt16 x, UInt16 y)
{
return x == y;
}
public override int GetHashCode(UInt16 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForInt32 : EqualityComparer<Int32>
{
public override bool Equals(Int32 x, Int32 y)
{
return x == y;
}
public override int GetHashCode(Int32 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForUInt32 : EqualityComparer<UInt32>
{
public override bool Equals(UInt32 x, UInt32 y)
{
return x == y;
}
public override int GetHashCode(UInt32 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForInt64 : EqualityComparer<Int64>
{
public override bool Equals(Int64 x, Int64 y)
{
return x == y;
}
public override int GetHashCode(Int64 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForUInt64 : EqualityComparer<UInt64>
{
public override bool Equals(UInt64 x, UInt64 y)
{
return x == y;
}
public override int GetHashCode(UInt64 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForIntPtr : EqualityComparer<IntPtr>
{
public override bool Equals(IntPtr x, IntPtr y)
{
return x == y;
}
public override int GetHashCode(IntPtr x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForUIntPtr : EqualityComparer<UIntPtr>
{
public override bool Equals(UIntPtr x, UIntPtr y)
{
return x == y;
}
public override int GetHashCode(UIntPtr x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForSingle : EqualityComparer<Single>
{
public override bool Equals(Single x, Single y)
{
// == has the wrong semantic for NaN for Single
return x.Equals(y);
}
public override int GetHashCode(Single x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForDouble : EqualityComparer<Double>
{
public override bool Equals(Double x, Double y)
{
// == has the wrong semantic for NaN for Double
return x.Equals(y);
}
public override int GetHashCode(Double x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForDecimal : EqualityComparer<Decimal>
{
public override bool Equals(Decimal x, Decimal y)
{
return x == y;
}
public override int GetHashCode(Decimal x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForString : EqualityComparer<String>
{
public override bool Equals(String x, String y)
{
return x == y;
}
public override int GetHashCode(String x)
{
if (x == null)
return 0;
return x.GetHashCode();
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Core.TimerJobs.Samples.NoThreadingJob
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*=============================================================================
**
**
**
** Purpose: This enumeration represents characters returned from a keyboard.
** The list is derived from a list of Windows virtual key codes,
** and is very similar to the Windows Forms Keys class.
**
**
=============================================================================*/
namespace System {
[Serializable]
public enum ConsoleKey
{
Backspace = 0x8,
Tab = 0x9,
// 0xA, // Reserved
// 0xB, // Reserved
Clear = 0xC,
Enter = 0xD,
// 0E-0F, // Undefined
// SHIFT = 0x10,
// CONTROL = 0x11,
// Alt = 0x12,
Pause = 0x13,
// CAPSLOCK = 0x14,
// Kana = 0x15, // Ime Mode
// Hangul = 0x15, // Ime Mode
// 0x16, // Undefined
// Junja = 0x17, // Ime Mode
// Final = 0x18, // Ime Mode
// Hanja = 0x19, // Ime Mode
// Kanji = 0x19, // Ime Mode
// 0x1A, // Undefined
Escape = 0x1B,
// Convert = 0x1C, // Ime Mode
// NonConvert = 0x1D, // Ime Mode
// Accept = 0x1E, // Ime Mode
// ModeChange = 0x1F, // Ime Mode
Spacebar = 0x20,
PageUp = 0x21,
PageDown = 0x22,
End = 0x23,
Home = 0x24,
LeftArrow = 0x25,
UpArrow = 0x26,
RightArrow = 0x27,
DownArrow = 0x28,
Select = 0x29,
Print = 0x2A,
Execute = 0x2B,
PrintScreen = 0x2C,
Insert = 0x2D,
Delete = 0x2E,
Help = 0x2F,
D0 = 0x30, // 0 through 9
D1 = 0x31,
D2 = 0x32,
D3 = 0x33,
D4 = 0x34,
D5 = 0x35,
D6 = 0x36,
D7 = 0x37,
D8 = 0x38,
D9 = 0x39,
// 3A-40 , // Undefined
A = 0x41,
B = 0x42,
C = 0x43,
D = 0x44,
E = 0x45,
F = 0x46,
G = 0x47,
H = 0x48,
I = 0x49,
J = 0x4A,
K = 0x4B,
L = 0x4C,
M = 0x4D,
N = 0x4E,
O = 0x4F,
P = 0x50,
Q = 0x51,
R = 0x52,
S = 0x53,
T = 0x54,
U = 0x55,
V = 0x56,
W = 0x57,
X = 0x58,
Y = 0x59,
Z = 0x5A,
LeftWindows = 0x5B, // Microsoft Natural keyboard
RightWindows = 0x5C, // Microsoft Natural keyboard
Applications = 0x5D, // Microsoft Natural keyboard
// 5E , // Reserved
Sleep = 0x5F, // Computer Sleep Key
NumPad0 = 0x60,
NumPad1 = 0x61,
NumPad2 = 0x62,
NumPad3 = 0x63,
NumPad4 = 0x64,
NumPad5 = 0x65,
NumPad6 = 0x66,
NumPad7 = 0x67,
NumPad8 = 0x68,
NumPad9 = 0x69,
Multiply = 0x6A,
Add = 0x6B,
Separator = 0x6C,
Subtract = 0x6D,
Decimal = 0x6E,
Divide = 0x6F,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
F13 = 0x7C,
F14 = 0x7D,
F15 = 0x7E,
F16 = 0x7F,
F17 = 0x80,
F18 = 0x81,
F19 = 0x82,
F20 = 0x83,
F21 = 0x84,
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
// 88-8F, // Undefined
// NumberLock = 0x90,
// ScrollLock = 0x91,
// 0x92, // OEM Specific
// 97-9F , // Undefined
// LeftShift = 0xA0,
// RightShift = 0xA1,
// LeftControl = 0xA2,
// RightControl = 0xA3,
// LeftAlt = 0xA4,
// RightAlt = 0xA5,
BrowserBack = 0xA6, // Windows 2000/XP
BrowserForward = 0xA7, // Windows 2000/XP
BrowserRefresh = 0xA8, // Windows 2000/XP
BrowserStop = 0xA9, // Windows 2000/XP
BrowserSearch = 0xAA, // Windows 2000/XP
BrowserFavorites = 0xAB, // Windows 2000/XP
BrowserHome = 0xAC, // Windows 2000/XP
VolumeMute = 0xAD, // Windows 2000/XP
VolumeDown = 0xAE, // Windows 2000/XP
VolumeUp = 0xAF, // Windows 2000/XP
MediaNext = 0xB0, // Windows 2000/XP
MediaPrevious = 0xB1, // Windows 2000/XP
MediaStop = 0xB2, // Windows 2000/XP
MediaPlay = 0xB3, // Windows 2000/XP
LaunchMail = 0xB4, // Windows 2000/XP
LaunchMediaSelect = 0xB5, // Windows 2000/XP
LaunchApp1 = 0xB6, // Windows 2000/XP
LaunchApp2 = 0xB7, // Windows 2000/XP
// B8-B9, // Reserved
Oem1 = 0xBA, // Misc characters, varies by keyboard. For US standard, ;:
OemPlus = 0xBB, // Misc characters, varies by keyboard. For US standard, +
OemComma = 0xBC, // Misc characters, varies by keyboard. For US standard, ,
OemMinus = 0xBD, // Misc characters, varies by keyboard. For US standard, -
OemPeriod = 0xBE, // Misc characters, varies by keyboard. For US standard, .
Oem2 = 0xBF, // Misc characters, varies by keyboard. For US standard, /?
Oem3 = 0xC0, // Misc characters, varies by keyboard. For US standard, `~
// 0xC1, // Reserved
// D8-DA, // Unassigned
Oem4 = 0xDB, // Misc characters, varies by keyboard. For US standard, [{
Oem5 = 0xDC, // Misc characters, varies by keyboard. For US standard, \|
Oem6 = 0xDD, // Misc characters, varies by keyboard. For US standard, ]}
Oem7 = 0xDE, // Misc characters, varies by keyboard. For US standard,
Oem8 = 0xDF, // Used for miscellaneous characters; it can vary by keyboard
// 0xE0, // Reserved
// 0xE1, // OEM specific
Oem102 = 0xE2, // Win2K/XP: Either angle or backslash on RT 102-key keyboard
// 0xE3, // OEM specific
Process = 0xE5, // Windows: IME Process Key
// 0xE6, // OEM specific
Packet = 0xE7, // Win2K/XP: Used to pass Unicode chars as if keystrokes
// 0xE8, // Unassigned
// 0xE9, // OEM specific
Attention = 0xF6,
CrSel = 0xF7,
ExSel = 0xF8,
EraseEndOfFile = 0xF9,
Play = 0xFA,
Zoom = 0xFB,
NoName = 0xFC, // Reserved
Pa1 = 0xFD,
OemClear = 0xFE,
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Performance;
using osu.Framework.Graphics.Shaders;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Visualisation;
using osu.Framework.Graphics.Visualisation.Audio;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.IO.Stores;
using osu.Framework.Localisation;
using osu.Framework.Platform;
using osuTK;
namespace osu.Framework
{
public abstract class Game : Container, IKeyBindingHandler<FrameworkAction>, IKeyBindingHandler<PlatformAction>, IHandleGlobalKeyboardInput
{
public IWindow Window => Host?.Window;
public ResourceStore<byte[]> Resources { get; private set; }
public TextureStore Textures { get; private set; }
protected GameHost Host { get; private set; }
private readonly Bindable<bool> isActive = new Bindable<bool>(true);
/// <summary>
/// Whether the game is active (in the foreground).
/// </summary>
public IBindable<bool> IsActive => isActive;
public AudioManager Audio { get; private set; }
public ShaderManager Shaders { get; private set; }
/// <summary>
/// A store containing fonts accessible game-wide.
/// </summary>
/// <remarks>
/// It is recommended to use <see cref="AddFont"/> when adding new fonts.
/// </remarks>
public FontStore Fonts { get; private set; }
private FontStore localFonts;
protected LocalisationManager Localisation { get; private set; }
private readonly Container content;
private DrawVisualiser drawVisualiser;
private TextureVisualiser textureVisualiser;
private LogOverlay logOverlay;
private AudioMixerVisualiser audioMixerVisualiser;
protected override Container<Drawable> Content => content;
protected internal virtual UserInputManager CreateUserInputManager() => new UserInputManager();
/// <summary>
/// Provide <see cref="FrameworkSetting"/> defaults which should override those provided by osu-framework.
/// <remarks>
/// Please check https://github.com/ppy/osu-framework/blob/master/osu.Framework/Configuration/FrameworkConfigManager.cs for expected types.
/// </remarks>
/// </summary>
protected internal virtual IDictionary<FrameworkSetting, object> GetFrameworkConfigDefaults() => null;
/// <summary>
/// Creates the <see cref="Storage"/> where this <see cref="Game"/> will reside.
/// </summary>
/// <param name="host">The <see cref="GameHost"/>.</param>
/// <param name="defaultStorage">The default <see cref="Storage"/> to be used if a custom <see cref="Storage"/> isn't desired.</param>
/// <returns>The <see cref="Storage"/>.</returns>
protected internal virtual Storage CreateStorage(GameHost host, Storage defaultStorage) => defaultStorage;
protected Game()
{
RelativeSizeAxes = Axes.Both;
AddRangeInternal(new Drawable[]
{
content = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
},
});
}
/// <summary>
/// As Load is run post host creation, you can override this method to alter properties of the host before it makes itself visible to the user.
/// </summary>
/// <param name="host"></param>
public virtual void SetHost(GameHost host)
{
Host = host;
host.Exiting += OnExiting;
host.Activated += () => isActive.Value = true;
host.Deactivated += () => isActive.Value = false;
}
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) =>
dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
[BackgroundDependencyLoader]
private void load(FrameworkConfigManager config)
{
Resources = new ResourceStore<byte[]>();
Resources.AddStore(new NamespacedResourceStore<byte[]>(new DllResourceStore(typeof(Game).Assembly), @"Resources"));
Textures = new TextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore<byte[]>(Resources, @"Textures")));
Textures.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
dependencies.Cache(Textures);
var tracks = new ResourceStore<byte[]>();
tracks.AddStore(new NamespacedResourceStore<byte[]>(Resources, @"Tracks"));
tracks.AddStore(new OnlineStore());
var samples = new ResourceStore<byte[]>();
samples.AddStore(new NamespacedResourceStore<byte[]>(Resources, @"Samples"));
samples.AddStore(new OnlineStore());
Audio = new AudioManager(Host.AudioThread, tracks, samples) { EventScheduler = Scheduler };
dependencies.Cache(Audio);
dependencies.CacheAs(Audio.Tracks);
dependencies.CacheAs(Audio.Samples);
// attach our bindables to the audio subsystem.
config.BindWith(FrameworkSetting.AudioDevice, Audio.AudioDevice);
config.BindWith(FrameworkSetting.VolumeUniversal, Audio.Volume);
config.BindWith(FrameworkSetting.VolumeEffect, Audio.VolumeSample);
config.BindWith(FrameworkSetting.VolumeMusic, Audio.VolumeTrack);
Shaders = new ShaderManager(new NamespacedResourceStore<byte[]>(Resources, @"Shaders"));
dependencies.Cache(Shaders);
var cacheStorage = Host.CacheStorage.GetStorageForDirectory("fonts");
// base store is for user fonts
Fonts = new FontStore(useAtlas: true, cacheStorage: cacheStorage);
// nested store for framework provided fonts.
// note that currently this means there could be two async font load operations.
Fonts.AddStore(localFonts = new FontStore(useAtlas: false));
// Roboto (FrameworkFont.Regular)
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-Regular");
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-RegularItalic");
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-Bold");
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-BoldItalic");
// RobotoCondensed (FrameworkFont.Condensed)
addFont(localFonts, Resources, @"Fonts/RobotoCondensed/RobotoCondensed-Regular");
addFont(localFonts, Resources, @"Fonts/RobotoCondensed/RobotoCondensed-Bold");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Solid");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Regular");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Brands");
dependencies.Cache(Fonts);
Localisation = new LocalisationManager(config);
dependencies.Cache(Localisation);
frameSyncMode = config.GetBindable<FrameSync>(FrameworkSetting.FrameSync);
executionMode = config.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
logOverlayVisibility = config.GetBindable<bool>(FrameworkSetting.ShowLogOverlay);
logOverlayVisibility.BindValueChanged(visibility =>
{
if (visibility.NewValue)
{
if (logOverlay == null)
{
LoadComponentAsync(logOverlay = new LogOverlay
{
Depth = float.MinValue / 2,
}, AddInternal);
}
logOverlay.Show();
}
else
{
logOverlay?.Hide();
}
}, true);
}
/// <summary>
/// Add a font to be globally accessible to the game.
/// </summary>
/// <param name="store">The backing store with font resources.</param>
/// <param name="assetName">The base name of the font.</param>
/// <param name="target">An optional target store to add the font to. If not specified, <see cref="Fonts"/> is used.</param>
public void AddFont(ResourceStore<byte[]> store, string assetName = null, FontStore target = null)
=> addFont(target ?? Fonts, store, assetName);
private void addFont(FontStore target, ResourceStore<byte[]> store, string assetName = null)
=> target.AddStore(new RawCachingGlyphStore(store, assetName, Host.CreateTextureLoaderStore(store)));
protected override void LoadComplete()
{
base.LoadComplete();
PerformanceOverlay performanceOverlay;
LoadComponentAsync(performanceOverlay = new PerformanceOverlay(Host.Threads)
{
Margin = new MarginPadding(5),
Direction = FillDirection.Vertical,
Spacing = new Vector2(10, 10),
AutoSizeAxes = Axes.Both,
Alpha = 0,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
Depth = float.MinValue
}, AddInternal);
FrameStatistics.BindValueChanged(e => performanceOverlay.State = e.NewValue, true);
}
protected readonly Bindable<FrameStatisticsMode> FrameStatistics = new Bindable<FrameStatisticsMode>();
private GlobalStatisticsDisplay globalStatistics;
private Bindable<bool> logOverlayVisibility;
private Bindable<FrameSync> frameSyncMode;
private Bindable<ExecutionMode> executionMode;
public bool OnPressed(KeyBindingPressEvent<FrameworkAction> e)
{
if (e.Repeat)
return false;
switch (e.Action)
{
case FrameworkAction.CycleFrameStatistics:
switch (FrameStatistics.Value)
{
case FrameStatisticsMode.None:
FrameStatistics.Value = FrameStatisticsMode.Minimal;
break;
case FrameStatisticsMode.Minimal:
FrameStatistics.Value = FrameStatisticsMode.Full;
break;
case FrameStatisticsMode.Full:
FrameStatistics.Value = FrameStatisticsMode.None;
break;
}
return true;
case FrameworkAction.ToggleDrawVisualiser:
if (drawVisualiser == null)
{
LoadComponentAsync(drawVisualiser = new DrawVisualiser
{
ToolPosition = getCascadeLocation(0),
Depth = float.MinValue / 2,
}, AddInternal);
}
drawVisualiser.ToggleVisibility();
return true;
case FrameworkAction.ToggleGlobalStatistics:
if (globalStatistics == null)
{
LoadComponentAsync(globalStatistics = new GlobalStatisticsDisplay
{
Depth = float.MinValue / 2,
Position = getCascadeLocation(1),
}, AddInternal);
}
globalStatistics.ToggleVisibility();
return true;
case FrameworkAction.ToggleAtlasVisualiser:
if (textureVisualiser == null)
{
LoadComponentAsync(textureVisualiser = new TextureVisualiser
{
Position = getCascadeLocation(2),
Depth = float.MinValue / 2,
}, AddInternal);
}
textureVisualiser.ToggleVisibility();
return true;
case FrameworkAction.ToggleAudioMixerVisualiser:
if (audioMixerVisualiser == null)
{
LoadComponentAsync(audioMixerVisualiser = new AudioMixerVisualiser
{
Position = getCascadeLocation(3),
Depth = float.MinValue / 2,
}, AddInternal);
}
audioMixerVisualiser.ToggleVisibility();
return true;
case FrameworkAction.ToggleLogOverlay:
logOverlayVisibility.Value = !logOverlayVisibility.Value;
return true;
case FrameworkAction.ToggleFullscreen:
Window?.CycleMode();
return true;
case FrameworkAction.CycleFrameSync:
var nextFrameSync = frameSyncMode.Value + 1;
if (nextFrameSync > FrameSync.Unlimited)
nextFrameSync = FrameSync.VSync;
frameSyncMode.Value = nextFrameSync;
break;
case FrameworkAction.CycleExecutionMode:
var nextExecutionMode = executionMode.Value + 1;
if (nextExecutionMode > ExecutionMode.MultiThreaded)
nextExecutionMode = ExecutionMode.SingleThread;
executionMode.Value = nextExecutionMode;
break;
}
return false;
Vector2 getCascadeLocation(int index)
=> new Vector2(100 + index * (TitleBar.HEIGHT + 10));
}
public void OnReleased(KeyBindingReleaseEvent<FrameworkAction> e)
{
}
public virtual bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
{
if (e.Repeat)
return false;
switch (e.Action)
{
case PlatformAction.Exit:
Host.Window?.Close();
return true;
}
return false;
}
public virtual void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
{
}
public void Exit()
{
if (Host == null)
throw new InvalidOperationException("Attempted to exit a game which has not yet been run");
Host.Exit();
}
protected virtual bool OnExiting() => false;
protected override void Dispose(bool isDisposing)
{
// ensure any async disposals are completed before we begin to rip components out.
// if we were to not wait, async disposals may throw unexpected exceptions.
AsyncDisposalQueue.WaitForEmpty();
base.Dispose(isDisposing);
// call a second time to protect against anything being potentially async disposed in the base.Dispose call.
AsyncDisposalQueue.WaitForEmpty();
Audio?.Dispose();
Audio = null;
Fonts?.Dispose();
Fonts = null;
localFonts?.Dispose();
localFonts = null;
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace Dynastream.Fit
{
/// <summary>
/// Implements the Totals profile message.
/// </summary>
public class TotalsMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public TotalsMesg() : base(Profile.mesgs[Profile.TotalsIndex])
{
}
public TotalsMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the MessageIndex field</summary>
/// <returns>Returns nullable ushort representing the MessageIndex field</returns>
public ushort? GetMessageIndex()
{
return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set MessageIndex field</summary>
/// <param name="messageIndex_">Nullable field value to be set</param>
public void SetMessageIndex(ushort? messageIndex_)
{
SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Timestamp field
/// Units: s</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public DateTime GetTimestamp()
{
return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set Timestamp field
/// Units: s</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(DateTime timestamp_)
{
SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TimerTime field
/// Units: s
/// Comment: Excludes pauses</summary>
/// <returns>Returns nullable uint representing the TimerTime field</returns>
public uint? GetTimerTime()
{
return (uint?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TimerTime field
/// Units: s
/// Comment: Excludes pauses</summary>
/// <param name="timerTime_">Nullable field value to be set</param>
public void SetTimerTime(uint? timerTime_)
{
SetFieldValue(0, 0, timerTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Distance field
/// Units: m</summary>
/// <returns>Returns nullable uint representing the Distance field</returns>
public uint? GetDistance()
{
return (uint?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Distance field
/// Units: m</summary>
/// <param name="distance_">Nullable field value to be set</param>
public void SetDistance(uint? distance_)
{
SetFieldValue(1, 0, distance_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Calories field
/// Units: kcal</summary>
/// <returns>Returns nullable uint representing the Calories field</returns>
public uint? GetCalories()
{
return (uint?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Calories field
/// Units: kcal</summary>
/// <param name="calories_">Nullable field value to be set</param>
public void SetCalories(uint? calories_)
{
SetFieldValue(2, 0, calories_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Sport field</summary>
/// <returns>Returns nullable Sport enum representing the Sport field</returns>
public Sport? GetSport()
{
object obj = GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
Sport? value = obj == null ? (Sport?)null : (Sport)obj;
return value;
}
/// <summary>
/// Set Sport field</summary>
/// <param name="sport_">Nullable field value to be set</param>
public void SetSport(Sport? sport_)
{
SetFieldValue(3, 0, sport_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ElapsedTime field
/// Units: s
/// Comment: Includes pauses</summary>
/// <returns>Returns nullable uint representing the ElapsedTime field</returns>
public uint? GetElapsedTime()
{
return (uint?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ElapsedTime field
/// Units: s
/// Comment: Includes pauses</summary>
/// <param name="elapsedTime_">Nullable field value to be set</param>
public void SetElapsedTime(uint? elapsedTime_)
{
SetFieldValue(4, 0, elapsedTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Sessions field</summary>
/// <returns>Returns nullable ushort representing the Sessions field</returns>
public ushort? GetSessions()
{
return (ushort?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Sessions field</summary>
/// <param name="sessions_">Nullable field value to be set</param>
public void SetSessions(ushort? sessions_)
{
SetFieldValue(5, 0, sessions_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActiveTime field
/// Units: s</summary>
/// <returns>Returns nullable uint representing the ActiveTime field</returns>
public uint? GetActiveTime()
{
return (uint?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ActiveTime field
/// Units: s</summary>
/// <param name="activeTime_">Nullable field value to be set</param>
public void SetActiveTime(uint? activeTime_)
{
SetFieldValue(6, 0, activeTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SportIndex field</summary>
/// <returns>Returns nullable byte representing the SportIndex field</returns>
public byte? GetSportIndex()
{
return (byte?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set SportIndex field</summary>
/// <param name="sportIndex_">Nullable field value to be set</param>
public void SetSportIndex(byte? sportIndex_)
{
SetFieldValue(9, 0, sportIndex_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
using System;
using System.IO;
using System.Text;
using System.CodeDom;
using System.Security;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.CodeDom.Compiler;
using System.Security.Permissions;
using System.Runtime.InteropServices;
[assembly:ComVisible(false)]
[assembly:CLSCompliantAttribute (true)]
namespace Microsoft.Samples.CodeDomTestSuite {
/// <summary>
/// Base class for all CodeDom test cases. You must inherit from this class
/// if you are writing a test case for the CodeDom test suite.
/// </summary>
public abstract class CodeDomTest {
/// <summary>
/// Any additional comment needed...
/// </summary>
public virtual string Comment {
get { return ""; }
}
/// <summary>
/// The classification of this test. This will determine which
/// bucket of test cases this test case falls into.
/// </summary>
/// <value>The classification of this test case.</value>
public abstract TestTypes TestType {
get;
}
/// <summary>
/// The name of the test case. This will be displayed to the user.
/// The user will also use this name to identify this test case.
/// </summary>
/// <value>The name of this test case.</value>
public abstract string Name {
get;
}
/// <summary>
/// This will be shown along with the test case name in the list
/// of test cases.
/// </summary>
/// <value>Short description of the test case.</value>
public abstract string Description {
get;
}
/// <summary>
/// Overriden to provide test functionality for the given
/// provider. Return true to signal a test pass, false for
/// test failure. Use LogMessage to output test status
/// along the way.
/// </summary>
/// <param name="provider">Provider to test.</param>
/// <returns>True if the test passed. False otherwise.</returns>
public abstract bool Run (CodeDomProvider provider);
protected bool Supports (CodeDomProvider provider, GeneratorSupport support) {
#if WHIDBEY
return provider.Supports (support);
#else
return (provider.CreateGenerator ()).Supports (support);
#endif
}
/// <summary>
/// Used to drop the given string to the given filename. All IO
/// and security exceptions are caught and displayed using LogMessage.
/// </summary>
protected void DumpStringToFile (string dumpText, string fileName) {
try {
using (StreamWriter srcWriter = new StreamWriter (
new FileStream (fileName, FileMode.Create),
Encoding.UTF8)) {
srcWriter.Write (dumpText);
}
} catch (IOException e) {
// catch exceptions here because we want to continue testing if possible
LogMessage ("Problem writing to '{0}'.", fileName);
LogMessage ("Exception stack:");
LogMessage (e.ToString ());
} catch (SecurityException e) {
// catch exceptions here because we want to continue testing if possible
LogMessage ("Problem writing to '{0}'.", fileName);
LogMessage ("Exception stack:");
LogMessage (e.ToString ());
}
}
#region Message logging
string indentString = String.Empty;
readonly string indentIncrement = " ";
TextWriter log = null;
bool echoToConsole = false;
/// <summary>
/// Gets/sets the TextWriter stream that log messages should
/// be written to.
/// </summary>
/// <value>The TextWriter to write messages to.</value>
public TextWriter LogStream {
get { return log; }
set { log = value; }
}
/// <summary>
/// In addition to writing to the TextWriter specified by the
/// LogStream property, a true EchoToConsole property will also
/// echo any output to the console.
/// </summary>
/// <value>Whether to echo to the console or not.</value>
public bool EchoToConsole {
get { return echoToConsole; }
set { echoToConsole = value; }
}
/// <summary>
/// Unindents the current indent string. Used in combination
/// with LogMessageIndent to make output follow a somewhat
/// heirachial format.
/// </summary>
public void LogMessageUnindent () {
if (indentString.Length >= 1)
indentString = indentString.Substring (indentIncrement.Length);
}
/// <summary>
/// Indents the current indent string. Used in combination
/// with LogMessageIndent to make output follow a somewhat
/// heirachial format.
/// </summary>
public void LogMessageIndent () {
indentString += indentIncrement;
}
/// <summary>
/// Provides communication with the test suite. Use this to log
/// any arbitrary message during any part of your test.
/// </summary>
/// <param name="txt">The message to log.</param>
public void LogMessage (string txt) {
// always echo to console if the log stream is null
if (log == null || echoToConsole) {
Console.Write (indentString);
Console.WriteLine (txt);
}
if (log != null) {
log.Write (indentString);
log.WriteLine (txt);
}
}
/// <summary>
/// Provides communication with the test suite. Use this to log
/// any arbitrary message during any part of your test. This overload
/// allows formatting.
/// </summary>
/// <param name="text">Message to log. You may use formats as in String.Format.</param>
/// <param name="p">Parameters to your message.</param>
public void LogMessage (string message, params object[] p) {
LogMessage (String.Format (CultureInfo.InvariantCulture, message, p));
}
#endregion
#region Common verification routines
/// <summary>
/// This method finds the given methodName in the type and object
/// and invokes it with the given parameters. If the return value of
/// this call matches the given expected return value, VerifyMethod()
/// returns true. False otherwise. It makes liberal use of LogMessage().
/// </summary>
/// <param name="container">Type of the given instance.</param>
/// <param name="instance">An instantiated object of the given type.</param>
/// <param name="methodName">The method to find and invoke.</param>
/// <param name="parameters">The parameters to pass to the method.</param>
/// <param name="expectedReturn">The expected return value of the method.</param>
/// <returns>True if verification succeeded. False otherwise.</returns>
protected bool VerifyMethod (Type container, object instance, string methodName, object[] parameters, object expectedReturn) {
if (container == null)
throw new ArgumentNullException ("container");
if (instance == null)
throw new ArgumentNullException ("instance");
if (methodName == null)
throw new ArgumentNullException ("methodName");
LogMessage ("Calling {0}, expecting '{1}' for a return value.", methodName, expectedReturn);
// output parameters
if (parameters != null) {
LogMessage ("with parameters");
int i = 0;
LogMessageIndent ();
foreach (object parameter in parameters) {
LogMessage ("{0}: type={1}, value='{2}'", i++, parameter.GetType (), parameter);
}
LogMessageUnindent ();
}
Type [] typeArray = parameters == null ? new Type[0] :
System.Type.GetTypeArray (parameters);
MethodInfo methodInfo = container.GetMethod (methodName, typeArray);
if (methodInfo == null) {
LogMessage ("Unable to get " + methodName);
return false;
}
object returnValue = methodInfo.Invoke (instance, parameters == null ?
new Object [0] : parameters);
if (expectedReturn == null && returnValue == null) {
LogMessage ("Return value was '{0}'", returnValue);
LogMessage ("");
return true;
}
if (returnValue == null) {
LogMessage ("Unable to get return value.");
return false;
}
if (returnValue.GetType () != expectedReturn.GetType ()) {
LogMessage ("Return value is wrong type. Returned type=" +
returnValue.GetType ().ToString () + ", expected " +
expectedReturn.GetType ().ToString () + ".");
return false;
}
if (!returnValue.Equals (expectedReturn)) {
LogMessage ("Return value is incorrect. Returned '" +
returnValue.ToString () + "', expected '" + expectedReturn.ToString () + "'.");
return false;
}
LogMessage ("Return value was '{0}'", returnValue);
LogMessage ("");
return true;
}
/// <summary>
/// This method finds the given propName in the type and object
/// and sets its value with the given object (setVal). If the set
/// succeeds, VerifyPropertySet() returns true. It makes liberal
/// use of LogMessage().
/// </summary>
/// <param name="container">Type of the given instance.</param>
/// <param name="instance">An instantiated object of the given type.</param>
/// <param name="propName">Property name to set.</param>
/// <param name="setVal">Value to set the property to.</param>
/// <returns>True if the operation succeeded. False otherwise.</returns>
protected bool VerifyPropertySet (Type container, object instance, string propName, object setVal) {
if (container == null)
throw new ArgumentNullException ("container");
if (instance == null)
throw new ArgumentNullException ("instance");
if (propName == null)
throw new ArgumentNullException ("propName");
PropertyInfo propInfo;
LogMessage ("Setting property '{0}' to '{1}'.", propName, setVal);
if (setVal != null && setVal.GetType () != null) {
propInfo = container.GetProperty(propName, setVal.GetType());
} else {
propInfo = container.GetProperty(propName);
}
if (propInfo == null) {
LogMessage ("Unable to get property '{0}' from the assembly.", propName);
return false;
}
propInfo.SetValue(instance, setVal, null);
LogMessage ("Set.");
LogMessage ("");
return true;
}
/// <summary>
/// This method finds the given propName in the type and object
/// and gets its value in order to compare it with the given object
/// (expectedReturn). If they match, VerifyPropertyGet() returns true.
/// It makes liberal use of LogMessage().
/// </summary>
/// <param name="testType">Type of the given instance.</param>
/// <param name="instance">An instantiated object of the given type.</param>
/// <param name="propName">Property name to get.</param>
/// <param name="setVal">Value you expect the property to return.</param>
/// <returns>True if the operation succeeded. False otherwise.</returns>
protected bool VerifyPropertyGet (Type container, object instance, string propName, object expectedReturn) {
if (container == null)
throw new ArgumentNullException ("container");
if (instance == null)
throw new ArgumentNullException ("instance");
if (propName == null)
throw new ArgumentNullException ("propName");
PropertyInfo propInfo = null;
LogMessage ("Getting property '{0}' expecting '{1}'.", propName, expectedReturn);
if (expectedReturn != null && expectedReturn.GetType () != null) {
propInfo = container.GetProperty (propName, expectedReturn.GetType ());
} else {
propInfo = container.GetProperty (propName);
}
if (propInfo == null) {
LogMessage ("Unable to get property '{0}'.", propName);
return false;
}
object retVal = propInfo.GetValue (instance, new object [0]);
if (retVal == null) {
LogMessage ("Return value is null.");
return false;
}
if (retVal.GetType () != expectedReturn.GetType ()) {
LogMessage ("Return value is wrong type. Returned type=" +
retVal.GetType ().ToString () + ", expected " + expectedReturn.GetType ().ToString () + ".");
return false;
}
if (!retVal.Equals (expectedReturn)) {
LogMessage ("Return value is incorrect. Returned '" + retVal.ToString () + "', expected '" + expectedReturn.ToString () + "'.");
return false;
}
LogMessage ("Return value was '{0}'.", retVal);
LogMessage ("");
return true;
}
/// <summary>
/// Verifies that the given exception (expectedException) is thrown
/// when the given methodName is called on the instance which is
/// of type container with the parameters. True is returned if this
/// is the case. False otherwise.
/// </summary>
/// <param name="container">The type in which to find the method.</param>
/// <param name="instance">An instantiated object of the given type.</param>
/// <param name="methodName">The name of the method to find.</param>
/// <param name="parameters">The parameters to pass to the method.</param>
/// <param name="expectedException">The expected exception to be thrown.</param>
/// <returns>True if the exception was thrown. False otherwise.</returns>
protected bool VerifyException (Type container, object instance, string methodName, object[] parameters, object expectedException) {
if (container == null)
throw new ArgumentNullException ("container");
if (instance == null)
throw new ArgumentNullException ("instance");
if (methodName == null)
throw new ArgumentNullException ("methodName");
LogMessage ("Calling {0} and expecting {1} to be thrown.", methodName, expectedException.GetType ());
MethodInfo methodInfo = container.GetMethod (methodName);
if (methodInfo == null) {
LogMessage ("Unable to get " + methodName);
return false;
}
try {
object returnValue = methodInfo.Invoke (instance, parameters);
}
catch (Exception e) {
if (e.GetType () != expectedException.GetType ()) {
LogMessage ("Return value type is incorrect. Returned " + e.GetType ().ToString ());
return false;
}
}
LogMessage ("Exception was thrown as expected.");
LogMessage ("");
return true;
}
/// <summary>
/// Used for attribute verification. This method finds the given type
/// and attempts to retrieve the value of the property specified in
/// propertyName. It compares this value with the given propertyValue
/// and returns true if they match. False is otherwise returned. The
/// type is searched for in the given attributes array.
/// </summary>
/// <param name="attributes">Array of objects in which to find the type.</param>
/// <param name="type">The type to find.</param>
/// <param name="propertyName">The property to validate against.</param>
/// <param name="propertyValue">The expected value of this property.</param>
/// <returns></returns>
protected bool VerifyAttribute (object[] attributes, Type type, string propertyName, object propertyValue) {
if (attributes == null)
throw new ArgumentNullException ("attributes");
if (type == null)
throw new ArgumentNullException ("type");
if (propertyName == null)
throw new ArgumentNullException ("propertyName");
LogMessage ("Attempting to find attribute " + type.Name);
foreach (object attr in attributes) {
if (attr.GetType () == type) {
object retVal = type.InvokeMember (propertyName, BindingFlags.GetProperty, null, attr, null, CultureInfo.InvariantCulture);
if (retVal == null) {
LogMessage ("Unable to get return value.");
return false;
}
if (retVal.GetType () != propertyValue.GetType ()) {
LogMessage ("Return value is wrong type. Returned type=" +
retVal.GetType ().ToString () + ", expected " + propertyValue.GetType ().ToString () + ".");
return false;
}
if (!retVal.Equals (propertyValue)) {
LogMessage ("Return value is incorrect. Returned '" +
retVal.ToString () + "', expected '" + propertyValue.ToString () + "'.");
return false;
}
LogMessage ("Found attribute: " + type.Name);
LogMessage ("");
return true;
}
}
LogMessage ("Unable to find attribute: " + type.Name);
LogMessage ("");
return false;
}
/// <summary>
/// Finds and instantiates the given type name in the assembly. Both the
/// type and instantiated object are out parameters. If the type can't be
/// found or instantiated, false is returned.
/// </summary>
/// <param name="typeName">Type to find in the given assembly.</param>
/// <param name="typeAssembly">Assembly to search through for the given type name.</param>
/// <param name="obj">Instantiated object of the given type.</param>
/// <param name="genType">The type that was found in the assembly.</param>
/// <returns>True if the type was found and instantiated, false otherwise.</returns>
protected bool FindAndInstantiate (string typeName, Assembly typeAssembly, out object obj, out Type genType) {
if (typeAssembly == null)
throw new ArgumentNullException ("typeAssembly");
obj = null;
if (FindType (typeName, typeAssembly, out genType)) {
LogMessage ("Instantiating type '{0}'.", typeName);
new ReflectionPermission (ReflectionPermissionFlag.NoFlags).Demand ();
obj = Activator.CreateInstance (genType);
if (obj == null) {
LogMessage ("Unable to instantiate {0}", typeName);
return false;
}
LogMessage ("Instantiated.");
LogMessage ("");
return true;
}
return false;
}
/// <summary>
/// Finds the given type name in the assembly. The type is an out parameter.
/// If the type can't be found, false is returned.
/// </summary>
/// <param name="typeName">Type to find in the given assembly.</param>
/// <param name="typeAssembly">Assembly to search through for the given type name.</param>
/// <param name="genType">The type that was found in the assembly.</param>
/// <returns>True if the type was found, false otherwise.</returns>
protected bool FindType (string typeName, Assembly typeAssembly, out Type genType) {
if (typeAssembly == null)
throw new ArgumentNullException ("typeAssembly");
genType = null;
LogMessage ("Finding type '{0}' in the given assembly.", typeName);
genType = typeAssembly.GetType (typeName);
if (genType == null) {
LogMessage ("Unable to get type {0}.", typeName);
return false;
}
LogMessage ("Found.");
LogMessage ("");
return true;
}
#endregion
}
}
| |
// Copyright 2018 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 gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using pb = Google.Protobuf;
using pbwkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Asset.V1Beta1
{
/// <summary>
/// Settings for a <see cref="AssetServiceClient"/>.
/// </summary>
public sealed partial class AssetServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="AssetServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="AssetServiceSettings"/>.
/// </returns>
public static AssetServiceSettings GetDefault() => new AssetServiceSettings();
/// <summary>
/// Constructs a new <see cref="AssetServiceSettings"/> object with default settings.
/// </summary>
public AssetServiceSettings() { }
private AssetServiceSettings(AssetServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ExportAssetsSettings = existing.ExportAssetsSettings;
ExportAssetsOperationsSettings = existing.ExportAssetsOperationsSettings?.Clone();
BatchGetAssetsHistorySettings = existing.BatchGetAssetsHistorySettings;
OnCopy(existing);
}
partial void OnCopy(AssetServiceSettings existing);
/// <summary>
/// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="AssetServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="grpccore::StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } =
gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="AssetServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="grpccore::StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } =
gaxgrpc::RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="AssetServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="AssetServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="AssetServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings(
delay: sys::TimeSpan.FromMilliseconds(100),
maxDelay: sys::TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="AssetServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="AssetServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="AssetServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 20000 milliseconds</description></item>
/// </list>
/// </remarks>
public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings(
delay: sys::TimeSpan.FromMilliseconds(20000),
maxDelay: sys::TimeSpan.FromMilliseconds(20000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AssetServiceClient.ExportAssets</c> and <c>AssetServiceClient.ExportAssetsAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>AssetServiceClient.ExportAssets</c> and
/// <c>AssetServiceClient.ExportAssetsAsync</c> <see cref="gaxgrpc::RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 20000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description>No status codes</description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public gaxgrpc::CallSettings ExportAssetsSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming(
gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)),
retryFilter: NonIdempotentRetryFilter
)));
/// <summary>
/// Long Running Operation settings for calls to <c>AssetServiceClient.ExportAssets</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 500 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 5000 milliseconds</description></item>
/// <item><description>Total timeout: 300000 milliseconds</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings ExportAssetsOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(
gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000L)),
sys::TimeSpan.FromMilliseconds(500L),
1.5,
sys::TimeSpan.FromMilliseconds(5000L))
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AssetServiceClient.BatchGetAssetsHistory</c> and <c>AssetServiceClient.BatchGetAssetsHistoryAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>AssetServiceClient.BatchGetAssetsHistory</c> and
/// <c>AssetServiceClient.BatchGetAssetsHistoryAsync</c> <see cref="gaxgrpc::RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 20000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public gaxgrpc::CallSettings BatchGetAssetsHistorySettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming(
gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="AssetServiceSettings"/> object.</returns>
public AssetServiceSettings Clone() => new AssetServiceSettings(this);
}
/// <summary>
/// AssetService client wrapper, for convenient use.
/// </summary>
public abstract partial class AssetServiceClient
{
/// <summary>
/// The default endpoint for the AssetService service, which is a host of "cloudasset.googleapis.com" and a port of 443.
/// </summary>
public static gaxgrpc::ServiceEndpoint DefaultEndpoint { get; } = new gaxgrpc::ServiceEndpoint("cloudasset.googleapis.com", 443);
/// <summary>
/// The default AssetService scopes.
/// </summary>
/// <remarks>
/// The default AssetService scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
});
private static readonly gaxgrpc::ChannelPool s_channelPool = new gaxgrpc::ChannelPool(DefaultScopes);
/// <summary>
/// Asynchronously creates a <see cref="AssetServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary. See the example for how to use custom credentials.
/// </summary>
/// <example>
/// This sample shows how to create a client using default credentials:
/// <code>
/// using Google.Cloud.Asset.V1Beta1;
/// ...
/// // When running on Google Cloud Platform this will use the project Compute Credential.
/// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON
/// // credential file to use that credential.
/// AssetServiceClient client = await AssetServiceClient.CreateAsync();
/// </code>
/// This sample shows how to create a client using credentials loaded from a JSON file:
/// <code>
/// using Google.Cloud.Asset.V1Beta1;
/// using Google.Apis.Auth.OAuth2;
/// using Grpc.Auth;
/// using Grpc.Core;
/// ...
/// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json");
/// Channel channel = new Channel(
/// AssetServiceClient.DefaultEndpoint.Host, AssetServiceClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
/// AssetServiceClient client = AssetServiceClient.Create(channel);
/// ...
/// // Shutdown the channel when it is no longer required.
/// await channel.ShutdownAsync();
/// </code>
/// </example>
/// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="AssetServiceSettings"/>.</param>
/// <returns>The task representing the created <see cref="AssetServiceClient"/>.</returns>
public static async stt::Task<AssetServiceClient> CreateAsync(gaxgrpc::ServiceEndpoint endpoint = null, AssetServiceSettings settings = null)
{
grpccore::Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="AssetServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary. See the example for how to use custom credentials.
/// </summary>
/// <example>
/// This sample shows how to create a client using default credentials:
/// <code>
/// using Google.Cloud.Asset.V1Beta1;
/// ...
/// // When running on Google Cloud Platform this will use the project Compute Credential.
/// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON
/// // credential file to use that credential.
/// AssetServiceClient client = AssetServiceClient.Create();
/// </code>
/// This sample shows how to create a client using credentials loaded from a JSON file:
/// <code>
/// using Google.Cloud.Asset.V1Beta1;
/// using Google.Apis.Auth.OAuth2;
/// using Grpc.Auth;
/// using Grpc.Core;
/// ...
/// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json");
/// Channel channel = new Channel(
/// AssetServiceClient.DefaultEndpoint.Host, AssetServiceClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
/// AssetServiceClient client = AssetServiceClient.Create(channel);
/// ...
/// // Shutdown the channel when it is no longer required.
/// channel.ShutdownAsync().Wait();
/// </code>
/// </example>
/// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="AssetServiceSettings"/>.</param>
/// <returns>The created <see cref="AssetServiceClient"/>.</returns>
public static AssetServiceClient Create(gaxgrpc::ServiceEndpoint endpoint = null, AssetServiceSettings settings = null)
{
grpccore::Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="AssetServiceClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="grpccore::Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="AssetServiceSettings"/>.</param>
/// <returns>The created <see cref="AssetServiceClient"/>.</returns>
public static AssetServiceClient Create(grpccore::Channel channel, AssetServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(channel, nameof(channel));
return Create(new grpccore::DefaultCallInvoker(channel), settings);
}
/// <summary>
/// Creates a <see cref="AssetServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="AssetServiceSettings"/>.</param>
/// <returns>The created <see cref="AssetServiceClient"/>.</returns>
public static AssetServiceClient Create(grpccore::CallInvoker callInvoker, AssetServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpccore::Interceptors.Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpccore::Interceptors.CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AssetService.AssetServiceClient grpcClient = new AssetService.AssetServiceClient(callInvoker);
return new AssetServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(gaxgrpc::ServiceEndpoint, AssetServiceSettings)"/>
/// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, AssetServiceSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(gaxgrpc::ServiceEndpoint, AssetServiceSettings)"/>
/// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, AssetServiceSettings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC AssetService client.
/// </summary>
public virtual AssetService.AssetServiceClient GrpcClient
{
get { throw new sys::NotImplementedException(); }
}
/// <summary>
/// Exports assets with time and resource types to a given Google Cloud Storage
/// location. The output format is newline-delimited JSON.
/// This API implements the [google.longrunning.Operation][google.longrunning.Operation] API allowing users
/// to keep track of the export.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<lro::Operation<ExportAssetsResponse, ExportAssetsRequest>> ExportAssetsAsync(
ExportAssetsRequest request,
gaxgrpc::CallSettings callSettings = null)
{
throw new sys::NotImplementedException();
}
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>ExportAssetsAsync</c>.
/// </summary>
/// <param name="operationName">The name of a previously invoked operation. Must not be <c>null</c> or empty.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<ExportAssetsResponse, ExportAssetsRequest>> PollOnceExportAssetsAsync(
string operationName,
gaxgrpc::CallSettings callSettings = null) => lro::Operation<ExportAssetsResponse, ExportAssetsRequest>.PollOnceFromNameAsync(
gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)),
ExportAssetsOperationsClient,
callSettings);
/// <summary>
/// Exports assets with time and resource types to a given Google Cloud Storage
/// location. The output format is newline-delimited JSON.
/// This API implements the [google.longrunning.Operation][google.longrunning.Operation] API allowing users
/// to keep track of the export.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual lro::Operation<ExportAssetsResponse, ExportAssetsRequest> ExportAssets(
ExportAssetsRequest request,
gaxgrpc::CallSettings callSettings = null)
{
throw new sys::NotImplementedException();
}
/// <summary>
/// The long-running operations client for <c>ExportAssets</c>.
/// </summary>
public virtual lro::OperationsClient ExportAssetsOperationsClient
{
get { throw new sys::NotImplementedException(); }
}
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>ExportAssets</c>.
/// </summary>
/// <param name="operationName">The name of a previously invoked operation. Must not be <c>null</c> or empty.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<ExportAssetsResponse, ExportAssetsRequest> PollOnceExportAssets(
string operationName,
gaxgrpc::CallSettings callSettings = null) => lro::Operation<ExportAssetsResponse, ExportAssetsRequest>.PollOnceFromName(
gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)),
ExportAssetsOperationsClient,
callSettings);
/// <summary>
/// Batch gets assets update history that overlaps a time window.
/// For RESOURCE content, this API outputs history with asset in both
/// non-delete or deleted status.
/// For IAM_POLICY content, this API only outputs history when asset and its
/// attached IAM POLICY both exist. So there may be gaps in the output history.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<BatchGetAssetsHistoryResponse> BatchGetAssetsHistoryAsync(
BatchGetAssetsHistoryRequest request,
gaxgrpc::CallSettings callSettings = null)
{
throw new sys::NotImplementedException();
}
/// <summary>
/// Batch gets assets update history that overlaps a time window.
/// For RESOURCE content, this API outputs history with asset in both
/// non-delete or deleted status.
/// For IAM_POLICY content, this API only outputs history when asset and its
/// attached IAM POLICY both exist. So there may be gaps in the output history.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="st::CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<BatchGetAssetsHistoryResponse> BatchGetAssetsHistoryAsync(
BatchGetAssetsHistoryRequest request,
st::CancellationToken cancellationToken) => BatchGetAssetsHistoryAsync(
request,
gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Batch gets assets update history that overlaps a time window.
/// For RESOURCE content, this API outputs history with asset in both
/// non-delete or deleted status.
/// For IAM_POLICY content, this API only outputs history when asset and its
/// attached IAM POLICY both exist. So there may be gaps in the output history.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual BatchGetAssetsHistoryResponse BatchGetAssetsHistory(
BatchGetAssetsHistoryRequest request,
gaxgrpc::CallSettings callSettings = null)
{
throw new sys::NotImplementedException();
}
}
/// <summary>
/// AssetService client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class AssetServiceClientImpl : AssetServiceClient
{
private readonly gaxgrpc::ApiCall<ExportAssetsRequest, lro::Operation> _callExportAssets;
private readonly gaxgrpc::ApiCall<BatchGetAssetsHistoryRequest, BatchGetAssetsHistoryResponse> _callBatchGetAssetsHistory;
/// <summary>
/// Constructs a client wrapper for the AssetService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AssetServiceSettings"/> used within this client </param>
public AssetServiceClientImpl(AssetService.AssetServiceClient grpcClient, AssetServiceSettings settings)
{
GrpcClient = grpcClient;
AssetServiceSettings effectiveSettings = settings ?? AssetServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
ExportAssetsOperationsClient = new lro::OperationsClientImpl(
grpcClient.CreateOperationsClient(), effectiveSettings.ExportAssetsOperationsSettings);
_callExportAssets = clientHelper.BuildApiCall<ExportAssetsRequest, lro::Operation>(
GrpcClient.ExportAssetsAsync, GrpcClient.ExportAssets, effectiveSettings.ExportAssetsSettings);
_callBatchGetAssetsHistory = clientHelper.BuildApiCall<BatchGetAssetsHistoryRequest, BatchGetAssetsHistoryResponse>(
GrpcClient.BatchGetAssetsHistoryAsync, GrpcClient.BatchGetAssetsHistory, effectiveSettings.BatchGetAssetsHistorySettings);
Modify_ApiCall(ref _callExportAssets);
Modify_ExportAssetsApiCall(ref _callExportAssets);
Modify_ApiCall(ref _callBatchGetAssetsHistory);
Modify_BatchGetAssetsHistoryApiCall(ref _callBatchGetAssetsHistory);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
// Partial methods are named to (mostly) ensure there cannot be conflicts with RPC method names.
// Partial methods called for every ApiCall on construction.
// Allows modification of all the underlying ApiCall objects.
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call)
where TRequest : class, pb::IMessage<TRequest>
where TResponse : class, pb::IMessage<TResponse>;
// Partial methods called for each ApiCall on construction.
// Allows per-RPC-method modification of the underlying ApiCall object.
partial void Modify_ExportAssetsApiCall(ref gaxgrpc::ApiCall<ExportAssetsRequest, lro::Operation> call);
partial void Modify_BatchGetAssetsHistoryApiCall(ref gaxgrpc::ApiCall<BatchGetAssetsHistoryRequest, BatchGetAssetsHistoryResponse> call);
partial void OnConstruction(AssetService.AssetServiceClient grpcClient, AssetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>
/// The underlying gRPC AssetService client.
/// </summary>
public override AssetService.AssetServiceClient GrpcClient { get; }
// Partial methods called on each request.
// Allows per-RPC-call modification to the request and CallSettings objects,
// before the underlying RPC is performed.
partial void Modify_ExportAssetsRequest(ref ExportAssetsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_BatchGetAssetsHistoryRequest(ref BatchGetAssetsHistoryRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Exports assets with time and resource types to a given Google Cloud Storage
/// location. The output format is newline-delimited JSON.
/// This API implements the [google.longrunning.Operation][google.longrunning.Operation] API allowing users
/// to keep track of the export.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override async stt::Task<lro::Operation<ExportAssetsResponse, ExportAssetsRequest>> ExportAssetsAsync(
ExportAssetsRequest request,
gaxgrpc::CallSettings callSettings = null)
{
Modify_ExportAssetsRequest(ref request, ref callSettings);
return new lro::Operation<ExportAssetsResponse, ExportAssetsRequest>(
await _callExportAssets.Async(request, callSettings).ConfigureAwait(false), ExportAssetsOperationsClient);
}
/// <summary>
/// Exports assets with time and resource types to a given Google Cloud Storage
/// location. The output format is newline-delimited JSON.
/// This API implements the [google.longrunning.Operation][google.longrunning.Operation] API allowing users
/// to keep track of the export.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override lro::Operation<ExportAssetsResponse, ExportAssetsRequest> ExportAssets(
ExportAssetsRequest request,
gaxgrpc::CallSettings callSettings = null)
{
Modify_ExportAssetsRequest(ref request, ref callSettings);
return new lro::Operation<ExportAssetsResponse, ExportAssetsRequest>(
_callExportAssets.Sync(request, callSettings), ExportAssetsOperationsClient);
}
/// <summary>
/// The long-running operations client for <c>ExportAssets</c>.
/// </summary>
public override lro::OperationsClient ExportAssetsOperationsClient { get; }
/// <summary>
/// Batch gets assets update history that overlaps a time window.
/// For RESOURCE content, this API outputs history with asset in both
/// non-delete or deleted status.
/// For IAM_POLICY content, this API only outputs history when asset and its
/// attached IAM POLICY both exist. So there may be gaps in the output history.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override stt::Task<BatchGetAssetsHistoryResponse> BatchGetAssetsHistoryAsync(
BatchGetAssetsHistoryRequest request,
gaxgrpc::CallSettings callSettings = null)
{
Modify_BatchGetAssetsHistoryRequest(ref request, ref callSettings);
return _callBatchGetAssetsHistory.Async(request, callSettings);
}
/// <summary>
/// Batch gets assets update history that overlaps a time window.
/// For RESOURCE content, this API outputs history with asset in both
/// non-delete or deleted status.
/// For IAM_POLICY content, this API only outputs history when asset and its
/// attached IAM POLICY both exist. So there may be gaps in the output history.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override BatchGetAssetsHistoryResponse BatchGetAssetsHistory(
BatchGetAssetsHistoryRequest request,
gaxgrpc::CallSettings callSettings = null)
{
Modify_BatchGetAssetsHistoryRequest(ref request, ref callSettings);
return _callBatchGetAssetsHistory.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
// Partial Grpc class to enable LRO client creation
public static partial class AssetService
{
public partial class AssetServiceClient
{
/// <summary>
/// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as this client.
/// </summary>
/// <returns>A new Operations client for the same target as this client.</returns>
public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal abstract class ExprVisitorBase
{
public Expr Visit(Expr pExpr)
{
if (pExpr == null)
{
return null;
}
Expr pResult;
if (IsCachedExpr(pExpr, out pResult))
{
return pResult;
}
if (pExpr is ExprStatement statement)
{
return CacheExprMapping(pExpr, DispatchStatementList(statement));
}
return CacheExprMapping(pExpr, Dispatch(pExpr));
}
/////////////////////////////////////////////////////////////////////////////////
private ExprStatement DispatchStatementList(ExprStatement expr)
{
Debug.Assert(expr != null);
ExprStatement first = expr;
ExprStatement pexpr = first;
while (pexpr != null)
{
// If the processor replaces the statement -- potentially with
// null, another statement, or a list of statements -- then we
// make sure that the statement list is hooked together correctly.
ExprStatement next = pexpr.OptionalNextStatement;
ExprStatement old = pexpr;
// Unhook the next one.
pexpr.OptionalNextStatement = null;
ExprStatement result = Dispatch(pexpr) as ExprStatement;
if (pexpr == first)
{
first = result;
}
else
{
pexpr.OptionalNextStatement = result;
}
// A transformation may return back a list of statements (or
// if the statements have been determined to be unnecessary,
// perhaps it has simply returned null.)
//
// Skip visiting the new list, then hook the tail of the old list
// up to the end of the new list.
while (pexpr.OptionalNextStatement != null)
{
pexpr = pexpr.OptionalNextStatement;
}
// Re-hook the next pointer.
pexpr.OptionalNextStatement = next;
}
return first;
}
/////////////////////////////////////////////////////////////////////////////////
private bool IsCachedExpr(Expr pExpr, out Expr pTransformedExpr)
{
pTransformedExpr = null;
return false;
}
/////////////////////////////////////////////////////////////////////////////////
private Expr CacheExprMapping(Expr pExpr, Expr pTransformedExpr)
{
return pTransformedExpr;
}
protected virtual Expr Dispatch(Expr pExpr)
{
switch (pExpr.Kind)
{
case ExpressionKind.Block:
return VisitBLOCK(pExpr as ExprBlock);
case ExpressionKind.Return:
return VisitRETURN(pExpr as ExprReturn);
case ExpressionKind.BinaryOp:
return VisitBINOP(pExpr as ExprBinOp);
case ExpressionKind.UnaryOp:
return VisitUNARYOP(pExpr as ExprUnaryOp);
case ExpressionKind.Assignment:
return VisitASSIGNMENT(pExpr as ExprAssignment);
case ExpressionKind.List:
return VisitLIST(pExpr as ExprList);
case ExpressionKind.ArrayIndex:
return VisitARRAYINDEX(pExpr as ExprArrayIndex);
case ExpressionKind.Call:
return VisitCALL(pExpr as ExprCall);
case ExpressionKind.Event:
return VisitEVENT(pExpr as ExprEvent);
case ExpressionKind.Field:
return VisitFIELD(pExpr as ExprField);
case ExpressionKind.Local:
return VisitLOCAL(pExpr as ExprLocal);
case ExpressionKind.Constant:
return VisitCONSTANT(pExpr as ExprConstant);
case ExpressionKind.Class:
return VisitCLASS(pExpr as ExprClass);
case ExpressionKind.FunctionPointer:
return VisitFUNCPTR(pExpr as ExprFuncPtr);
case ExpressionKind.Property:
return VisitPROP(pExpr as ExprProperty);
case ExpressionKind.Multi:
return VisitMULTI(pExpr as ExprMulti);
case ExpressionKind.MultiGet:
return VisitMULTIGET(pExpr as ExprMultiGet);
case ExpressionKind.Wrap:
return VisitWRAP(pExpr as ExprWrap);
case ExpressionKind.Concat:
return VisitCONCAT(pExpr as ExprConcat);
case ExpressionKind.ArrayInit:
return VisitARRINIT(pExpr as ExprArrayInit);
case ExpressionKind.Cast:
return VisitCAST(pExpr as ExprCast);
case ExpressionKind.UserDefinedConversion:
return VisitUSERDEFINEDCONVERSION(pExpr as ExprUserDefinedConversion);
case ExpressionKind.TypeOf:
return VisitTYPEOF(pExpr as ExprTypeOf);
case ExpressionKind.ZeroInit:
return VisitZEROINIT(pExpr as ExprZeroInit);
case ExpressionKind.UserLogicalOp:
return VisitUSERLOGOP(pExpr as ExprUserLogicalOp);
case ExpressionKind.MemberGroup:
return VisitMEMGRP(pExpr as ExprMemberGroup);
case ExpressionKind.BoundLambda:
return VisitBOUNDLAMBDA(pExpr as ExprBoundLambda);
case ExpressionKind.HoistedLocalExpression:
return VisitHOISTEDLOCALEXPR(pExpr as ExprHoistedLocalExpr);
case ExpressionKind.FieldInfo:
return VisitFIELDINFO(pExpr as ExprFieldInfo);
case ExpressionKind.MethodInfo:
return VisitMETHODINFO(pExpr as ExprMethodInfo);
// Binary operators
case ExpressionKind.EqualsParam:
return VisitEQUALS(pExpr as ExprBinOp);
case ExpressionKind.Compare:
return VisitCOMPARE(pExpr as ExprBinOp);
case ExpressionKind.NotEq:
return VisitNE(pExpr as ExprBinOp);
case ExpressionKind.LessThan:
return VisitLT(pExpr as ExprBinOp);
case ExpressionKind.LessThanOrEqual:
return VisitLE(pExpr as ExprBinOp);
case ExpressionKind.GreaterThan:
return VisitGT(pExpr as ExprBinOp);
case ExpressionKind.GreaterThanOrEqual:
return VisitGE(pExpr as ExprBinOp);
case ExpressionKind.Add:
return VisitADD(pExpr as ExprBinOp);
case ExpressionKind.Subtract:
return VisitSUB(pExpr as ExprBinOp);
case ExpressionKind.Multiply:
return VisitMUL(pExpr as ExprBinOp);
case ExpressionKind.Divide:
return VisitDIV(pExpr as ExprBinOp);
case ExpressionKind.Modulo:
return VisitMOD(pExpr as ExprBinOp);
case ExpressionKind.BitwiseAnd:
return VisitBITAND(pExpr as ExprBinOp);
case ExpressionKind.BitwiseOr:
return VisitBITOR(pExpr as ExprBinOp);
case ExpressionKind.BitwiseExclusiveOr:
return VisitBITXOR(pExpr as ExprBinOp);
case ExpressionKind.LeftShirt:
return VisitLSHIFT(pExpr as ExprBinOp);
case ExpressionKind.RightShift:
return VisitRSHIFT(pExpr as ExprBinOp);
case ExpressionKind.LogicalAnd:
return VisitLOGAND(pExpr as ExprBinOp);
case ExpressionKind.LogicalOr:
return VisitLOGOR(pExpr as ExprBinOp);
case ExpressionKind.Sequence:
return VisitSEQUENCE(pExpr as ExprBinOp);
case ExpressionKind.SequenceReverse:
return VisitSEQREV(pExpr as ExprBinOp);
case ExpressionKind.Save:
return VisitSAVE(pExpr as ExprBinOp);
case ExpressionKind.Swap:
return VisitSWAP(pExpr as ExprBinOp);
case ExpressionKind.Indir:
return VisitINDIR(pExpr as ExprBinOp);
case ExpressionKind.StringEq:
return VisitSTRINGEQ(pExpr as ExprBinOp);
case ExpressionKind.StringNotEq:
return VisitSTRINGNE(pExpr as ExprBinOp);
case ExpressionKind.DelegateEq:
return VisitDELEGATEEQ(pExpr as ExprBinOp);
case ExpressionKind.DelegateNotEq:
return VisitDELEGATENE(pExpr as ExprBinOp);
case ExpressionKind.DelegateAdd:
return VisitDELEGATEADD(pExpr as ExprBinOp);
case ExpressionKind.DelegateSubtract:
return VisitDELEGATESUB(pExpr as ExprBinOp);
case ExpressionKind.Eq:
return VisitEQ(pExpr as ExprBinOp);
// Unary operators
case ExpressionKind.True:
return VisitTRUE(pExpr as ExprUnaryOp);
case ExpressionKind.False:
return VisitFALSE(pExpr as ExprUnaryOp);
case ExpressionKind.Inc:
return VisitINC(pExpr as ExprUnaryOp);
case ExpressionKind.Dec:
return VisitDEC(pExpr as ExprUnaryOp);
case ExpressionKind.LogicalNot:
return VisitLOGNOT(pExpr as ExprUnaryOp);
case ExpressionKind.Negate:
return VisitNEG(pExpr as ExprUnaryOp);
case ExpressionKind.UnaryPlus:
return VisitUPLUS(pExpr as ExprUnaryOp);
case ExpressionKind.BitwiseNot:
return VisitBITNOT(pExpr as ExprUnaryOp);
case ExpressionKind.Addr:
return VisitADDR(pExpr as ExprUnaryOp);
case ExpressionKind.DecimalNegate:
return VisitDECIMALNEG(pExpr as ExprUnaryOp);
case ExpressionKind.DecimalInc:
return VisitDECIMALINC(pExpr as ExprUnaryOp);
case ExpressionKind.DecimalDec:
return VisitDECIMALDEC(pExpr as ExprUnaryOp);
default:
throw Error.InternalCompilerError();
}
}
private void VisitChildren(Expr pExpr)
{
Debug.Assert(pExpr != null);
Expr exprRet;
switch (pExpr.Kind)
{
case ExpressionKind.List:
// Lists are a special case. We treat a list not as a
// binary node but rather as a node with n children.
ExprList list = (ExprList)pExpr;
while (true)
{
list.OptionalElement = Visit(list.OptionalElement);
Expr nextNode = list.OptionalNextListNode;
if (nextNode == null)
{
return;
}
if (!(nextNode is ExprList next))
{
list.OptionalNextListNode = Visit(nextNode);
return;
}
list = next;
}
case ExpressionKind.Assignment:
exprRet = Visit((pExpr as ExprAssignment).LHS);
Debug.Assert(exprRet != null);
(pExpr as ExprAssignment).LHS = exprRet;
exprRet = Visit((pExpr as ExprAssignment).RHS);
Debug.Assert(exprRet != null);
(pExpr as ExprAssignment).RHS = exprRet;
break;
case ExpressionKind.ArrayIndex:
exprRet = Visit((pExpr as ExprArrayIndex).Array);
Debug.Assert(exprRet != null);
(pExpr as ExprArrayIndex).Array = exprRet;
exprRet = Visit((pExpr as ExprArrayIndex).Index);
Debug.Assert(exprRet != null);
(pExpr as ExprArrayIndex).Index = exprRet;
break;
case ExpressionKind.UnaryOp:
case ExpressionKind.True:
case ExpressionKind.False:
case ExpressionKind.Inc:
case ExpressionKind.Dec:
case ExpressionKind.LogicalNot:
case ExpressionKind.Negate:
case ExpressionKind.UnaryPlus:
case ExpressionKind.BitwiseNot:
case ExpressionKind.Addr:
case ExpressionKind.DecimalNegate:
case ExpressionKind.DecimalInc:
case ExpressionKind.DecimalDec:
exprRet = Visit((pExpr as ExprUnaryOp).Child);
Debug.Assert(exprRet != null);
(pExpr as ExprUnaryOp).Child = exprRet;
break;
case ExpressionKind.UserLogicalOp:
exprRet = Visit((pExpr as ExprUserLogicalOp).TrueFalseCall);
Debug.Assert(exprRet != null);
(pExpr as ExprUserLogicalOp).TrueFalseCall = exprRet;
exprRet = Visit((pExpr as ExprUserLogicalOp).OperatorCall);
Debug.Assert(exprRet != null);
(pExpr as ExprUserLogicalOp).OperatorCall = exprRet as ExprCall;
exprRet = Visit((pExpr as ExprUserLogicalOp).FirstOperandToExamine);
Debug.Assert(exprRet != null);
(pExpr as ExprUserLogicalOp).FirstOperandToExamine = exprRet;
break;
case ExpressionKind.TypeOf:
exprRet = Visit((pExpr as ExprTypeOf).SourceType);
(pExpr as ExprTypeOf).SourceType = exprRet as ExprClass;
break;
case ExpressionKind.Cast:
exprRet = Visit((pExpr as ExprCast).Argument);
Debug.Assert(exprRet != null);
(pExpr as ExprCast).Argument = exprRet;
exprRet = Visit((pExpr as ExprCast).DestinationType);
(pExpr as ExprCast).DestinationType = exprRet as ExprClass;
break;
case ExpressionKind.UserDefinedConversion:
exprRet = Visit((pExpr as ExprUserDefinedConversion).UserDefinedCall);
Debug.Assert(exprRet != null);
(pExpr as ExprUserDefinedConversion).UserDefinedCall = exprRet;
break;
case ExpressionKind.ZeroInit:
exprRet = Visit((pExpr as ExprZeroInit).OptionalArgument);
(pExpr as ExprZeroInit).OptionalArgument = exprRet;
// Used for when we zeroinit 0 parameter constructors for structs/enums.
exprRet = Visit((pExpr as ExprZeroInit).OptionalConstructorCall);
(pExpr as ExprZeroInit).OptionalConstructorCall = exprRet;
break;
case ExpressionKind.Block:
exprRet = Visit((pExpr as ExprBlock).OptionalStatements);
(pExpr as ExprBlock).OptionalStatements = exprRet as ExprStatement;
break;
case ExpressionKind.MemberGroup:
// The object expression. NULL for a static invocation.
exprRet = Visit((pExpr as ExprMemberGroup).OptionalObject);
(pExpr as ExprMemberGroup).OptionalObject = exprRet;
break;
case ExpressionKind.Call:
exprRet = Visit((pExpr as ExprCall).OptionalArguments);
(pExpr as ExprCall).OptionalArguments = exprRet;
exprRet = Visit((pExpr as ExprCall).MemberGroup);
Debug.Assert(exprRet != null);
(pExpr as ExprCall).MemberGroup = exprRet as ExprMemberGroup;
break;
case ExpressionKind.Property:
exprRet = Visit((pExpr as ExprProperty).OptionalArguments);
(pExpr as ExprProperty).OptionalArguments = exprRet;
exprRet = Visit((pExpr as ExprProperty).MemberGroup);
Debug.Assert(exprRet != null);
(pExpr as ExprProperty).MemberGroup = exprRet as ExprMemberGroup;
break;
case ExpressionKind.Field:
exprRet = Visit((pExpr as ExprField).OptionalObject);
(pExpr as ExprField).OptionalObject = exprRet;
break;
case ExpressionKind.Event:
exprRet = Visit((pExpr as ExprEvent).OptionalObject);
(pExpr as ExprEvent).OptionalObject = exprRet;
break;
case ExpressionKind.Return:
exprRet = Visit((pExpr as ExprReturn).OptionalObject);
(pExpr as ExprReturn).OptionalObject = exprRet;
break;
case ExpressionKind.Constant:
// Used for when we zeroinit 0 parameter constructors for structs/enums.
exprRet = Visit((pExpr as ExprConstant).OptionalConstructorCall);
(pExpr as ExprConstant).OptionalConstructorCall = exprRet;
break;
/*************************************************************************************************
TYPEEXPRs defined:
The following exprs are used to represent the results of type binding, and are defined as follows:
TYPEARGUMENTS - This wraps the type arguments for a class. It contains the TypeArray* which is
associated with the AggregateType for the instantiation of the class.
TYPEORNAMESPACE - This is the base class for this set of Exprs. When binding a type, the result
must be a type or a namespace. This Expr encapsulates that fact. The lhs member is the Expr
tree that was bound to resolve the type or namespace.
TYPEORNAMESPACEERROR - This is the error class for the type or namespace exprs when we don't know
what to bind it to.
The following two exprs all have a TYPEORNAMESPACE child, which is their fundamental type:
POINTERTYPE - This wraps the sym for the pointer type.
NULLABLETYPE - This wraps the sym for the nullable type.
CLASS - This represents an instantiation of a class.
NSPACE - This represents a namespace, which is the intermediate step when attempting to bind
a qualified name.
ALIAS - This represents an alias
*************************************************************************************************/
case ExpressionKind.Multi:
exprRet = Visit((pExpr as ExprMulti).Left);
Debug.Assert(exprRet != null);
(pExpr as ExprMulti).Left = exprRet;
exprRet = Visit((pExpr as ExprMulti).Operator);
Debug.Assert(exprRet != null);
(pExpr as ExprMulti).Operator = exprRet;
break;
case ExpressionKind.Concat:
exprRet = Visit((pExpr as ExprConcat).FirstArgument);
Debug.Assert(exprRet != null);
(pExpr as ExprConcat).FirstArgument = exprRet;
exprRet = Visit((pExpr as ExprConcat).SecondArgument);
Debug.Assert(exprRet != null);
(pExpr as ExprConcat).SecondArgument = exprRet;
break;
case ExpressionKind.ArrayInit:
exprRet = Visit((pExpr as ExprArrayInit).OptionalArguments);
(pExpr as ExprArrayInit).OptionalArguments = exprRet;
exprRet = Visit((pExpr as ExprArrayInit).OptionalArgumentDimensions);
(pExpr as ExprArrayInit).OptionalArgumentDimensions = exprRet;
break;
case ExpressionKind.BoundLambda:
exprRet = Visit((pExpr as ExprBoundLambda).OptionalBody);
(pExpr as ExprBoundLambda).OptionalBody = exprRet as ExprBlock;
break;
case ExpressionKind.Local:
case ExpressionKind.Class:
case ExpressionKind.FunctionPointer:
case ExpressionKind.MultiGet:
case ExpressionKind.Wrap:
case ExpressionKind.NoOp:
case ExpressionKind.HoistedLocalExpression:
case ExpressionKind.FieldInfo:
case ExpressionKind.MethodInfo:
break;
default:
pExpr.AssertIsBin();
exprRet = Visit((pExpr as ExprBinOp).OptionalLeftChild);
(pExpr as ExprBinOp).OptionalLeftChild = exprRet;
exprRet = Visit((pExpr as ExprBinOp).OptionalRightChild);
(pExpr as ExprBinOp).OptionalRightChild = exprRet;
break;
}
}
protected virtual Expr VisitEXPR(Expr pExpr)
{
VisitChildren(pExpr);
return pExpr;
}
protected virtual Expr VisitBLOCK(ExprBlock pExpr)
{
return VisitSTMT(pExpr);
}
protected virtual Expr VisitRETURN(ExprReturn pExpr)
{
return VisitSTMT(pExpr);
}
protected virtual Expr VisitCLASS(ExprClass pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitSTMT(ExprStatement pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitBINOP(ExprBinOp pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitLIST(ExprList pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitASSIGNMENT(ExprAssignment pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitARRAYINDEX(ExprArrayIndex pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitUNARYOP(ExprUnaryOp pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitUSERLOGOP(ExprUserLogicalOp pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitTYPEOF(ExprTypeOf pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitCAST(ExprCast pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitUSERDEFINEDCONVERSION(ExprUserDefinedConversion pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitZEROINIT(ExprZeroInit pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitMEMGRP(ExprMemberGroup pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitCALL(ExprCall pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitPROP(ExprProperty pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitFIELD(ExprField pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitEVENT(ExprEvent pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitLOCAL(ExprLocal pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitCONSTANT(ExprConstant pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitFUNCPTR(ExprFuncPtr pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitMULTIGET(ExprMultiGet pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitMULTI(ExprMulti pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitWRAP(ExprWrap pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitCONCAT(ExprConcat pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitARRINIT(ExprArrayInit pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitBOUNDLAMBDA(ExprBoundLambda pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitHOISTEDLOCALEXPR(ExprHoistedLocalExpr pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitFIELDINFO(ExprFieldInfo pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitMETHODINFO(ExprMethodInfo pExpr)
{
return VisitEXPR(pExpr);
}
protected virtual Expr VisitEQUALS(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitCOMPARE(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitEQ(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitNE(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitLE(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitGE(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitADD(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitSUB(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitDIV(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitBITAND(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitBITOR(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitLSHIFT(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitLOGAND(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitSEQUENCE(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitSAVE(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitINDIR(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitSTRINGEQ(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitDELEGATEEQ(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitDELEGATEADD(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitLT(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitMUL(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitBITXOR(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitRSHIFT(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitLOGOR(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitSEQREV(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitSTRINGNE(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitDELEGATENE(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitGT(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitMOD(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitSWAP(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitDELEGATESUB(ExprBinOp pExpr)
{
return VisitBINOP(pExpr);
}
protected virtual Expr VisitTRUE(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitINC(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitLOGNOT(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitNEG(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitBITNOT(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitADDR(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitDECIMALNEG(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitDECIMALDEC(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitFALSE(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitDEC(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitUPLUS(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
protected virtual Expr VisitDECIMALINC(ExprUnaryOp pExpr)
{
return VisitUNARYOP(pExpr);
}
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_834 : MapLoop
{
public M_834() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_N1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new L_INS(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
//1000
public class L_N1 : MapLoop
{
public L_N1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_ACT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//1100
public class L_ACT : MapLoop
{
public L_ACT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new ACT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2000
public class L_INS : MapLoop
{
public L_INS(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new INS() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_NM1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_DSB(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 4 },
new L_HD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new L_LC(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_FSA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new L_RP(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2100
public class L_NM1 : MapLoop
{
public L_NM1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new EC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new ICM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new HLH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new HI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new LUI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2200
public class L_DSB : MapLoop
{
public L_DSB(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new DSB() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new AD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//2300
public class L_HD : MapLoop
{
public L_HD(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new HD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new IDC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 30 },
new L_COB(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
});
}
}
//2310
public class L_LX : MapLoop
{
public L_LX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new PRV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 6 },
new PLA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2320
public class L_COB : MapLoop
{
public L_COB(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new COB() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
});
}
}
//2400
public class L_LC : MapLoop
{
public L_LC(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_BEN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
});
}
}
//2410
public class L_BEN : MapLoop
{
public L_BEN(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new BEN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2500
public class L_FSA : MapLoop
{
public L_FSA(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new FSA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2600
public class L_RP : MapLoop
{
public L_RP(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new RP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new INV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new K3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new REL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_NM1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_FC(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_AIN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2610
public class L_NM1_1 : MapLoop
{
public L_NM1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new BEN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_NX1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2620
public class L_NX1 : MapLoop
{
public L_NX1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NX1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2630
public class L_FC : MapLoop
{
public L_FC(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new FC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_INV(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2640
public class L_INV : MapLoop
{
public L_INV(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new INV() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new ENT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new K3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
});
}
}
//2650
public class L_AIN : MapLoop
{
public L_AIN(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new AIN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass()]
public partial class TabHost : android.widget.FrameLayout, android.view.ViewTreeObserver.OnTouchModeChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected TabHost(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.TabHost.OnTabChangeListener_))]
public partial interface OnTabChangeListener : global::MonoJavaBridge.IJavaObject
{
void onTabChanged(java.lang.String arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.TabHost.OnTabChangeListener))]
internal sealed partial class OnTabChangeListener_ : java.lang.Object, OnTabChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnTabChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.widget.TabHost.OnTabChangeListener.onTabChanged(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.OnTabChangeListener_.staticClass, "onTabChanged", "(Ljava/lang/String;)V", ref global::android.widget.TabHost.OnTabChangeListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static OnTabChangeListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.TabHost.OnTabChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/TabHost$OnTabChangeListener"));
}
}
public delegate void OnTabChangeListenerDelegate(java.lang.String arg0);
internal partial class OnTabChangeListenerDelegateWrapper : java.lang.Object, OnTabChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnTabChangeListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnTabChangeListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.TabHost.OnTabChangeListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.widget.TabHost.OnTabChangeListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.widget.TabHost.OnTabChangeListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TabHost.OnTabChangeListenerDelegateWrapper.staticClass, global::android.widget.TabHost.OnTabChangeListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnTabChangeListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.TabHost.OnTabChangeListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/TabHost_OnTabChangeListenerDelegateWrapper"));
}
}
internal partial class OnTabChangeListenerDelegateWrapper
{
private OnTabChangeListenerDelegate myDelegate;
public void onTabChanged(java.lang.String arg0)
{
myDelegate(arg0);
}
public static implicit operator OnTabChangeListenerDelegateWrapper(OnTabChangeListenerDelegate d)
{
global::android.widget.TabHost.OnTabChangeListenerDelegateWrapper ret = new global::android.widget.TabHost.OnTabChangeListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.TabHost.TabContentFactory_))]
public partial interface TabContentFactory : global::MonoJavaBridge.IJavaObject
{
global::android.view.View createTabContent(java.lang.String arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.TabHost.TabContentFactory))]
internal sealed partial class TabContentFactory_ : java.lang.Object, TabContentFactory
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal TabContentFactory_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
global::android.view.View android.widget.TabHost.TabContentFactory.createTabContent(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.TabContentFactory_.staticClass, "createTabContent", "(Ljava/lang/String;)Landroid/view/View;", ref global::android.widget.TabHost.TabContentFactory_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.view.View;
}
static TabContentFactory_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.TabHost.TabContentFactory_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/TabHost$TabContentFactory"));
}
}
public delegate android.view.View TabContentFactoryDelegate(java.lang.String arg0);
internal partial class TabContentFactoryDelegateWrapper : java.lang.Object, TabContentFactory
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected TabContentFactoryDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public TabContentFactoryDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.TabHost.TabContentFactoryDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.widget.TabHost.TabContentFactoryDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.widget.TabHost.TabContentFactoryDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TabHost.TabContentFactoryDelegateWrapper.staticClass, global::android.widget.TabHost.TabContentFactoryDelegateWrapper._m0);
Init(@__env, handle);
}
static TabContentFactoryDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.TabHost.TabContentFactoryDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/TabHost_TabContentFactoryDelegateWrapper"));
}
}
internal partial class TabContentFactoryDelegateWrapper
{
private TabContentFactoryDelegate myDelegate;
public android.view.View createTabContent(java.lang.String arg0)
{
return myDelegate(arg0);
}
public static implicit operator TabContentFactoryDelegateWrapper(TabContentFactoryDelegate d)
{
global::android.widget.TabHost.TabContentFactoryDelegateWrapper ret = new global::android.widget.TabHost.TabContentFactoryDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaClass()]
public partial class TabSpec : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected TabSpec(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
public new global::java.lang.String Tag
{
get
{
return getTag();
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual global::java.lang.String getTag()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.widget.TabHost.TabSpec.staticClass, "getTag", "()Ljava/lang/String;", ref global::android.widget.TabHost.TabSpec._m0) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::android.widget.TabHost.TabSpec setIndicator(java.lang.CharSequence arg0, android.graphics.drawable.Drawable arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.TabSpec.staticClass, "setIndicator", "(Ljava/lang/CharSequence;Landroid/graphics/drawable/Drawable;)Landroid/widget/TabHost$TabSpec;", ref global::android.widget.TabHost.TabSpec._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.widget.TabHost.TabSpec;
}
public android.widget.TabHost.TabSpec setIndicator(string arg0, android.graphics.drawable.Drawable arg1)
{
return setIndicator((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual global::android.widget.TabHost.TabSpec setIndicator(android.view.View arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.TabSpec.staticClass, "setIndicator", "(Landroid/view/View;)Landroid/widget/TabHost$TabSpec;", ref global::android.widget.TabHost.TabSpec._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.widget.TabHost.TabSpec;
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual global::android.widget.TabHost.TabSpec setIndicator(java.lang.CharSequence arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.TabSpec.staticClass, "setIndicator", "(Ljava/lang/CharSequence;)Landroid/widget/TabHost$TabSpec;", ref global::android.widget.TabHost.TabSpec._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.widget.TabHost.TabSpec;
}
public android.widget.TabHost.TabSpec setIndicator(string arg0)
{
return setIndicator((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual global::android.widget.TabHost.TabSpec setContent(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.TabSpec.staticClass, "setContent", "(I)Landroid/widget/TabHost$TabSpec;", ref global::android.widget.TabHost.TabSpec._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.widget.TabHost.TabSpec;
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual global::android.widget.TabHost.TabSpec setContent(android.widget.TabHost.TabContentFactory arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.TabSpec.staticClass, "setContent", "(Landroid/widget/TabHost$TabContentFactory;)Landroid/widget/TabHost$TabSpec;", ref global::android.widget.TabHost.TabSpec._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.widget.TabHost.TabSpec;
}
public android.widget.TabHost.TabSpec setContent(global::android.widget.TabHost.TabContentFactoryDelegate arg0)
{
return setContent((global::android.widget.TabHost.TabContentFactoryDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual global::android.widget.TabHost.TabSpec setContent(android.content.Intent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.TabSpec.staticClass, "setContent", "(Landroid/content/Intent;)Landroid/widget/TabHost$TabSpec;", ref global::android.widget.TabHost.TabSpec._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.widget.TabHost.TabSpec;
}
static TabSpec()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.TabHost.TabSpec.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/TabHost$TabSpec"));
}
}
public new global::android.app.LocalActivityManager up
{
set
{
setup(value);
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual void setup(android.app.LocalActivityManager arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "setup", "(Landroid/app/LocalActivityManager;)V", ref global::android.widget.TabHost._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual void setup()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "setup", "()V", ref global::android.widget.TabHost._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
protected override void onAttachedToWindow()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "onAttachedToWindow", "()V", ref global::android.widget.TabHost._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
protected override void onDetachedFromWindow()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "onDetachedFromWindow", "()V", ref global::android.widget.TabHost._m3);
}
private static global::MonoJavaBridge.MethodId _m4;
public override bool dispatchKeyEvent(android.view.KeyEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.TabHost.staticClass, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z", ref global::android.widget.TabHost._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public override void dispatchWindowFocusChanged(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "dispatchWindowFocusChanged", "(Z)V", ref global::android.widget.TabHost._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual void onTouchModeChanged(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "onTouchModeChanged", "(Z)V", ref global::android.widget.TabHost._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.widget.TabWidget TabWidget
{
get
{
return getTabWidget();
}
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual global::android.widget.TabWidget getTabWidget()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.staticClass, "getTabWidget", "()Landroid/widget/TabWidget;", ref global::android.widget.TabHost._m7) as android.widget.TabWidget;
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual global::android.widget.TabHost.TabSpec newTabSpec(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.staticClass, "newTabSpec", "(Ljava/lang/String;)Landroid/widget/TabHost$TabSpec;", ref global::android.widget.TabHost._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.widget.TabHost.TabSpec;
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void addTab(android.widget.TabHost.TabSpec arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "addTab", "(Landroid/widget/TabHost$TabSpec;)V", ref global::android.widget.TabHost._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual void clearAllTabs()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "clearAllTabs", "()V", ref global::android.widget.TabHost._m10);
}
public new int CurrentTab
{
get
{
return getCurrentTab();
}
set
{
setCurrentTab(value);
}
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual int getCurrentTab()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.TabHost.staticClass, "getCurrentTab", "()I", ref global::android.widget.TabHost._m11);
}
public new global::java.lang.String CurrentTabTag
{
get
{
return getCurrentTabTag();
}
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual global::java.lang.String getCurrentTabTag()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.widget.TabHost.staticClass, "getCurrentTabTag", "()Ljava/lang/String;", ref global::android.widget.TabHost._m12) as java.lang.String;
}
public new global::android.view.View CurrentTabView
{
get
{
return getCurrentTabView();
}
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual global::android.view.View getCurrentTabView()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.staticClass, "getCurrentTabView", "()Landroid/view/View;", ref global::android.widget.TabHost._m13) as android.view.View;
}
public new global::android.view.View CurrentView
{
get
{
return getCurrentView();
}
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual global::android.view.View getCurrentView()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.staticClass, "getCurrentView", "()Landroid/view/View;", ref global::android.widget.TabHost._m14) as android.view.View;
}
public new global::java.lang.String CurrentTabByTag
{
set
{
setCurrentTabByTag(value);
}
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void setCurrentTabByTag(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "setCurrentTabByTag", "(Ljava/lang/String;)V", ref global::android.widget.TabHost._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.widget.FrameLayout TabContentView
{
get
{
return getTabContentView();
}
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual global::android.widget.FrameLayout getTabContentView()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.TabHost.staticClass, "getTabContentView", "()Landroid/widget/FrameLayout;", ref global::android.widget.TabHost._m16) as android.widget.FrameLayout;
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void setCurrentTab(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "setCurrentTab", "(I)V", ref global::android.widget.TabHost._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.widget.TabHost.OnTabChangeListener OnTabChangedListener
{
set
{
setOnTabChangedListener(value);
}
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void setOnTabChangedListener(android.widget.TabHost.OnTabChangeListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.TabHost.staticClass, "setOnTabChangedListener", "(Landroid/widget/TabHost$OnTabChangeListener;)V", ref global::android.widget.TabHost._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setOnTabChangedListener(global::android.widget.TabHost.OnTabChangeListenerDelegate arg0)
{
setOnTabChangedListener((global::android.widget.TabHost.OnTabChangeListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m19;
public TabHost(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.TabHost._m19.native == global::System.IntPtr.Zero)
global::android.widget.TabHost._m19 = @__env.GetMethodIDNoThrow(global::android.widget.TabHost.staticClass, "<init>", "(Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TabHost.staticClass, global::android.widget.TabHost._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m20;
public TabHost(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.TabHost._m20.native == global::System.IntPtr.Zero)
global::android.widget.TabHost._m20 = @__env.GetMethodIDNoThrow(global::android.widget.TabHost.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TabHost.staticClass, global::android.widget.TabHost._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
static TabHost()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.TabHost.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/TabHost"));
}
}
}
| |
// GtkSharp.Generation.ClassBase.cs - Common code between object
// and interface wrappers
//
// Authors: Rachel Hestilow <hestilow@ximian.com>
// Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2002 Rachel Hestilow
// Copyright (c) 2001-2003 Mike Kestner
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the GNU General Public
// License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301
namespace GtkSharp.Generation {
using System;
using System.Collections;
using System.IO;
using System.Xml;
public abstract class ClassBase : GenBase {
protected Hashtable props = new Hashtable();
protected Hashtable fields = new Hashtable();
protected Hashtable sigs = new Hashtable();
protected Hashtable methods = new Hashtable();
protected ArrayList interfaces = new ArrayList();
protected ArrayList managed_interfaces = new ArrayList();
protected ArrayList ctors = new ArrayList();
private bool ctors_initted = false;
private Hashtable clash_map;
private bool deprecated = false;
private bool isabstract = false;
public Hashtable Methods {
get {
return methods;
}
}
public Hashtable Signals {
get {
return sigs;
}
}
public ClassBase Parent {
get {
string parent = Elem.GetAttribute("parent");
if (parent == "")
return null;
else
return SymbolTable.Table.GetClassGen(parent);
}
}
protected ClassBase (XmlElement ns, XmlElement elem) : base (ns, elem) {
if (elem.HasAttribute ("deprecated")) {
string attr = elem.GetAttribute ("deprecated");
deprecated = attr == "1" || attr == "true";
}
if (elem.HasAttribute ("abstract")) {
string attr = elem.GetAttribute ("abstract");
isabstract = attr == "1" || attr == "true";
}
foreach (XmlNode node in elem.ChildNodes) {
if (!(node is XmlElement)) continue;
XmlElement member = (XmlElement) node;
if (member.HasAttribute ("hidden"))
continue;
string name;
switch (node.Name) {
case "method":
name = member.GetAttribute("name");
while (methods.ContainsKey(name))
name += "mangled";
methods.Add (name, new Method (member, this));
break;
case "property":
name = member.GetAttribute("name");
while (props.ContainsKey(name))
name += "mangled";
props.Add (name, new Property (member, this));
break;
case "field":
name = member.GetAttribute("name");
while (fields.ContainsKey (name))
name += "mangled";
fields.Add (name, new ObjectField (member, this));
break;
case "signal":
name = member.GetAttribute("name");
while (sigs.ContainsKey(name))
name += "mangled";
sigs.Add (name, new Signal (member, this));
break;
case "implements":
ParseImplements (member);
break;
case "constructor":
ctors.Add (new Ctor (member, this));
break;
default:
break;
}
}
}
public override bool Validate ()
{
if (Parent != null && !Parent.ValidateForSubclass ())
return false;
foreach (string iface in interfaces) {
InterfaceGen igen = SymbolTable.Table[iface] as InterfaceGen;
if (igen == null) {
Console.WriteLine (QualifiedName + " implements unknown GInterface " + iface);
return false;
}
if (!igen.ValidateForSubclass ()) {
Console.WriteLine (QualifiedName + " implements invalid GInterface " + iface);
return false;
}
}
ArrayList invalids = new ArrayList ();
foreach (Property prop in props.Values) {
if (!prop.Validate ()) {
Console.WriteLine ("in type " + QualifiedName);
invalids.Add (prop);
}
}
foreach (Property prop in invalids)
props.Remove (prop.Name);
invalids.Clear ();
foreach (Signal sig in sigs.Values) {
if (!sig.Validate ()) {
Console.WriteLine ("in type " + QualifiedName);
invalids.Add (sig);
}
}
foreach (Signal sig in invalids)
sigs.Remove (sig.Name);
invalids.Clear ();
foreach (ObjectField field in fields.Values) {
if (!field.Validate ()) {
Console.WriteLine ("in type " + QualifiedName);
invalids.Add (field);
}
}
foreach (ObjectField field in invalids)
fields.Remove (field.Name);
invalids.Clear ();
foreach (Method method in methods.Values) {
if (!method.Validate ()) {
Console.WriteLine ("in type " + QualifiedName);
invalids.Add (method);
}
}
foreach (Method method in invalids)
methods.Remove (method.Name);
invalids.Clear ();
foreach (Ctor ctor in ctors) {
if (!ctor.Validate ()) {
Console.WriteLine ("in type " + QualifiedName);
invalids.Add (ctor);
}
}
foreach (Ctor ctor in invalids)
ctors.Remove (ctor);
invalids.Clear ();
return true;
}
public virtual bool ValidateForSubclass ()
{
ArrayList invalids = new ArrayList ();
foreach (Signal sig in sigs.Values) {
if (!sig.Validate ()) {
Console.WriteLine ("in type " + QualifiedName);
invalids.Add (sig);
}
}
foreach (Signal sig in invalids)
sigs.Remove (sig.Name);
invalids.Clear ();
return true;
}
public bool IsDeprecated {
get {
return deprecated;
}
}
public bool IsAbstract {
get {
return isabstract;
}
}
public abstract string AssignToName { get; }
public abstract string CallByName ();
public override string DefaultValue {
get {
return "null";
}
}
protected bool IsNodeNameHandled (string name)
{
switch (name) {
case "method":
case "property":
case "field":
case "signal":
case "implements":
case "constructor":
case "disabledefaultconstructor":
return true;
default:
return false;
}
}
public void GenProperties (GenerationInfo gen_info, ClassBase implementor)
{
if (props.Count == 0)
return;
foreach (Property prop in props.Values)
prop.Generate (gen_info, "\t\t", implementor);
}
public void GenSignals (GenerationInfo gen_info, ClassBase implementor)
{
if (sigs == null)
return;
foreach (Signal sig in sigs.Values)
sig.Generate (gen_info, implementor);
}
protected void GenFields (GenerationInfo gen_info)
{
foreach (ObjectField field in fields.Values)
field.Generate (gen_info, "\t\t");
}
private void ParseImplements (XmlElement member)
{
foreach (XmlNode node in member.ChildNodes) {
if (node.Name != "interface")
continue;
XmlElement element = (XmlElement) node;
if (element.HasAttribute ("hidden"))
continue;
if (element.HasAttribute ("cname"))
interfaces.Add (element.GetAttribute ("cname"));
else if (element.HasAttribute ("name"))
managed_interfaces.Add (element.GetAttribute ("name"));
}
}
protected bool IgnoreMethod (Method method, ClassBase implementor)
{
if (implementor != null && implementor.QualifiedName != this.QualifiedName && method.IsStatic)
return true;
string mname = method.Name;
return ((method.IsSetter || (method.IsGetter && mname.StartsWith("Get"))) &&
((props != null) && props.ContainsKey(mname.Substring(3)) ||
(fields != null) && fields.ContainsKey(mname.Substring(3))));
}
public void GenMethods (GenerationInfo gen_info, Hashtable collisions, ClassBase implementor)
{
if (methods == null)
return;
foreach (Method method in methods.Values) {
if (IgnoreMethod (method, implementor))
continue;
string oname = null, oprotection = null;
if (collisions != null && collisions.Contains (method.Name)) {
oname = method.Name;
oprotection = method.Protection;
method.Name = QualifiedName + "." + method.Name;
method.Protection = "";
}
method.Generate (gen_info, implementor);
if (oname != null) {
method.Name = oname;
method.Protection = oprotection;
}
}
}
public Method GetMethod (string name)
{
return (Method) methods[name];
}
public Property GetProperty (string name)
{
return (Property) props[name];
}
public Signal GetSignal (string name)
{
return (Signal) sigs[name];
}
public Method GetMethodRecursively (string name)
{
return GetMethodRecursively (name, false);
}
public virtual Method GetMethodRecursively (string name, bool check_self)
{
Method p = null;
if (check_self)
p = GetMethod (name);
if (p == null && Parent != null)
p = Parent.GetMethodRecursively (name, true);
if (check_self && p == null) {
foreach (string iface in interfaces) {
ClassBase igen = SymbolTable.Table.GetClassGen (iface);
if (igen == null)
continue;
p = igen.GetMethodRecursively (name, true);
if (p != null)
break;
}
}
return p;
}
public virtual Property GetPropertyRecursively (string name)
{
ClassBase klass = this;
Property p = null;
while (klass != null && p == null) {
p = (Property) klass.GetProperty (name);
klass = klass.Parent;
}
return p;
}
public Signal GetSignalRecursively (string name)
{
return GetSignalRecursively (name, false);
}
public virtual Signal GetSignalRecursively (string name, bool check_self)
{
Signal p = null;
if (check_self)
p = GetSignal (name);
if (p == null && Parent != null)
p = Parent.GetSignalRecursively (name, true);
if (check_self && p == null) {
foreach (string iface in interfaces) {
ClassBase igen = SymbolTable.Table.GetClassGen (iface);
if (igen == null)
continue;
p = igen.GetSignalRecursively (name, true);
if (p != null)
break;
}
}
return p;
}
public bool Implements (string iface)
{
if (interfaces.Contains (iface))
return true;
else if (Parent != null)
return Parent.Implements (iface);
else
return false;
}
public ArrayList Ctors { get { return ctors; } }
bool HasStaticCtor (string name)
{
if (Parent != null && Parent.HasStaticCtor (name))
return true;
foreach (Ctor ctor in Ctors)
if (ctor.StaticName == name)
return true;
return false;
}
private void InitializeCtors ()
{
if (ctors_initted)
return;
if (Parent != null)
Parent.InitializeCtors ();
ArrayList valid_ctors = new ArrayList();
clash_map = new Hashtable();
foreach (Ctor ctor in ctors) {
if (clash_map.Contains (ctor.Signature.Types)) {
Ctor clash = clash_map [ctor.Signature.Types] as Ctor;
Ctor alter = ctor.Preferred ? clash : ctor;
alter.IsStatic = true;
if (Parent != null && Parent.HasStaticCtor (alter.StaticName))
alter.Modifiers = "new ";
} else
clash_map [ctor.Signature.Types] = ctor;
valid_ctors.Add (ctor);
}
ctors = valid_ctors;
ctors_initted = true;
}
protected virtual void GenCtors (GenerationInfo gen_info)
{
InitializeCtors ();
foreach (Ctor ctor in ctors)
ctor.Generate (gen_info);
}
public virtual void Finish (StreamWriter sw, string indent)
{
}
public virtual void Prepare (StreamWriter sw, string indent)
{
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A public structure, such as a town hall or concert hall.
/// </summary>
public class CivicStructure_Core : TypeCore, IPlace
{
public CivicStructure_Core()
{
this._TypeId = 62;
this._Id = "CivicStructure";
this._Schema_Org_Url = "http://schema.org/CivicStructure";
string label = "";
GetLabel(out label, "CivicStructure", typeof(CivicStructure_Core));
this._Label = label;
this._Ancestors = new int[]{266,206};
this._SubTypes = new int[]{14,18,34,47,48,51,55,79,99,104,116,130,171,173,180,196,197,199,207,208,210,220,250,254,261,271,297};
this._SuperTypes = new int[]{206};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using System;
using Server;
using Server.Items;
using Server.Network;
using Server.Mobiles;
using System.Collections;
using Server.Gumps;
using System.Text;
using Server.Targeting;
using Server.Commands;
using Server.Commands.Generic;
namespace Server.Engines.XmlSpawner2
{
public class XmlSockets : XmlAttachment
{
// if CanSocketByDefault is set to true, then any object can be socketed using the default settings. If the XmlSocketable attachment is present, it
// will override these defaults regardless of the CanSocketByDefault setting.
// If this is set to false, then ONLY objects with the XmlSocketable attachment can be socketed.
public static bool CanSocketByDefault = false;
// The following default settings will be applied when CanSocketByDefault is true
//
// DefaultMaxSockets determines the default maximum number of sockets and item can have.
// A value of -1 means that any item can have an unlimited number of sockets.
// To set it up so that items by default cannot have sockets added to them set this to zero.
// That way, only items that have the XmlSocketLimit attachment will be allowed to be socketed. This is the same as setting CanSocketByDefault to false.
// You can also assign any other value here to set the default number of sockets allowed when no XmlSocketLimit attachment is present.
public static int DefaultMaxSockets = -1;
// DefaultSocketDifficulty is the default minimum skill required to socket.
// This can be overridden with the XmlSocketLimit attachment on specific items (100 by default)
public static double DefaultSocketDifficulty = 100.0;
public static SkillName DefaultSocketSkill = SkillName.Blacksmith;
public static Type DefaultSocketResource = typeof(ValoriteIngot);
public static int DefaultSocketResourceQuantity = 50;
// DefaultDestructionProbability is the percent chance that failure to socket will result in destruction of the the item (10% by default)
public static double DefaultDestructionProbability = 0.1;
public static int MaxAugmentDistance = 2; // if socketed object isnt in pack, then this is the max distance away from it you can be and still augment
public static int MaxSocketDistance = 2; // if socketable object isnt in pack, then this is the max distance away from it you can be and still socket
private ArrayList m_SocketOccupants;
private bool m_MustAugmentInPack = true; // determines whether the socketed object must be in the players pack in order to augment
public class SocketOccupant
{
public Type OccupantType;
public int OccupantID;
public int AugmentationVersion;
public string Description;
public int IconXOffset;
public int IconYOffset;
public int IconHue;
public bool UseGumpArt;
public SocketOccupant(Type t, int version, int id, int xoffset, int yoffset, int hue, bool usegumpart, string description)
{
OccupantType = t;
AugmentationVersion = version;
OccupantID = id;
IconXOffset = xoffset;
IconYOffset = yoffset;
IconHue = hue;
UseGumpArt = usegumpart;
Description = description;
}
public SocketOccupant(Type t, int nsockets, int version, int id)
{
OccupantType = t;
AugmentationVersion = version;
OccupantID = id;
}
}
public ArrayList SocketOccupants { get{ return m_SocketOccupants; } set { m_SocketOccupants = value;} }
[CommandProperty( AccessLevel.GameMaster )]
public bool MustAugmentInPack
{
get
{
return m_MustAugmentInPack;
}
set
{
m_MustAugmentInPack = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public int NSockets
{
get
{
if(m_SocketOccupants == null)
{
return 0;
}
else
{
return m_SocketOccupants.Count;
}
}
}
[CommandProperty( AccessLevel.GameMaster )]
public int NFree
{
get
{
if(m_SocketOccupants == null)
{
return 0;
}
else
{
int count = 0;
for(int i = 0; i < m_SocketOccupants.Count; i++)
{
if(m_SocketOccupants[i] != null) count++;
}
return m_SocketOccupants.Count - count;
}
}
}
public static new void Initialize()
{
CommandSystem.Register( "AddSocket", AccessLevel.Player, new CommandEventHandler( AddSocket_OnCommand ) );
TargetCommands.Register( new UpgradeAugmentCommand() );
TargetCommands.Register( new LimitSocketsCommand() );
}
public class LimitSocketsCommand : BaseCommand
{
int m_maxsockets;
public LimitSocketsCommand()
{
AccessLevel = AccessLevel.Administrator;
Supports = CommandSupport.Area | CommandSupport.Region | CommandSupport.Global | CommandSupport.Multi | CommandSupport.Single;
Commands = new string[]{ "LimitSockets" };
ObjectTypes = ObjectTypes.All;
Usage = "LimitSockets <maxsockets>";
Description = "Finds XmlSocket attachments with more than maxsockets, recovers their augmentations and reduces the socket number";
ListOptimized = true;
}
public override void ExecuteList( CommandEventArgs e, ArrayList list )
{
int nobjects = 0;
for ( int i = 0; i < list.Count; ++i )
{
object targetobject = list[i];
// get any socket attachments
// first see if the target has any existing sockets
XmlSockets s = XmlAttach.FindAttachment(targetobject,typeof(XmlSockets)) as XmlSockets;
bool found = true;
if(s != null && s.SocketOccupants != null && s.SocketOccupants.Count > m_maxsockets)
{
int maxsock = s.NSockets;
int nchange = 0;
while(found && nchange <= maxsock)
{
found = false;
// recover all of the augments
for(int j = 0; j < s.SocketOccupants.Count; j++)
{
SocketOccupant so =s.SocketOccupants[j] as SocketOccupant;
if(so != null )
{
nchange++;
// recover the old version of the augment
BaseSocketAugmentation augment = s.RecoverAugmentation(null, targetobject, j);
if(augment != null)
{
// give it back to the owner
if(targetobject is Item)
{
// is the parent a container?
if(((Item)targetobject).Parent is Container)
{
// add the augment to the container
((Container)((Item)targetobject).Parent).DropItem(augment);
}
else
if(((Item)targetobject).Parent is Mobile)
{
// drop it on the ground
augment.MoveToWorld(((Mobile)((Item)targetobject).Parent).Location);
}
else
if(((Item)targetobject).Parent == null)
{
// drop it on the ground
augment.MoveToWorld(((Item)targetobject).Location);
}
}
else
if(targetobject is Mobile)
{
// drop it on the ground
augment.MoveToWorld(((Mobile)targetobject).Location);
}
found = true;
break;
}
}
}
}
if(nchange > 0)
nobjects ++;
e.Mobile.SendMessage("Modified object {0}",targetobject);
// limit the sockets
s.SocketOccupants = new ArrayList(m_maxsockets);
for(int k =0;k<m_maxsockets;k++)
{
s.SocketOccupants.Add(null);
}
}
}
AddResponse( String.Format( "{0} objects adjusted.",nobjects) );
}
public override bool ValidateArgs( BaseCommandImplementor impl, CommandEventArgs e )
{
if ( e.Arguments.Length >= 1 )
{
try
{
m_maxsockets = int.Parse(e.GetString( 0 ));
}
catch { e.Mobile.SendMessage( "Usage: " + Usage ); return false; }
return true;
}
e.Mobile.SendMessage( "Usage: " + Usage );
return false;
}
}
public class UpgradeAugmentCommand : BaseCommand
{
int m_oldversion;
Type m_augmenttype;
public UpgradeAugmentCommand()
{
AccessLevel = AccessLevel.Administrator;
Supports = CommandSupport.Area | CommandSupport.Region | CommandSupport.Global | CommandSupport.Multi | CommandSupport.Single;
Commands = new string[]{ "UpgradeAugment" };
ObjectTypes = ObjectTypes.All;
Usage = "UpgradeAugment <augmenttype> <oldversion>";
Description = "Upgrades the specified augmentation on objects from the oldversion number to the newversion number.";
ListOptimized = true;
}
public override void ExecuteList( CommandEventArgs e, ArrayList list )
{
int naugments = 0;
int nobjects = 0;
int nfailures = 0;
for ( int i = 0; i < list.Count; ++i )
{
object targetobject = list[i];
// get any socket attachments
// first see if the target has any existing sockets
XmlSockets s = XmlAttach.FindAttachment(targetobject,typeof(XmlSockets)) as XmlSockets;
bool found = true;
if(s != null && s.SocketOccupants != null)
{
int maxsock = s.NSockets;
int nchange = 0;
while(found && nchange <= maxsock)
{
found = false;
// find the specified augment type
for(int j = 0; j < s.SocketOccupants.Count; j++)
{
SocketOccupant so =s.SocketOccupants[j] as SocketOccupant;
if(so != null && so.OccupantType == m_augmenttype && so.AugmentationVersion == m_oldversion)
{
// recover the old version of the augment
BaseSocketAugmentation augment = s.RecoverAugmentation(null, targetobject, j);
if(augment != null)
{
// augment with the new version
if(!Augment( null, targetobject, s, j, augment))
{
e.Mobile.SendMessage("failed to replace augment on {0}",targetobject);
nfailures++;
}
else
{
naugments++;
}
nchange++;
found = true;
break;
}
}
}
}
if(nchange > 0)
nobjects ++;
}
}
AddResponse( String.Format( "{0} {1} augmentations upgraded on {2} objects. {3} failures.", naugments, m_augmenttype.Name, nobjects, nfailures ) );
}
public override bool ValidateArgs( BaseCommandImplementor impl, CommandEventArgs e )
{
if ( e.Arguments.Length >= 2 )
{
m_augmenttype = SpawnerType.GetType(e.GetString( 0 ));
if(m_augmenttype == null)
{
e.Mobile.SendMessage( "Unknown augment type: " + e.GetString( 0 ));
return false;
}
m_oldversion = -1;
try
{
m_oldversion = int.Parse(e.GetString( 1 ));
}
catch{}
if(m_oldversion != -1)
{
return true;
}
}
e.Mobile.SendMessage( "Usage: " + Usage );
return false;
}
}
// These are the various ways in which the message attachment can be constructed.
// These can be called via the [addatt interface, via scripts, via the spawner ATTACH keyword.
// Other overloads could be defined to handle other types of arguments
// a serial constructor is REQUIRED
public XmlSockets(ASerial serial) : base(serial)
{
}
[Attachable]
public XmlSockets(int nsockets)
{
m_SocketOccupants = new ArrayList(nsockets);
for(int i =0;i<nsockets;i++)
{
m_SocketOccupants.Add(null);
}
InvalidateParentProperties();
}
[Attachable]
public XmlSockets(int nsockets, bool mustaugmentinpack)
{
m_SocketOccupants = new ArrayList(nsockets);
for(int i =0;i<nsockets;i++)
{
m_SocketOccupants.Add(null);
}
MustAugmentInPack = mustaugmentinpack;
InvalidateParentProperties();
}
public override void Serialize( GenericWriter writer )
{
base.Serialize(writer);
writer.Write( (int) 2 );
// version 1
writer.Write(m_MustAugmentInPack);
// version 0
if(m_SocketOccupants == null)
{
writer.Write((int)0);
}
else
{
writer.Write(m_SocketOccupants.Count);
for(int i = 0;i< m_SocketOccupants.Count;i++)
{
SocketOccupant s = (SocketOccupant)m_SocketOccupants[i];
if(s != null)
{
string typename = s.OccupantType.ToString();
writer.Write(typename);
if( typename != null)
{
writer.Write(s.AugmentationVersion); // added in version 2
writer.Write(s.OccupantID);
writer.Write(s.Description);
writer.Write(s.IconXOffset);
writer.Write(s.IconYOffset);
writer.Write(s.IconHue);
writer.Write(s.UseGumpArt);
}
}
else
{
writer.Write((string)null);
}
}
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
if(version > 0)
{
// version 1
m_MustAugmentInPack = reader.ReadBool();
}
// version 0
int count = reader.ReadInt();
m_SocketOccupants = new ArrayList(count);
for(int i = 0;i< count;i++)
{
Type t = null;
string typename = reader.ReadString();
if(typename != null)
{
try
{
t = Type.GetType(typename);
}
catch{}
int augmentversion = 0;
if(version > 1)
{
// version 2
augmentversion = reader.ReadInt();
}
int id = reader.ReadInt();
string desc = reader.ReadString();
int xoff = reader.ReadInt();
int yoff = reader.ReadInt();
int hue = reader.ReadInt();
bool use = reader.ReadBool();
if(t != null)
m_SocketOccupants.Add(new SocketOccupant(t, augmentversion, id, xoff, yoff, hue, use, desc));
else
m_SocketOccupants.Add(null);
}
else
{
m_SocketOccupants.Add(null);
}
}
}
public override void OnAttach()
{
base.OnAttach();
InvalidateParentProperties();
}
public override string OnIdentify(Mobile from)
{
// open up the socket gump
if(from != null)
{
from.SendGump(new SocketsGump(from, this));
}
else
{
return String.Format("{0} Sockets. {1} available.",NSockets, NFree);
}
return null;
}
// this is a utility method that will set up a target item with random socket configurations
public static void ConfigureRandom(object target, double dropchance, double chance5, double chance4, double chance3, double chance2, double chance1)
{
ConfigureRandom( target, dropchance, chance5, chance4, chance3, chance2, chance1,
DefaultSocketSkill, DefaultSocketDifficulty, DefaultSocketResource, DefaultSocketResourceQuantity);
}
public static void ConfigureRandom(object target, double dropchance, double chance5, double chance4, double chance3,
double chance2, double chance1, SkillName skillname, double minskill, Type resource, int quantity)
{
if(Utility.Random(1000) < (int)(dropchance*10))
{
// compute chance of having sockets
int level = Utility.Random(1000);
if(level < (int)(chance5*10))
XmlAttach.AttachTo(target, new XmlSockets(5));
else
if(level < (int)(chance4 + chance5)*10)
XmlAttach.AttachTo(target, new XmlSockets(4));
else
if(level < (int)(chance3 + chance4)*10)
XmlAttach.AttachTo(target, new XmlSockets(3));
else
if(level < (int)(chance2 + chance3)*10)
XmlAttach.AttachTo(target, new XmlSockets(2));
else
if(level < (int)(chance1 + chance2)*10)
XmlAttach.AttachTo(target, new XmlSockets(1));
// compute chance of being socketable
int socklevel = Utility.Random(1000);
if(socklevel < (int)(chance5*10))
XmlAttach.AttachTo(target, new XmlSocketable(5, skillname, minskill, resource, quantity));
else
if(socklevel < (int)(chance4 + chance5)*10)
XmlAttach.AttachTo(target, new XmlSocketable(4, skillname, minskill, resource, quantity));
else
if(socklevel < (int)(chance3 + chance4)*10)
XmlAttach.AttachTo(target, new XmlSocketable(3, skillname, minskill, resource, quantity));
else
if(socklevel < (int)(chance2 + chance3)*10)
XmlAttach.AttachTo(target, new XmlSocketable(2, skillname, minskill, resource, quantity));
else
XmlAttach.AttachTo(target, new XmlSocketable(1, skillname, minskill, resource, quantity));
}
}
public static void ConfigureRandom(object target, double dropchance, double chance5, double chance4, double chance3,
double chance2, double chance1, SkillName skillname, double minskill, SkillName skillname2, double minskill2, Type resource, int quantity)
{
if(Utility.Random(1000) < (int)(dropchance*10))
{
// compute chance of having sockets
int level = Utility.Random(1000);
if(level < (int)(chance5*10))
XmlAttach.AttachTo(target, new XmlSockets(5));
else
if(level < (int)(chance4 + chance5)*10)
XmlAttach.AttachTo(target, new XmlSockets(4));
else
if(level < (int)(chance3 + chance4)*10)
XmlAttach.AttachTo(target, new XmlSockets(3));
else
if(level < (int)(chance2 + chance3)*10)
XmlAttach.AttachTo(target, new XmlSockets(2));
else
if(level < (int)(chance1 + chance2)*10)
XmlAttach.AttachTo(target, new XmlSockets(1));
// compute chance of being socketable
int socklevel = Utility.Random(1000);
if(socklevel < (int)(chance5*10))
XmlAttach.AttachTo(target, new XmlSocketable(5, skillname, minskill, skillname2, minskill2, resource, quantity));
else
if(socklevel < (int)(chance4 + chance5)*10)
XmlAttach.AttachTo(target, new XmlSocketable(4, skillname, minskill, skillname2, minskill2, resource, quantity));
else
if(socklevel < (int)(chance3 + chance4)*10)
XmlAttach.AttachTo(target, new XmlSocketable(3, skillname, minskill, skillname2, minskill2, resource, quantity));
else
if(socklevel < (int)(chance2 + chance3)*10)
XmlAttach.AttachTo(target, new XmlSocketable(2, skillname, minskill, skillname2, minskill2, resource, quantity));
else
XmlAttach.AttachTo(target, new XmlSocketable(1, skillname, minskill, skillname2, minskill2, resource, quantity));
}
}
public static int ComputeSuccessChance(Mobile from, int nsockets, double difficulty, SkillName requiredSkill)
{
if(from == null) return 0;
double skill = 0;
// with a difficulty of 120
// at 120, chance of adding 1 socket is 15%, 2 sockets is 2%, 3 is 0%
//
// with a difficulty of 100
// at skill level of 100, adding 1 socket has a probability of success of 15%, 2 sockets is 0%
// at 120, chance of adding 1 socket is 55%, 2 sockets is 42%, 3 is 29%, 4 is 16% , 5 is 3%, 6 is 0%
//
// with a difficulty of 70
// at skill level of 100, adding 1 socket has a probability of success of 75%, 2 sockets is 60%, 3 sockets is 45%, etc.
// at 120, chance of adding 1 socket is 100%, 2 sockets is 100%, 3 sockets is 85%, etc.
//
try
{
skill = from.Skills[requiredSkill].Value;
}
catch{}
if((int)(skill - difficulty) < 0) return 0;
int successchance = (int)(2*(skill - difficulty) + 15 - (nsockets-1)*13);
if(successchance < 0 ) successchance = 0;
return successchance;
}
public static int ComputeSuccessChance(Mobile from, int nsockets, double difficulty, SkillName requiredSkill, double difficulty2, SkillName requiredSkill2)
{
if(from == null) return 0;
double skill = 0;
// with a difficulty of 120
// at 120, chance of adding 1 socket is 15%, 2 sockets is 2%, 3 is 0%
//
// with a difficulty of 100
// at skill level of 100, adding 1 socket has a probability of success of 15%, 2 sockets is 0%
// at 120, chance of adding 1 socket is 55%, 2 sockets is 42%, 3 is 29%, 4 is 16% , 5 is 3%, 6 is 0%
//
// with a difficulty of 70
// at skill level of 100, adding 1 socket has a probability of success of 75%, 2 sockets is 60%, 3 sockets is 45%, etc.
// at 120, chance of adding 1 socket is 100%, 2 sockets is 100%, 3 sockets is 85%, etc.
//
try
{
skill = from.Skills[requiredSkill].Value;
}
catch{}
if((int)(skill - difficulty) < 0) return 0;
int successchance = (int)(2*(skill - difficulty) + 15 - (nsockets-1)*13);
// if a second skill check has been specified then test it
if(difficulty2 > 0)
{
double skill2 = 0;
try
{
skill2 = from.Skills[requiredSkill2].Value;
}
catch{}
if((int)(skill2 - difficulty2) < 0) return 0;
successchance = (int)((skill - difficulty) + (skill2 - difficulty2) + 15 - (nsockets-1)*13);
}
if(successchance < 0 ) successchance = 0;
return successchance;
}
public static bool AddSocket(Mobile from, object target, int maxSockets, double difficulty, SkillName requiredSkill, Type resource, int quantity)
{
return AddSocket(from, target, maxSockets, difficulty, requiredSkill, 0, requiredSkill, resource, quantity);
}
public static bool AddSocket(Mobile from, object target, int maxSockets, double difficulty, SkillName requiredSkill,
double difficulty2, SkillName requiredSkill2, Type resource, int quantity)
{
if(maxSockets == 0 || target == null || from == null) return false;
// is it in the pack
if ( target is Item && !((Item)target).IsChildOf( from.Backpack ))
{
from.SendMessage("Must be in your backpack.");
return false;
}
else
if ( target is BaseCreature && ((BaseCreature)target).ControlMaster != from)
{
from.SendMessage("Must be under your control.");
return false;
}
// check the target range
if ( target is Mobile && !Utility.InRange( ((Mobile)target).Location, from.Location, MaxSocketDistance ))
{
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that.
return false;
}
int nSockets = 0;
// first see if the target has any existing sockets
ArrayList plist = XmlAttach.FindAttachments(target,typeof(XmlSockets));
XmlSockets s = null;
if(plist != null && plist.Count > 0)
{
s = plist[0] as XmlSockets;
// find out how many sockets it has
nSockets = s.NSockets;
}
// already full, no more sockets allowed
if(nSockets >= maxSockets && maxSockets >= 0)
{
from.SendMessage("This cannot be socketed any further.");
return false;
}
// try to add a socket to the target
// determine the difficulty based upon the required skill and the current number of sockets
int successchance = ComputeSuccessChance( from, nSockets, difficulty, requiredSkill, difficulty2, requiredSkill2);
if(successchance <= 0)
{
from.SendMessage("You have no chance of socketing this.");
return false;
}
// consume the resources
if(from.Backpack != null && resource != null && quantity > 0)
{
if(!from.Backpack.ConsumeTotal( resource, quantity, true))
{
from.SendMessage("Socketing this requires {0} {1}",quantity, resource.Name);
return false;
}
}
from.PlaySound( 0x2A ); // play anvil sound
if(Utility.Random(1000) < successchance*10)
{
from.SendMessage("You have successfully added a socket the target!");
if(s != null)
{
// add an empty socket
s.SocketOccupants.Add(null );
}
else
{
// add an xmlsockets attachment with the new socket
s = new XmlSockets(1);
XmlAttach.AttachTo(target, s);
}
if(s != null)
s.InvalidateParentProperties();
from.SendGump(new SocketsGump(from, s));
}
else
{
from.SendMessage("Your attempt to add a socket to the target was unsuccessful.");
// if it fails then there is also a chance of destroying it
if(DefaultDestructionProbability > 0 && Utility.RandomDouble() < DefaultDestructionProbability)
{
from.SendMessage("You destroy the target while attempting to add a socket to it.");
if(target is Item)
{
((Item)target).Delete();
}
else
if(target is BaseCreature)
{
((BaseCreature)target).Delete();
}
from.CloseGump(typeof(SocketsGump));
return false;
}
}
return true;
}
public static bool Augment( Mobile from, object parent, XmlSockets sock, int socketnum, IXmlSocketAugmentation a)
{
if(parent == null || a == null || sock == null || socketnum < 0)
{
if(a != null && from == null) a.Delete();
return false;
}
if(sock.SocketOccupants != null && sock.NFree >= a.SocketsRequired && sock.SocketOccupants.Count > socketnum && a.OnAugment(from, parent))
{
SocketOccupant occ = new SocketOccupant(a.GetType(), a.Version, a.Icon, a.IconXOffset, a.IconYOffset, a.IconHue, a.UseGumpArt,
String.Format("{0}\n{1}\n{2} Socket(s)",a.Name,a.OnIdentify(null),a.SocketsRequired));
int remaining = a.SocketsRequired;
// make sure the requested socket is unoccupied
if(sock.SocketOccupants[socketnum] == null)
{
sock.SocketOccupants[socketnum] = occ;
remaining--;
}
// if this augmentation requires more than 1 socket, then fill the rest
if(remaining > 0)
{
// find a free socket
for(int i = 0;i<sock.SocketOccupants.Count;i++)
{
if(sock.SocketOccupants[i] == null)
{
sock.SocketOccupants[i] = occ;
remaining--;
}
// filled all of the required sockets
if(remaining == 0) break;
}
}
// destroy after augmenting if needed
if(a.DestroyAfterUse || from == null)
a.Delete();
return true;
}
else
{
if(from == null) a.Delete();
return false;
}
}
public BaseSocketAugmentation RecoverAugmentation(Mobile from, object o, int index)
{
if(SocketOccupants == null || SocketOccupants.Count < index) return null;
BaseSocketAugmentation augment = null;
SocketOccupant s = SocketOccupants[index] as SocketOccupant;
if(s == null) return null;
Type t = s.OccupantType;
if(t != null)
{
try
{
augment = Activator.CreateInstance( t ) as BaseSocketAugmentation;
}
catch{}
}
if(augment != null)
{
if(augment.CanRecover(from, o, s.AugmentationVersion) && augment.RecoverableSockets(s.AugmentationVersion) > 0)
{
// recover the augment
augment.OnRecover(from, o, s.AugmentationVersion);
// clear all of the sockets that it occupied
int count = augment.RecoverableSockets(s.AugmentationVersion);
for(int i = 0; i < SocketOccupants.Count; i++)
{
if(SocketOccupants[i] != null && ((SocketOccupant)SocketOccupants[i]).OccupantType == t && ((SocketOccupant)SocketOccupants[i]).AugmentationVersion == s.AugmentationVersion)
{
SocketOccupants[i] = null;
count--;
if(count <= 0) break;
}
}
}
else
{
augment.Delete();
return null;
}
}
return augment;
}
public BaseSocketAugmentation RecoverRandomAugmentation(Mobile from, object o)
{
int nfilled = NSockets - NFree;
if(nfilled > 0)
{
// pick a random augmentation from a filled socket
int rindex = Utility.Random(nfilled);
int count = 0;
for(int i = 0; i < SocketOccupants.Count; i++)
{
if(SocketOccupants[i] != null)
{
if(count == rindex)
{
// reconstruct the augment
BaseSocketAugmentation augment = RecoverAugmentation(from, o, i);
return augment;
}
count++;
}
}
}
return null;
}
private class AddAugmentationToSocket : Target
{
private object m_parent;
private XmlSockets m_s;
private int m_socketnum;
public AddAugmentationToSocket(object parent, XmlSockets s, int socketnum) : base ( 30, false, TargetFlags.None )
{
m_parent = parent;
m_socketnum = socketnum;
m_s = s;
}
protected override void OnTarget( Mobile from, object targeted )
{
if(from == null || targeted == null) return;
// is this a valid augmentation
if(targeted is IXmlSocketAugmentation)
{
IXmlSocketAugmentation a = targeted as IXmlSocketAugmentation;
// check the augment
if ( a is Item && !((Item)a).IsChildOf( from.Backpack ))
{
from.SendMessage("Augmentation must be in your backpack.");
return;
}
else
if ( a is BaseCreature && ((BaseCreature)a).ControlMaster != from)
{
from.SendMessage("Augmentation must be under your control.");
return;
}
// check the parent
if ( m_parent is Item && !((Item)m_parent).IsChildOf( from.Backpack ) && m_s != null && m_s.MustAugmentInPack)
{
from.SendMessage("Socketable item be in your backpack.");
return;
}
else
if ( m_parent is BaseCreature && ((BaseCreature)m_parent).ControlMaster != from)
{
from.SendMessage("Socketable creature must be under your control.");
return;
}
// check the parent range
if ( ( m_parent is Item && ((Item)m_parent).Parent == null) || m_parent is Mobile)
{
Point3D loc = from.Location;
if(m_parent is Item)
{
loc = ((Item)m_parent).Location;
}
else
if(m_parent is Mobile)
{
loc = ((Mobile)m_parent).Location;
}
if ( !Utility.InRange( loc, from.Location, MaxAugmentDistance ) )
{
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that.
return;
}
}
if (a.CanAugment(from, m_parent, m_socketnum))
{
// check for sufficient available sockets
if( m_s == null || m_s.NFree < a.SocketsRequired)
{
from.SendMessage("Not enough available sockets for that augmentation.");
return;
}
if(!a.ConsumeOnAugment(from))
{
from.SendMessage("You are lacking the resources needed to use that augmentation.");
return;
}
from.PlaySound( 0x2A ); // play anvil sound
// add the augmentation to the socket
if(Augment(from, m_parent, m_s, m_socketnum, a))
{
// refresh the gump
from.CloseGump(typeof(SocketsGump));
from.SendGump(new SocketsGump(from, m_s));
from.SendMessage("You successfully augment the target.");
m_s.InvalidateParentProperties();
}
else
{
from.SendMessage("The augmentation fails.");
}
}
else
{
from.SendMessage("That cannot be used in this socket.");
}
}
else
{
from.SendMessage("That is not a valid augmentation.");
}
}
}
public class AddSocketToTarget : Target
{
//private CommandEventArgs m_e;
private int m_extrasockets;
public AddSocketToTarget( ) : this ( 0 )
{
}
public AddSocketToTarget( int extrasockets) : base ( 30, false, TargetFlags.None )
{
m_extrasockets = extrasockets;
}
protected override void OnTarget( Mobile from, object targeted )
{
if(from == null || targeted == null) return;
int maxSockets = DefaultMaxSockets;
double difficulty = DefaultSocketDifficulty;
SkillName skillname = DefaultSocketSkill;
double difficulty2 = DefaultSocketDifficulty;
SkillName skillname2 = DefaultSocketSkill;
Type resource = DefaultSocketResource;
int quantity = DefaultSocketResourceQuantity;
// see if this has an XmlSocketable attachment that might impose socketing restrictions
ArrayList plist = XmlAttach.FindAttachments(targeted,typeof(XmlSocketable));
if(plist != null && plist.Count > 0)
{
XmlSocketable s = plist[0] as XmlSocketable;
// get the socketing restrictions
maxSockets = s.MaxSockets;
// and any difficulty restrictions
difficulty = s.MinSkillLevel;
skillname = s.RequiredSkill;
difficulty2 = s.MinSkillLevel2;
skillname2 = s.RequiredSkill2;
resource = s.RequiredResource;
quantity = s.ResourceQuantity;
}
else
if(!CanSocketByDefault && m_extrasockets <= 0)
{
from.SendMessage("This cannot be socketed.");
return;
}
if(maxSockets < 0 && m_extrasockets > 0)
{
maxSockets = 0;
}
// override maximum socket restrictions
maxSockets += m_extrasockets;
AddSocket(from, targeted, maxSockets, difficulty, skillname, difficulty2, skillname2, resource, quantity);
}
}
public class RecoverAugmentationFromTarget : Target
{
//private CommandEventArgs m_e;
public RecoverAugmentationFromTarget( /*CommandEventArgs e*/) : base ( 30, false, TargetFlags.None )
{
//m_e = e;
}
protected override void OnTarget( Mobile from, object targeted )
{
if(from == null || targeted == null) return;
// see if the target has an XmlSockets attachment
XmlSockets s = XmlAttach.FindAttachment(targeted,typeof(XmlSockets)) as XmlSockets;
if(s == null)
{
from.SendMessage("This is not socketed.");
return;
}
BaseSocketAugmentation augment = s.RecoverRandomAugmentation(from, targeted);
if(augment != null)
{
from.SendMessage("Recovered a {0} augmentation.", augment.Name);
from.AddToBackpack(augment);
// update the sockets gump
s.OnIdentify(from);
}
else
{
from.SendMessage("Failed to recover augmentation.");
}
}
}
[Usage( "AddSocket" )]
[Description( "Attempts to add a socket to the targeted item." )]
public static void AddSocket_OnCommand( CommandEventArgs e )
{
e.Mobile.Target = new AddSocketToTarget();
}
private class SocketsGump : Gump
{
private XmlSockets m_attachment;
private const int vertspacing = 65;
public SocketsGump( Mobile from, XmlSockets a) : base( 0,0)
{
if(a == null)
{
return;
}
if(from != null)
from.CloseGump(typeof( SocketsGump));
m_attachment = a;
int socketcount = 0;
if(a.SocketOccupants != null)
{
socketcount = a.SocketOccupants.Count;
}
// prepare the page
AddPage( 0 );
AddBackground( 0, 0, 185, 137 + socketcount*vertspacing, 5054 );
AddImage( 2 , 2 , 0x28d4); // garg top center
AddImageTiled( 2 , 52 , 30, 50 + socketcount*vertspacing, 0x28e0); // left edge
AddImageTiled( 151 , 52 , 30, 50 + socketcount*vertspacing, 0x28e0); // right edge
AddImageTiled( 40 , 104 + socketcount*vertspacing , 121, 30, 0x28de); // bottom edge
AddImage( 143 , 84 + socketcount*vertspacing , 0x28d2); // garg bottom right
AddImage( 2 , 84 + socketcount*vertspacing , 0x28d2); // garg bottom left
string label = null;
if(m_attachment.AttachedTo is Item)
{
Item item = m_attachment.AttachedTo as Item;
label = item.Name;
if(item.Name == null)
{
label = item.ItemData.Name;
}
}
else
if(m_attachment.AttachedTo is Mobile)
{
Mobile m = m_attachment.AttachedTo as Mobile;
label = m.Name;
}
int xadjust = 50;
if(label != null)
xadjust -= label.Length*5/2;
if(xadjust < 0) xadjust = 0;
AddLabelCropped( 34 + xadjust, 60, 110-xadjust, 20, 55, label );
// go through the list of sockets and add buttons for them
int xoffset = 62;
int y = 98;
for(int i = 0;i<socketcount;i++)
{
SocketOccupant s = (SocketOccupant)m_attachment.SocketOccupants[i];
// add the socket icon
if(s != null && s.OccupantID != 0)
{
// add the describe socket button
AddButton( xoffset, y, 0x00ea, 0x00ea, 2000+i, GumpButtonType.Reply, 0 );
// put in the filled socket background
AddImageTiled( xoffset , y+1 , 57, 59, 0x1404); // dark
AddImageTiled( xoffset+2 , y , 56, 58, 0xbbc); // light
AddImageTiled( xoffset+2, y+2 , 54, 56, 0x13f0); // neutral
if(s.UseGumpArt)
{
AddImage( xoffset + s.IconXOffset, y + s.IconYOffset, s.OccupantID, s.IconHue );
}
else
{
AddItem( xoffset + s.IconXOffset, y + s.IconYOffset, s.OccupantID, s.IconHue );
}
}
else
{
// display the empty socket button
AddButton( xoffset+2, y, 0x00ea, 0x00ea, 1000+i, GumpButtonType.Reply, 0 );
}
y += vertspacing;
}
}
public override void OnResponse( NetState state, RelayInfo info )
{
if(m_attachment == null || state == null || state.Mobile == null || info == null || m_attachment.SocketOccupants == null) return;
// make sure the parent of the socket is still valid
if(m_attachment.AttachedTo == null || (m_attachment.AttachedTo is Item && ((Item)m_attachment.AttachedTo).Deleted) ||
(m_attachment.AttachedTo is Mobile && ((Mobile)m_attachment.AttachedTo).Deleted))
{
return;
}
// go through all of the possible specials and find the matching button
for(int i = 0;i<m_attachment.SocketOccupants.Count;i++)
{
SocketOccupant s = (SocketOccupant)m_attachment.SocketOccupants[i];
if(info.ButtonID == i + 1000)
{
// bring up the targeting to fill the socket
state.Mobile.Target = new AddAugmentationToSocket(m_attachment.AttachedTo, m_attachment, i);
state.Mobile.SendGump(new SocketsGump(state.Mobile, m_attachment));
break;
}
if(info.ButtonID == i + 2000)
{
if(s != null)
{
// bring up the info on the socket
// check the augmentation to see if it can be recovered. Optimize this later with table look up of prototype instances
bool canrecover = false;
BaseSocketAugmentation augment = null;
Type t = s.OccupantType;
if(t != null)
{
try
{
augment = Activator.CreateInstance( t ) as BaseSocketAugmentation;
}
catch{}
}
if(augment != null)
{
canrecover = augment.CanRecover(state.Mobile, m_attachment.AttachedTo, s.AugmentationVersion);
augment.Delete();
}
state.Mobile.SendMessage(s.Description + (canrecover ? "\nCan be recovered" : ""));
}
state.Mobile.SendGump(new SocketsGump(state.Mobile, m_attachment));
break;
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using ApprovalTests;
using ApprovalTests.Reporters;
using ApprovalUtilities.Utilities;
using ConsoleToolkit.ConsoleIO;
using ConsoleToolkit.ConsoleIO.Internal;
using ConsoleToolkit.Testing;
using ConsoleToolkitTests.TestingUtilities;
using NUnit.Framework;
namespace ConsoleToolkitTests.ConsoleIO.Internal
{
[TestFixture]
[UseReporter(typeof(CustomReporter))]
public class TestReadValue
{
private ConsoleInterfaceForTesting _interface;
private ConsoleAdapter _adapter;
private static readonly PropertyInfo StringProp = typeof(TestReadInputItem).GetProperty("StringVal");
private static readonly PropertyInfo IntProp = typeof(TestReadInputItem).GetProperty("IntVal");
public string StringVal { get; set; }
public int IntVal { get; set; }
[SetUp]
public void SetUp()
{
_interface = new ConsoleInterfaceForTesting();
_adapter = new ConsoleAdapter(_interface);
StringVal = null;
IntVal = 0;
}
private TextReader MakeStream(IEnumerable<string> input)
{
return new StringReader(input.JoinWith(Environment.NewLine));
}
[Test]
public void StringCanBeRead()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "text" }));
var item = new InputItem
{
Name = "StringVal",
Property = StringProp,
Type = typeof(string)
};
//Act
object value;
ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Assert.That(value, Is.EqualTo("text"));
}
[Test]
public void ValidReadReturnsTrue()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "text" }));
var item = new InputItem
{
Name = "StringVal",
Property = StringProp,
Type = typeof(string)
};
//Act
object value;
var result = ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Assert.That(result, Is.True);
}
[Test]
public void InvalidReadReturnsFalse()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "text" }));
_interface.InputIsRedirected = true;
var item = new InputItem
{
Name = "IntVal",
Property = IntProp,
Type = typeof(int)
};
//Act
object value;
var result = ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Assert.That(result, Is.False);
}
[Test]
public void TextIsConvertedToRequiredType()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "45" }));
var item = new InputItem
{
Name = "IntVal",
Property = IntProp,
Type = typeof(int)
};
//Act
object value;
ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Assert.That(value, Is.EqualTo(45));
}
[Test]
public void ErrorIsDisplayedWhenInputIsInvalid()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "text" }));
_interface.InputIsRedirected = true;
var item = new InputItem
{
Name = "IntVal",
Property = IntProp,
Type = typeof(int),
ReadInfo = Read.Int().Prompt("prompt")
};
//Act
object value;
ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Approvals.Verify(_interface.GetBuffer());
}
[Test]
public void OptionIsSelected()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "C" }));
var item = new InputItem
{
Name = "IntVal",
Property = IntProp,
Type = typeof(int),
ReadInfo = Read.Int().Prompt("prompt")
.Option(100, "B", "First")
.Option(200, "C", "Second")
.Option(300, "D", "Third")
};
//Act
object value;
ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Assert.That(value, Is.EqualTo(200));
}
[Test]
public void OptionInputIsNotCaseSensitive()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "c" }));
var item = new InputItem
{
Name = "IntVal",
Property = IntProp,
Type = typeof(int),
ReadInfo = Read.Int().Prompt("prompt")
.Option(100, "B", "First")
.Option(200, "C", "Second")
.Option(300, "D", "Third")
};
//Act
object value;
ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Assert.That(value, Is.EqualTo(200));
}
[Test]
public void OptionsCanBeDifferentiatedByCase()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "a", "A" }));
var item = new InputItem
{
Name = "IntVal",
Property = IntProp,
Type = typeof(int),
ReadInfo = Read.Int().Prompt("prompt")
.Option(100, "a", "First")
.Option(200, "A", "Second")
};
//Act
object value1, value2;
ReadValue.UsingReadLine(item, _interface, _adapter, out value1);
ReadValue.UsingReadLine(item, _interface, _adapter, out value2);
//Assert
Assert.That(string.Format("Value1 = {0}, Value2 = {1}", value1, value2), Is.EqualTo("Value1 = 100, Value2 = 200"));
}
[Test]
public void ValidationErrorMessageIsDisplayed()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "10" }));
var item = new InputItem
{
Name = "IntVal",
Property = IntProp,
Type = typeof(int),
ReadInfo = Read.Int().Validate(i => i > 10, "Value must be greater than 10")
};
//Act
object value;
ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Approvals.Verify(_interface.GetBuffer());
}
[Test]
public void ValidationErrorCausesFalseReturn()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "10" }));
var item = new InputItem
{
Name = "IntVal",
Property = IntProp,
Type = typeof(int),
ReadInfo = Read.Int().Validate(i => i > 10, "Value must be greater than 10")
};
//Act
object value;
var result = ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Assert.That(result, Is.False);
}
[Test]
public void ValidationPassReturnsTrue()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "11" }));
var item = new InputItem
{
Name = "IntVal",
Property = IntProp,
Type = typeof(int),
ReadInfo = Read.Int().Validate(i => i > 10, "Value must be greater than 10")
};
//Act
object value;
var result = ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Assert.That(result, Is.True);
}
[Test]
public void ValidationPassSetsValue()
{
//Arrange
_interface.SetInputStream(MakeStream(new[] { "11" }));
var item = new InputItem
{
Name = "IntVal",
Property = IntProp,
Type = typeof(int),
ReadInfo = Read.Int().Validate(i => i > 10, "Value must be greater than 10")
};
//Act
object value;
ReadValue.UsingReadLine(item, _interface, _adapter, out value);
//Assert
Assert.That(value, Is.EqualTo(11));
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculus.com/licenses/LICENSE-3.3
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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 UnityEngine;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
/// <summary>
/// Miscellaneous extension methods that any script can use.
/// </summary>
public static class OVRExtensions
{
/// <summary>
/// Converts the given world-space transform to an OVRPose in tracking space.
/// </summary>
public static OVRPose ToTrackingSpacePose(this Transform transform)
{
OVRPose headPose;
headPose.position = UnityEngine.VR.InputTracking.GetLocalPosition(UnityEngine.VR.VRNode.Head);
headPose.orientation = UnityEngine.VR.InputTracking.GetLocalRotation(UnityEngine.VR.VRNode.Head);
var ret = headPose * transform.ToHeadSpacePose();
return ret;
}
/// <summary>
/// Converts the given world-space transform to an OVRPose in head space.
/// </summary>
public static OVRPose ToHeadSpacePose(this Transform transform)
{
return Camera.current.transform.ToOVRPose().Inverse() * transform.ToOVRPose();
}
internal static OVRPose ToOVRPose(this Transform t, bool isLocal = false)
{
OVRPose pose;
pose.orientation = (isLocal) ? t.localRotation : t.rotation;
pose.position = (isLocal) ? t.localPosition : t.position;
return pose;
}
internal static void FromOVRPose(this Transform t, OVRPose pose, bool isLocal = false)
{
if (isLocal)
{
t.localRotation = pose.orientation;
t.localPosition = pose.position;
}
else
{
t.rotation = pose.orientation;
t.position = pose.position;
}
}
internal static OVRPose ToOVRPose(this OVRPlugin.Posef p)
{
return new OVRPose()
{
position = new Vector3(p.Position.x, p.Position.y, -p.Position.z),
orientation = new Quaternion(-p.Orientation.x, -p.Orientation.y, p.Orientation.z, p.Orientation.w)
};
}
internal static OVRTracker.Frustum ToFrustum(this OVRPlugin.Frustumf f)
{
return new OVRTracker.Frustum()
{
nearZ = f.zNear,
farZ = f.zFar,
fov = new Vector2()
{
x = Mathf.Rad2Deg * f.fovX,
y = Mathf.Rad2Deg * f.fovY
}
};
}
internal static Color FromColorf(this OVRPlugin.Colorf c)
{
return new Color() { r = c.r, g = c.g, b = c.b, a = c.a };
}
internal static OVRPlugin.Colorf ToColorf(this Color c)
{
return new OVRPlugin.Colorf() { r = c.r, g = c.g, b = c.b, a = c.a };
}
internal static Vector3 FromVector3f(this OVRPlugin.Vector3f v)
{
return new Vector3() { x = v.x, y = v.y, z = v.z };
}
internal static Vector3 FromFlippedZVector3f(this OVRPlugin.Vector3f v)
{
return new Vector3() { x = v.x, y = v.y, z = -v.z };
}
internal static OVRPlugin.Vector3f ToVector3f(this Vector3 v)
{
return new OVRPlugin.Vector3f() { x = v.x, y = v.y, z = v.z };
}
internal static OVRPlugin.Vector3f ToFlippedZVector3f(this Vector3 v)
{
return new OVRPlugin.Vector3f() { x = v.x, y = v.y, z = -v.z };
}
internal static Quaternion FromQuatf(this OVRPlugin.Quatf q)
{
return new Quaternion() { x = q.x, y = q.y, z = q.z, w = q.w };
}
internal static OVRPlugin.Quatf ToQuatf(this Quaternion q)
{
return new OVRPlugin.Quatf() { x = q.x, y = q.y, z = q.z, w = q.w };
}
}
/// <summary>
/// An affine transformation built from a Unity position and orientation.
/// </summary>
[System.Serializable]
public struct OVRPose
{
/// <summary>
/// A pose with no translation or rotation.
/// </summary>
public static OVRPose identity
{
get {
return new OVRPose()
{
position = Vector3.zero,
orientation = Quaternion.identity
};
}
}
public override bool Equals(System.Object obj)
{
return obj is OVRPose && this == (OVRPose)obj;
}
public override int GetHashCode()
{
return position.GetHashCode() ^ orientation.GetHashCode();
}
public static bool operator ==(OVRPose x, OVRPose y)
{
return x.position == y.position && x.orientation == y.orientation;
}
public static bool operator !=(OVRPose x, OVRPose y)
{
return !(x == y);
}
/// <summary>
/// The position.
/// </summary>
public Vector3 position;
/// <summary>
/// The orientation.
/// </summary>
public Quaternion orientation;
/// <summary>
/// Multiplies two poses.
/// </summary>
public static OVRPose operator*(OVRPose lhs, OVRPose rhs)
{
var ret = new OVRPose();
ret.position = lhs.position + lhs.orientation * rhs.position;
ret.orientation = lhs.orientation * rhs.orientation;
return ret;
}
/// <summary>
/// Computes the inverse of the given pose.
/// </summary>
public OVRPose Inverse()
{
OVRPose ret;
ret.orientation = Quaternion.Inverse(orientation);
ret.position = ret.orientation * -position;
return ret;
}
/// <summary>
/// Converts the pose from left- to right-handed or vice-versa.
/// </summary>
internal OVRPose flipZ()
{
var ret = this;
ret.position.z = -ret.position.z;
ret.orientation.z = -ret.orientation.z;
ret.orientation.w = -ret.orientation.w;
return ret;
}
internal OVRPlugin.Posef ToPosef()
{
return new OVRPlugin.Posef()
{
Position = position.ToVector3f(),
Orientation = orientation.ToQuatf()
};
}
}
/// <summary>
/// Encapsulates an 8-byte-aligned of unmanaged memory.
/// </summary>
public class OVRNativeBuffer : IDisposable
{
private bool disposed = false;
private int m_numBytes = 0;
private IntPtr m_ptr = IntPtr.Zero;
/// <summary>
/// Creates a buffer of the specified size.
/// </summary>
public OVRNativeBuffer(int numBytes)
{
Reallocate(numBytes);
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the <see cref="OVRNativeBuffer"/> is
/// reclaimed by garbage collection.
/// </summary>
~OVRNativeBuffer()
{
Dispose(false);
}
/// <summary>
/// Reallocates the buffer with the specified new size.
/// </summary>
public void Reset(int numBytes)
{
Reallocate(numBytes);
}
/// <summary>
/// The current number of bytes in the buffer.
/// </summary>
public int GetCapacity()
{
return m_numBytes;
}
/// <summary>
/// A pointer to the unmanaged memory in the buffer, starting at the given offset in bytes.
/// </summary>
public IntPtr GetPointer(int byteOffset = 0)
{
if (byteOffset < 0 || byteOffset >= m_numBytes)
return IntPtr.Zero;
return (byteOffset == 0) ? m_ptr : new IntPtr(m_ptr.ToInt64() + byteOffset);
}
/// <summary>
/// Releases all resource used by the <see cref="OVRNativeBuffer"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="OVRNativeBuffer"/>. The <see cref="Dispose"/>
/// method leaves the <see cref="OVRNativeBuffer"/> in an unusable state. After calling <see cref="Dispose"/>, you must
/// release all references to the <see cref="OVRNativeBuffer"/> so the garbage collector can reclaim the memory that
/// the <see cref="OVRNativeBuffer"/> was occupying.</remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// dispose managed resources
}
// dispose unmanaged resources
Release();
disposed = true;
}
private void Reallocate(int numBytes)
{
Release();
if (numBytes > 0)
{
m_ptr = Marshal.AllocHGlobal(numBytes);
m_numBytes = numBytes;
}
else
{
m_ptr = IntPtr.Zero;
m_numBytes = 0;
}
}
private void Release()
{
if (m_ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(m_ptr);
m_ptr = IntPtr.Zero;
m_numBytes = 0;
}
}
}
| |
// Copyright 2022 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 gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V10.Services
{
/// <summary>Settings for <see cref="AssetServiceClient"/> instances.</summary>
public sealed partial class AssetServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AssetServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AssetServiceSettings"/>.</returns>
public static AssetServiceSettings GetDefault() => new AssetServiceSettings();
/// <summary>Constructs a new <see cref="AssetServiceSettings"/> object with default settings.</summary>
public AssetServiceSettings()
{
}
private AssetServiceSettings(AssetServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateAssetsSettings = existing.MutateAssetsSettings;
OnCopy(existing);
}
partial void OnCopy(AssetServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AssetServiceClient.MutateAssets</c> and <c>AssetServiceClient.MutateAssetsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateAssetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AssetServiceSettings"/> object.</returns>
public AssetServiceSettings Clone() => new AssetServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AssetServiceClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
internal sealed partial class AssetServiceClientBuilder : gaxgrpc::ClientBuilderBase<AssetServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AssetServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AssetServiceClientBuilder()
{
UseJwtAccessWithScopes = AssetServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AssetServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AssetServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AssetServiceClient Build()
{
AssetServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AssetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AssetServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AssetServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AssetServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AssetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AssetServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AssetServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AssetServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AssetServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AssetService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage assets. Asset types can be created with AssetService are
/// YoutubeVideoAsset, MediaBundleAsset and ImageAsset. TextAsset should be
/// created with Ad inline.
/// </remarks>
public abstract partial class AssetServiceClient
{
/// <summary>
/// The default endpoint for the AssetService service, which is a host of "googleads.googleapis.com" and a port
/// of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AssetService scopes.</summary>
/// <remarks>
/// The default AssetService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AssetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AssetServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AssetServiceClient"/>.</returns>
public static stt::Task<AssetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AssetServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AssetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AssetServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AssetServiceClient"/>.</returns>
public static AssetServiceClient Create() => new AssetServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AssetServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AssetServiceSettings"/>.</param>
/// <returns>The created <see cref="AssetServiceClient"/>.</returns>
internal static AssetServiceClient Create(grpccore::CallInvoker callInvoker, AssetServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AssetService.AssetServiceClient grpcClient = new AssetService.AssetServiceClient(callInvoker);
return new AssetServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AssetService client</summary>
public virtual AssetService.AssetServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates assets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AssetError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MediaUploadError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// [YoutubeVideoRegistrationError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAssetsResponse MutateAssets(MutateAssetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates assets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AssetError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MediaUploadError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// [YoutubeVideoRegistrationError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAssetsResponse> MutateAssetsAsync(MutateAssetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates assets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AssetError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MediaUploadError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// [YoutubeVideoRegistrationError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAssetsResponse> MutateAssetsAsync(MutateAssetsRequest request, st::CancellationToken cancellationToken) =>
MutateAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates assets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AssetError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MediaUploadError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// [YoutubeVideoRegistrationError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual assets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAssetsResponse MutateAssets(string customerId, scg::IEnumerable<AssetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAssets(new MutateAssetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates assets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AssetError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MediaUploadError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// [YoutubeVideoRegistrationError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual assets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAssetsResponse> MutateAssetsAsync(string customerId, scg::IEnumerable<AssetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAssetsAsync(new MutateAssetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates assets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AssetError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MediaUploadError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// [YoutubeVideoRegistrationError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual assets.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAssetsResponse> MutateAssetsAsync(string customerId, scg::IEnumerable<AssetOperation> operations, st::CancellationToken cancellationToken) =>
MutateAssetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AssetService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage assets. Asset types can be created with AssetService are
/// YoutubeVideoAsset, MediaBundleAsset and ImageAsset. TextAsset should be
/// created with Ad inline.
/// </remarks>
public sealed partial class AssetServiceClientImpl : AssetServiceClient
{
private readonly gaxgrpc::ApiCall<MutateAssetsRequest, MutateAssetsResponse> _callMutateAssets;
/// <summary>
/// Constructs a client wrapper for the AssetService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AssetServiceSettings"/> used within this client.</param>
public AssetServiceClientImpl(AssetService.AssetServiceClient grpcClient, AssetServiceSettings settings)
{
GrpcClient = grpcClient;
AssetServiceSettings effectiveSettings = settings ?? AssetServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateAssets = clientHelper.BuildApiCall<MutateAssetsRequest, MutateAssetsResponse>(grpcClient.MutateAssetsAsync, grpcClient.MutateAssets, effectiveSettings.MutateAssetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAssets);
Modify_MutateAssetsApiCall(ref _callMutateAssets);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_MutateAssetsApiCall(ref gaxgrpc::ApiCall<MutateAssetsRequest, MutateAssetsResponse> call);
partial void OnConstruction(AssetService.AssetServiceClient grpcClient, AssetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AssetService client</summary>
public override AssetService.AssetServiceClient GrpcClient { get; }
partial void Modify_MutateAssetsRequest(ref MutateAssetsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates assets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AssetError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MediaUploadError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// [YoutubeVideoRegistrationError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateAssetsResponse MutateAssets(MutateAssetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAssetsRequest(ref request, ref callSettings);
return _callMutateAssets.Sync(request, callSettings);
}
/// <summary>
/// Creates assets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AssetError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MediaUploadError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// [YoutubeVideoRegistrationError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateAssetsResponse> MutateAssetsAsync(MutateAssetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAssetsRequest(ref request, ref callSettings);
return _callMutateAssets.Async(request, callSettings);
}
}
}
| |
// 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 AddUInt16()
{
var test = new SimpleBinaryOpTest__AddUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// 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();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// 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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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__AddUInt16
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[ElementCount];
private static UInt16[] _data2 = new UInt16[ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private SimpleBinaryOpTest__DataTable<UInt16> _dataTable;
static SimpleBinaryOpTest__AddUInt16()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AddUInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt16>(_data1, _data2, new UInt16[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Add(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Add(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Add(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddUInt16();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt16> left, Vector256<UInt16> right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[ElementCount];
UInt16[] inArray2 = new UInt16[ElementCount];
UInt16[] outArray = new UInt16[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[ElementCount];
UInt16[] inArray2 = new UInt16[ElementCount];
UInt16[] outArray = new UInt16[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
if ((ushort)(left[0] + right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((ushort)(left[i] + right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Add)}<UInt16>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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.Text.Utf8;
namespace System.Text.JsonLab.Tests
{
public class TestDom
{
public Object Object { get; set; }
public Array Array { get; set; }
public Value Value { get; set; }
public TestDom this[ReadOnlyMemory<byte> index]
{
get
{
if (Object == null) throw new NullReferenceException();
if (Object.Pairs == null) throw new NullReferenceException();
var json = new TestDom();
foreach (var pair in Object.Pairs)
{
if (pair.Name.Span.SequenceEqual(index.Span))
{
switch (pair.Value.Type)
{
case Value.ValueType.Object:
json.Object = pair.Value.ObjectValue;
break;
case Value.ValueType.Array:
json.Array = pair.Value.ArrayValue;
break;
case Value.ValueType.String:
case Value.ValueType.Number:
case Value.ValueType.False:
case Value.ValueType.True:
case Value.ValueType.Null:
json.Value = pair.Value;
break;
default:
break;
}
return json;
}
}
throw new KeyNotFoundException();
}
}
public TestDom this[int index]
{
get
{
if (Array == null) throw new NullReferenceException();
if (Array.Values == null) throw new NullReferenceException();
List<Value> values = Array.Values;
if (index < 0 || index >= values.Count) throw new IndexOutOfRangeException();
Value value = values[index];
var json = new TestDom();
switch (value.Type)
{
case Value.ValueType.Object:
json.Object = value.ObjectValue;
break;
case Value.ValueType.Array:
json.Array = value.ArrayValue;
break;
case Value.ValueType.String:
case Value.ValueType.Number:
case Value.ValueType.False:
case Value.ValueType.True:
case Value.ValueType.Null:
json.Value = value;
break;
default:
break;
}
return json;
}
}
public static explicit operator string (TestDom json)
{
if (json == null || json.Value == null) throw new NullReferenceException();
if (json.Value.Type == Value.ValueType.String)
{
return Encoding.UTF8.GetString(json.Value.StringValue.Span);
}
else if (json.Value.Type == Value.ValueType.Null)
{
return json.Value.NullValue.ToString();
}
else
{
throw new InvalidCastException();
}
}
public static explicit operator double (TestDom json)
{
if (json == null || json.Value == null) throw new NullReferenceException();
if (json.Value.Type == Value.ValueType.Number)
{
return json.Value.NumberValue;
}
else
{
throw new InvalidCastException();
}
}
public static explicit operator bool (TestDom json)
{
if (json == null || json.Value == null) throw new NullReferenceException();
if (json.Value.Type == Value.ValueType.True)
{
return json.Value.TrueValue;
}
else if (json.Value.Type == Value.ValueType.False)
{
return json.Value.FalseValue;
}
else
{
throw new InvalidCastException();
}
}
public List<Value> GetValueFromPropertyName(string str)
{
return GetValueFromPropertyName(new Utf8Span(str), Object);
}
public List<Value> GetValueFromPropertyName(Utf8Span str)
{
return GetValueFromPropertyName(str, Object);
}
public List<Value> GetValueFromPropertyName(string str, Object obj)
{
return GetValueFromPropertyName(new Utf8Span(str), obj);
}
public List<Value> GetValueFromPropertyName(Utf8Span str, Object obj)
{
var values = new List<Value>();
if (obj == null || obj.Pairs == null) return values;
foreach (var pair in obj.Pairs)
{
if (pair == null || pair.Value == null) return values;
if (pair.Value.Type == Value.ValueType.Object)
{
values.AddRange(GetValueFromPropertyName(str, pair.Value.ObjectValue));
}
if (pair.Value.Type == Value.ValueType.Array)
{
if (pair.Value.ArrayValue == null || pair.Value.ArrayValue.Values == null) return values;
foreach (var value in pair.Value.ArrayValue.Values)
{
if (value != null && value.Type == Value.ValueType.Object)
{
values.AddRange(GetValueFromPropertyName(str, value.ObjectValue));
}
}
}
if (new Utf8Span(pair.Name.Span) == str)
{
values.Add(pair.Value);
}
}
return values;
}
public override string ToString()
{
if (Object != null)
{
return OutputObject(Object);
}
if (Array != null)
{
return OutputArray(Array);
}
return "";
}
private string OutputObject(Object obj)
{
var strBuilder = new StringBuilder();
if (obj == null || obj.Pairs == null) return "";
strBuilder.Append("{");
for (var i = 0; i < obj.Pairs.Count; i++)
{
strBuilder.Append(OutputPair(obj.Pairs[i]));
if (i < obj.Pairs.Count - 1)
{
strBuilder.Append(",");
}
}
strBuilder.Append("}");
return strBuilder.ToString();
}
private string OutputPair(Pair pair)
{
var str = "";
if (pair == null) return str;
str += "\"" + Encoding.UTF8.GetString(pair.Name.Span) + "\":";
str += OutputValue(pair.Value);
return str;
}
private string OutputArray(Array array)
{
var strBuilder = new StringBuilder();
if (array == null || array.Values == null) return "";
strBuilder.Append("[");
for (var i = 0; i < array.Values.Count; i++)
{
strBuilder.Append(OutputValue(array.Values[i]));
if (i < array.Values.Count - 1)
{
strBuilder.Append(",");
}
}
strBuilder.Append("]");
return strBuilder.ToString();
}
private string OutputValue(Value value)
{
var str = "";
if (value == null) return str;
var type = value.Type;
switch (type)
{
case Value.ValueType.String:
str += "\"" + Encoding.UTF8.GetString(value.StringValue.Span) + "\"";
break;
case Value.ValueType.Number:
str += value.NumberValue;
break;
case Value.ValueType.Object:
str += OutputObject(value.ObjectValue);
break;
case Value.ValueType.Array:
str += OutputArray(value.ArrayValue);
break;
case Value.ValueType.True:
str += value.TrueValue.ToString().ToLower();
break;
case Value.ValueType.False:
str += value.FalseValue.ToString().ToLower();
break;
case Value.ValueType.Null:
str += value.NullValue.ToString().ToLower();
break;
default:
throw new ArgumentOutOfRangeException();
}
return str;
}
}
public class Object
{
public List<Pair> Pairs { get; set; }
}
public class Pair
{
public ReadOnlyMemory<byte> Name { get; set; }
public Value Value { get; set; }
}
public class Array
{
public List<Value> Values { get; set; }
}
public class Value
{
public ValueType Type { get; set; }
public enum ValueType
{
String,
Number,
Object,
Array,
True,
False,
Null
}
public object Raw()
{
switch (Type)
{
case ValueType.String:
return _string;
case ValueType.Number:
return _number;
case ValueType.Object:
return _object;
case ValueType.Array:
return _array;
case ValueType.True:
return True;
case ValueType.False:
return False;
case ValueType.Null:
return null;
default:
throw new ArgumentOutOfRangeException();
}
}
public ReadOnlyMemory<byte> StringValue
{
get
{
if (Type == ValueType.String)
{
return _string;
}
throw new TypeAccessException("Value is not of type 'string'.");
}
set
{
if (Type == ValueType.String)
{
_string = value;
}
}
}
public double NumberValue
{
get
{
if (Type == ValueType.Number)
{
return _number;
}
throw new TypeAccessException("Value is not of type 'number'.");
}
set
{
if (Type == ValueType.Number)
{
_number = value;
}
}
}
public Object ObjectValue
{
get
{
if (Type == ValueType.Object)
{
return _object;
}
throw new TypeAccessException("Value is not of type 'object'.");
}
set
{
if (Type == ValueType.Object)
{
_object = value;
}
}
}
public Array ArrayValue
{
get
{
if (Type == ValueType.Array)
{
return _array;
}
throw new TypeAccessException("Value is not of type 'array'.");
}
set
{
if (Type == ValueType.Array)
{
_array = value;
}
}
}
public bool TrueValue
{
get
{
if (Type == ValueType.True)
{
return True;
}
throw new TypeAccessException("Value is not of type 'true'.");
}
}
public bool FalseValue
{
get
{
if (Type == ValueType.False)
{
return False;
}
throw new TypeAccessException("Value is not of type 'false'.");
}
}
public object NullValue
{
get
{
if (Type == ValueType.Null)
{
return Null;
}
throw new TypeAccessException("Value is not of type 'null'.");
}
}
private ReadOnlyMemory<byte> _string;
private double _number;
private Object _object;
private Array _array;
private const bool True = true;
private const bool False = false;
private const string Null = "null";
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.UI;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Framework.Data;
using Subtext.Framework.Routing;
using Subtext.Framework.Services.SearchEngine;
using Subtext.Framework.Text;
using Subtext.Framework.UI.Skinning;
using Subtext.Framework.Web.Handlers;
using Subtext.Web.UI.Controls;
namespace Subtext.Web.UI.Pages
{
/// <summary>
/// This serves as the master page for every page within the
/// site (except for the admin section. This page contains
/// a PlaceHolder in which the PageTemplate.ascx control within
/// each skin is loaded.
/// </summary>
public partial class SubtextMasterPage : SubtextPage, IPageWithControls, IContainerControl
{
protected const string ControlLocation = "~/Skins/{0}/Controls/{1}";
protected const string OpenIdDelegateLocation = "<link rel=\"openid.delegate\" href=\"{0}\" />";
protected const string OpenIdServerLocation = "<link rel=\"openid.server\" href=\"{0}\" />";
protected const string TemplateLocation = "~/Skins/{0}/{1}";
public static readonly string CommentsPanelId = "commentsUpdatePanelWrapper";
private static readonly ScriptElementCollectionRenderer ScriptRenderer = new ScriptElementCollectionRenderer(new SkinEngine());
private static readonly StyleSheetElementCollectionRenderer StyleRenderer =
new StyleSheetElementCollectionRenderer(new SkinEngine());
IEnumerable<string> _controls;
/// <summary>
/// Returns the text for a javascript array of allowed elements.
/// This will be used by other scripts.
/// </summary>
/// <value>The allowed HTML javascript declaration.</value>
protected static string AllowedHtmlJavascriptDeclaration
{
get
{
string declaration = "var subtextAllowedHtmlTags = [";
for (int i = 0; i < Config.Settings.AllowedHtmlTags.Count; i++)
{
string tagname = Config.Settings.AllowedHtmlTags.Keys[i];
declaration += string.Format(CultureInfo.InvariantCulture, "'{0}', ", tagname);
}
if (Config.Settings.AllowedHtmlTags.Count > 0)
{
declaration = declaration.Left(declaration.Length - 2);
}
return declaration + "];";
}
}
public void SetControls(IEnumerable<string> controls)
{
_controls = controls;
}
public void InitializeControls(ISkinControlLoader controlLoader)
{
IEnumerable<string> controlNames = _controls;
if (controlNames != null)
{
var apnlCommentsWrapper = new UpdatePanel { Visible = true, ID = CommentsPanelId };
if (!controlNames.Contains("HomePage", StringComparer.OrdinalIgnoreCase) && !String.IsNullOrEmpty(Query))
{
int entryId = -1;
Entry entry = Cacher.GetEntryFromRequest(true, SubtextContext);
if (entry != null)
{
entryId = entry.Id;
}
var query = Query;
if (!String.IsNullOrEmpty(query))
{
var searchResults = SearchEngineService.Search(query, 5, Blog.Id, entryId);
if (searchResults.Any())
{
AddMoreResultsControl(searchResults, controlLoader, apnlCommentsWrapper);
}
}
}
foreach (string controlName in controlNames)
{
Control control = controlLoader.LoadControl(controlName);
AddControlToBody(controlName, control, apnlCommentsWrapper, CenterBodyControl);
}
}
}
private void AddMoreResultsControl(IEnumerable<SearchEngineResult> searchResults, ISkinControlLoader controlLoader, UpdatePanel apnlCommentsWrapper)
{
var moreResults = controlLoader.LoadControl("MoreResults");
if (moreResults != null)
{
var moreSearchResults = moreResults as MoreResultsLikeThis;
if (moreSearchResults != null)
{
moreSearchResults.SearchResults = searchResults;
}
AddControlToBody("MoreResults", moreResults, apnlCommentsWrapper, CenterBodyControl);
}
}
public void AddControlToBody(string controlName, Control control, UpdatePanel apnlCommentsWrapper, Control centerBodyControl)
{
if (controlName.Equals("Comments", StringComparison.OrdinalIgnoreCase))
{
control.Visible = true;
commentsControl = control as Comments;
apnlCommentsWrapper.ContentTemplateContainer.Controls.Add(control);
}
else if (controlName.Equals("PostComment", StringComparison.OrdinalIgnoreCase))
{
postCommentControl = control as PostComment;
if (postCommentControl != null)
{
postCommentControl.CommentApproved += OnCommentPosted;
}
apnlCommentsWrapper.ContentTemplateContainer.Controls.Add(control);
centerBodyControl.Controls.Add(apnlCommentsWrapper);
}
else
{
if (centerBodyControl != null)
{
centerBodyControl.Controls.Add(control);
}
}
}
public string Query
{
get
{
if (_query == null)
{
var request = SubtextContext.HttpContext.Request;
var referrer = request.UrlReferrer;
if (referrer == null)
{
if (request.IsLocal)
{
string referrerInQuery = request.QueryString["referrer"];
if (!String.IsNullOrEmpty(referrerInQuery))
{
Uri.TryCreate(referrerInQuery, UriKind.Absolute, out referrer);
}
}
}
if (referrer == null)
{
return null;
}
_query = BlogUrlHelper.ExtractKeywordsFromReferrer(referrer, request.Url);
}
return _query;
}
}
private string _query;
public void InitializeBlogPage()
{
var skin = SkinConfig.GetCurrentSkin(Blog, SubtextContext.HttpContext);
var skinControlLoader = new SkinControlLoader(this, skin);
InitializeControls(skinControlLoader);
if (skin.HasCustomCssText)
{
CustomCss.Attributes.Add("href", Url.CustomCssUrl());
}
else
{
//MAC IE does not like the empy CSS file, plus its a waste :)
CustomCss.Visible = false;
}
if (Rsd != null)
{
Rsd.Attributes.Add("href", Url.RsdUrl(Blog).ToString());
}
if (wlwmanifest != null)
{
wlwmanifest.Attributes.Add("href", Url.WlwManifestUrl());
}
if (opensearch != null)
{
opensearch.Attributes.Add("href", Url.OpenSearchDescriptorUrl());
opensearch.Attributes.Add("Title", Blog.Title);
}
if (RSSLink != null)
{
RSSLink.Attributes.Add("href", Url.RssUrl(Blog).ToString());
}
// if specified, add script elements
if (scripts != null)
{
scripts.Text = ScriptRenderer.RenderScriptElementCollection(skin.SkinKey);
}
if (styles != null)
{
styles.Text = StyleRenderer.RenderStyleElementCollection(skin.SkinKey);
}
if (openIDServer != null && !string.IsNullOrEmpty(Blog.OpenIdServer))
{
openIDServer.Text = string.Format(OpenIdServerLocation, Blog.OpenIdServer);
}
if (openIDDelegate != null && !string.IsNullOrEmpty(Blog.OpenIdDelegate))
{
openIDDelegate.Text = string.Format(OpenIdDelegateLocation, Blog.OpenIdDelegate);
}
if (metaTags != null)
{
metaTags.Blog = Blog;
}
}
void OnCommentPosted(object sender, EventArgs e)
{
if (commentsControl != null)
{
commentsControl.InvalidateFeedbackCache();
commentsControl.BindFeedback(true); //don't get it from cache.
}
}
/// <summary>
/// Before rendering, turns off ViewState again (why? not sure),
/// applies skins and stylesheet references, and sets the page title.
/// </summary>
/// <param name="e">E.</param>
protected override void OnPreRender(EventArgs e)
{
Response.ContentEncoding = Encoding.UTF8; //TODO: allow for per/blog config.
Response.ContentType = "text/html"; //TODO: allow for per/blog config.
//Is this for extra security?
EnableViewState = false;
pageTitle.Text = Globals.CurrentTitle(Context);
if (!String.IsNullOrEmpty(Blog.Author))
{
authorMetaTag.Text = String.Format(Environment.NewLine + "<meta name=\"author\" content=\"{0}\" />",
Blog.Author);
}
versionMetaTag.Text =
String.Format("{0}<meta name=\"Generator\" content=\"{1}\" />{0}", Environment.NewLine, VersionInfo.VersionDisplayText);
if (!String.IsNullOrEmpty(Blog.TrackingCode))
{
customTrackingCode.Text = Blog.TrackingCode;
}
base.OnPreRender(e);
}
/// <summary>
/// Initializes this blog page, applying skins and whatnot.
/// </summary>
/// <param name="e">E.</param>
override protected void OnInit(EventArgs e)
{
MaintainScrollPositionOnPostBack = true;
InitializeBlogPage();
base.OnInit(e);
}
/// <summary>
/// Loads the page state from persistence medium. In this case
/// this returns null as we are not using ViewState.
/// </summary>
/// <returns></returns>
protected override object LoadPageStateFromPersistenceMedium()
{
return null;
}
/// <summary>
/// Saves the page state to persistence medium. In this case
/// this does nothing as we are not using ViewState.
/// </summary>
/// <param name="viewState">State of the view.</param>
protected override void SavePageStateToPersistenceMedium(object viewState)
{
}
}
}
| |
using Microsoft.Deployment.WindowsInstaller;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace WixSharp.UI.Forms
{
/// <summary>
/// Set of extension methods for working with ManagedUI dialogs
/// </summary>
public static class Extensions
{
/// <summary>
/// Determines whether the feature checkbox is checked.
/// </summary>
/// <param name="feature">The feature.</param>
/// <returns></returns>
public static bool IsViewChecked(this FeatureItem feature)
{
if (feature.View is TreeNode)
return (feature.View as TreeNode).Checked;
return false;
}
/// <summary>
/// Resets the whether the feature checkbox checked state to the initial stat.
/// </summary>
/// <param name="feature">The feature.</param>
public static void ResetViewChecked(this FeatureItem feature)
{
if (feature.View is TreeNode)
(feature.View as TreeNode).Checked = feature.DefaultIsToBeInstalled();
}
/// <summary>
/// Returns default 'is to be installed' state of teh feature.
/// </summary>
/// <param name="feature">The feature.</param>
/// <returns></returns>
public static bool DefaultIsToBeInstalled(this FeatureItem feature)
{
return feature.RequestedState != InstallState.Absent;
}
/// <summary>
/// Returns the FeatireItem bound to the TreeNode.
/// </summary>
/// <param name="node">The node.</param>
/// <returns></returns>
public static FeatureItem FeatureItem(this TreeNode node)
{
return node.Tag as FeatureItem;
}
/// <summary>
/// Converts TreeNodeCollection into the TreeNode array.
/// </summary>
/// <param name="nodes">The nodes.</param>
/// <returns></returns>
public static TreeNode[] ToArray(this TreeNodeCollection nodes)
{
return nodes.Cast<TreeNode>().ToArray();
}
/// <summary>
/// Aggregates all nodes of the TreeView control.
/// </summary>
/// <param name="treeView">The tree view.</param>
/// <returns></returns>
public static TreeNode[] AllNodes(this TreeView treeView)
{
var result = new List<TreeNode>();
var queue = new Queue<TreeNode>(treeView.Nodes.Cast<TreeNode>());
while (queue.Any())
{
TreeNode node = queue.Dequeue();
result.Add(node);
foreach (TreeNode child in node.Nodes)
queue.Enqueue(child);
}
return result.ToArray();
}
}
#pragma warning disable 1591
public class ReadOnlyTreeNode : TreeNode
{
public bool IsReadOnly { get; set; }
public class Behavior
{
public static void AttachTo(TreeView treeView, bool drawTextOnly = false)
{
if (drawTextOnly)
{
treeView.DrawMode = TreeViewDrawMode.OwnerDrawText;
treeView.DrawNode += treeView_DrawNodeText;
}
else
{
treeView.DrawMode = TreeViewDrawMode.OwnerDrawAll;
treeView.DrawNode += treeView_DrawNode;
}
treeView.BeforeCheck += treeView_BeforeCheck;
}
static void treeView_BeforeCheck(object sender, TreeViewCancelEventArgs e)
{
if (IsReadOnly(e.Node))
{
e.Cancel = true;
}
}
static Pen dotPen = new Pen(Color.FromArgb(128, 128, 128)) { DashStyle = DashStyle.Dot };
static Brush selectionModeBrush = new SolidBrush(Color.FromArgb(51, 153, 255));
static bool IsReadOnly(TreeNode node)
{
return (node is ReadOnlyTreeNode) && (node as ReadOnlyTreeNode).IsReadOnly;
}
static int cIndentBy = -1;
static int cMargin = -1;
static void treeView_DrawNodeText(object sender, DrawTreeNodeEventArgs e)
{
var bounds = e.Bounds;
//Loosely based on Jason Williams solution (http://stackoverflow.com/questions/1003459/c-treeview-owner-drawing-with-ownerdrawtext-and-the-weird-black-highlighting-w)
if (bounds.Height < 1 || bounds.Width < 1)
return;
var treeView = (TreeView) sender;
bounds.Width += 5; //found by experiment that text can swallow last character
if (e.Node.IsSelected)
{
e.Graphics.FillRectangle(selectionModeBrush, e.Bounds);
e.Graphics.DrawString(e.Node.Text, treeView.Font, Brushes.White, bounds);
}
else
{
if (IsReadOnly(e.Node))
e.Graphics.DrawString(e.Node.Text, treeView.Font, Brushes.Gray, bounds);
else
e.Graphics.DrawString(e.Node.Text, treeView.Font, Brushes.Black, bounds);
}
}
static void treeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
var treeView = (TreeView) sender;
try
{
//Loosely based on Jason Williams solution (http://stackoverflow.com/questions/1003459/c-treeview-owner-drawing-with-ownerdrawtext-and-the-weird-black-highlighting-w)
if (e.Bounds.Height < 1 || e.Bounds.Width < 1)
return;
if (cIndentBy == -1)
{
cIndentBy = e.Bounds.Height;
cMargin = e.Bounds.Height / 2;
}
Rectangle itemRect = e.Bounds;
e.Graphics.FillRectangle(Brushes.White, itemRect);
//e.Graphics.FillRectangle(Brushes.WhiteSmoke, itemRect);
int cTwoMargins = cMargin * 2;
int midY = (itemRect.Top + itemRect.Bottom) / 2;
int iconWidth = itemRect.Height + 2;
int checkboxWidth = itemRect.Height + 2;
int indent = (e.Node.Level * cIndentBy) + cMargin;
int iconLeft = indent; // lines left position
int checkboxLeft = iconLeft + iconWidth; // +/- icon left position
int textLeft = checkboxLeft + checkboxWidth; // text left position
if (!treeView.CheckBoxes)
textLeft = checkboxLeft;
// Draw parentage lines
if (treeView.ShowLines)
{
int x = cMargin * 2;
if (e.Node.Level == 0 && e.Node.PrevNode == null)
{
// The very first node in the tree has a half-height line
e.Graphics.DrawLine(dotPen, x, midY, x, itemRect.Bottom);
}
else
{
TreeNode testNode = e.Node; // Used to only draw lines to nodes with Next Siblings, as in normal TreeViews
for (int iLine = e.Node.Level; iLine >= 0; iLine--)
{
if (testNode.NextNode != null)
{
x = (iLine * cIndentBy) + (cMargin * 2);
e.Graphics.DrawLine(dotPen, x, itemRect.Top, x, itemRect.Bottom);
}
testNode = testNode.Parent;
}
x = (e.Node.Level * cIndentBy) + (cMargin * 2);
e.Graphics.DrawLine(dotPen, x, itemRect.Top, x, midY);
}
e.Graphics.DrawLine(dotPen, iconLeft + cMargin, midY, iconLeft + cMargin + 10, midY);
}
// Draw (plus/minus) icon if required
if (e.Node.Nodes.Count > 0)
{
var element = e.Node.IsExpanded ? VisualStyleElement.TreeView.Glyph.Opened : VisualStyleElement.TreeView.Glyph.Closed;
var renderer = new VisualStyleRenderer(element);
var iconTrueSize = renderer.GetPartSize(e.Graphics, ThemeSizeType.True);
var bounds = new Rectangle(itemRect.Left + iconLeft, itemRect.Top, iconWidth, iconWidth);
//e.Graphics.FillRectangle(Brushes.Salmon, bounds);
//deflate (resize and center) icon within bounds
var dif = (iconWidth - iconTrueSize.Height) / 2 - 1; //-1 is to compensate for rounding as icon is not getting rendered if the bounds is too small
bounds.Inflate(-dif, -dif);
renderer.DrawBackground(e.Graphics, bounds);
}
//Checkbox
if (treeView.CheckBoxes)
{
var element = e.Node.Checked ? VisualStyleElement.Button.CheckBox.CheckedNormal : VisualStyleElement.Button.CheckBox.UncheckedNormal;
if (IsReadOnly(e.Node))
element = e.Node.Checked ? VisualStyleElement.Button.CheckBox.CheckedDisabled : VisualStyleElement.Button.CheckBox.UncheckedDisabled;
var renderer = new VisualStyleRenderer(element);
var bounds = new Rectangle(itemRect.Left + checkboxLeft, itemRect.Top, checkboxWidth, itemRect.Height);
//e.Graphics.FillRectangle(Brushes.Bisque, bounds);
renderer.DrawBackground(e.Graphics, bounds);
}
//Text
if (!string.IsNullOrEmpty(e.Node.Text))
{
SizeF textSize = e.Graphics.MeasureString(e.Node.Text, treeView.Font);
var drawFormat = new StringFormat
{
Alignment = StringAlignment.Near,
LineAlignment = StringAlignment.Center,
FormatFlags = StringFormatFlags.NoWrap,
};
var bounds = new Rectangle(itemRect.Left + textLeft, itemRect.Top, (int) (textSize.Width + 2), itemRect.Height);
if (e.Node.IsSelected)
{
e.Graphics.FillRectangle(selectionModeBrush, bounds);
e.Graphics.DrawString(e.Node.Text, treeView.Font, Brushes.White, bounds, drawFormat);
}
else
{
var brush = Brushes.Black;
if (IsReadOnly(e.Node))
brush = Brushes.Gray;
e.Graphics.DrawString(e.Node.Text, treeView.Font, brush, bounds, drawFormat);
}
}
// Focus rectangle around the text
if (e.State == TreeNodeStates.Focused)
{
var r = itemRect;
r.Width -= 2;
r.Height -= 2;
r.Offset(indent, 0);
r.Width -= indent;
e.Graphics.DrawRectangle(dotPen, r);
}
}
catch
{
//The exception can be thrown in the result of incapability of the target OS.
//Thus users reported VisualStyleRenderer instantiation exception (https://wixsharp.codeplex.com/discussions/656266#)
//Thus fall back to more conservative rendering algorithm
treeView.DrawMode = TreeViewDrawMode.OwnerDrawText;
treeView.DrawNode -= treeView_DrawNode;
treeView.DrawNode += treeView_DrawNodeText;
}
}
}
#pragma warning restore 1591
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ReaderOutput.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Xsl.XsltOld {
using Res = System.Xml.Utils.Res;
using System;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Collections;
internal class ReaderOutput : XmlReader, RecordOutput {
private Processor processor;
private XmlNameTable nameTable;
// Main node + Fields Collection
private RecordBuilder builder;
private BuilderInfo mainNode;
private ArrayList attributeList;
private int attributeCount;
private BuilderInfo attributeValue;
// OutputScopeManager
private OutputScopeManager manager;
// Current position in the list
private int currentIndex;
private BuilderInfo currentInfo;
// Reader state
private ReadState state = ReadState.Initial;
private bool haveRecord;
// Static default record
static BuilderInfo s_DefaultInfo = new BuilderInfo();
XmlEncoder encoder = new XmlEncoder();
XmlCharType xmlCharType = XmlCharType.Instance;
internal ReaderOutput(Processor processor) {
Debug.Assert(processor != null);
Debug.Assert(processor.NameTable != null);
this.processor = processor;
this.nameTable = processor.NameTable;
Reset();
}
// XmlReader abstract methods implementation
public override XmlNodeType NodeType {
get {
CheckCurrentInfo();
return this.currentInfo.NodeType;
}
}
public override string Name {
get {
CheckCurrentInfo();
string prefix = Prefix;
string localName = LocalName;
if (prefix != null && prefix.Length > 0) {
if (localName.Length > 0) {
return nameTable.Add(prefix + ":" + localName);
}
else {
return prefix;
}
}
else {
return localName;
}
}
}
public override string LocalName {
get {
CheckCurrentInfo();
return this.currentInfo.LocalName;
}
}
public override string NamespaceURI {
get {
CheckCurrentInfo();
return this.currentInfo.NamespaceURI;
}
}
public override string Prefix {
get {
CheckCurrentInfo();
return this.currentInfo.Prefix;
}
}
public override bool HasValue {
get {
return XmlReader.HasValueInternal(NodeType);
}
}
public override string Value {
get {
CheckCurrentInfo();
return this.currentInfo.Value;
}
}
public override int Depth {
get {
CheckCurrentInfo();
return this.currentInfo.Depth;
}
}
public override string BaseURI {
get {
return string.Empty;
}
}
public override bool IsEmptyElement {
get {
CheckCurrentInfo();
return this.currentInfo.IsEmptyTag;
}
}
public override char QuoteChar {
get { return encoder.QuoteChar; }
}
public override bool IsDefault {
get { return false; }
}
public override XmlSpace XmlSpace {
get { return this.manager != null ? this.manager.XmlSpace : XmlSpace.None; }
}
public override string XmlLang {
get { return this.manager != null ? this.manager.XmlLang : string.Empty; }
}
// Attribute Accessors
public override int AttributeCount {
get { return this.attributeCount; }
}
public override string GetAttribute(string name) {
int ordinal;
if (FindAttribute(name, out ordinal)) {
Debug.Assert(ordinal >= 0);
return((BuilderInfo)this.attributeList[ordinal]).Value;
}
else {
Debug.Assert(ordinal == -1);
return null;
}
}
public override string GetAttribute(string localName, string namespaceURI) {
int ordinal;
if (FindAttribute(localName, namespaceURI, out ordinal)) {
Debug.Assert(ordinal >= 0);
return((BuilderInfo)this.attributeList[ordinal]).Value;
}
else {
Debug.Assert(ordinal == -1);
return null;
}
}
public override string GetAttribute(int i) {
BuilderInfo attribute = GetBuilderInfo(i);
return attribute.Value;
}
public override string this [int i] {
get { return GetAttribute(i); }
}
public override string this [string name] {
get { return GetAttribute(name); }
}
public override string this [string name, string namespaceURI] {
get { return GetAttribute(name, namespaceURI); }
}
public override bool MoveToAttribute(string name) {
int ordinal;
if (FindAttribute(name, out ordinal)) {
Debug.Assert(ordinal >= 0);
SetAttribute(ordinal);
return true;
}
else {
Debug.Assert(ordinal == -1);
return false;
}
}
public override bool MoveToAttribute(string localName, string namespaceURI) {
int ordinal;
if (FindAttribute(localName, namespaceURI, out ordinal)) {
Debug.Assert(ordinal >= 0);
SetAttribute(ordinal);
return true;
}
else {
Debug.Assert(ordinal == -1);
return false;
}
}
public override void MoveToAttribute(int i) {
if (i < 0 || this.attributeCount <= i) {
throw new ArgumentOutOfRangeException("i");
}
SetAttribute(i);
}
public override bool MoveToFirstAttribute() {
if (this.attributeCount <= 0) {
Debug.Assert(this.attributeCount == 0);
return false;
}
else {
SetAttribute(0);
return true;
}
}
public override bool MoveToNextAttribute() {
if (this.currentIndex + 1 < this.attributeCount) {
SetAttribute(this.currentIndex + 1);
return true;
}
return false;
}
public override bool MoveToElement() {
if (NodeType == XmlNodeType.Attribute || this.currentInfo == this.attributeValue) {
SetMainNode();
return true;
}
return false;
}
// Moving through the Stream
public override bool Read() {
Debug.Assert(this.processor != null || this.state == ReadState.Closed);
if (this.state != ReadState.Interactive) {
if (this.state == ReadState.Initial) {
state = ReadState.Interactive;
}
else {
return false;
}
}
while (true) { // while -- to ignor empty whitespace nodes.
if (this.haveRecord) {
this.processor.ResetOutput();
this.haveRecord = false;
}
this.processor.Execute();
if (this.haveRecord) {
CheckCurrentInfo();
// check text nodes on whitespaces;
switch (this.NodeType) {
case XmlNodeType.Text :
if (xmlCharType.IsOnlyWhitespace(this.Value)) {
this.currentInfo.NodeType = XmlNodeType.Whitespace;
goto case XmlNodeType.Whitespace;
}
Debug.Assert(this.Value.Length != 0, "It whould be Whitespace in this case");
break;
case XmlNodeType.Whitespace :
if(this.Value.Length == 0) {
continue; // ignoring emty text nodes
}
if (this.XmlSpace == XmlSpace.Preserve) {
this.currentInfo.NodeType = XmlNodeType.SignificantWhitespace;
}
break;
}
}
else {
Debug.Assert(this.processor.ExecutionDone);
this.state = ReadState.EndOfFile;
Reset();
}
return this.haveRecord;
}
}
public override bool EOF {
get { return this.state == ReadState.EndOfFile; }
}
public override void Close() {
this.processor = null;
this.state = ReadState.Closed;
Reset();
}
public override ReadState ReadState {
get { return this.state; }
}
// Whole Content Read Methods
public override string ReadString() {
string result = string.Empty;
if (NodeType == XmlNodeType.Element || NodeType == XmlNodeType.Attribute || this.currentInfo == this.attributeValue) {
if(this.mainNode.IsEmptyTag) {
return result;
}
if (! Read()) {
throw new InvalidOperationException(Res.GetString(Res.Xml_InvalidOperation));
}
}
StringBuilder sb = null;
bool first = true;
while(true) {
switch (NodeType) {
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
// case XmlNodeType.CharacterEntity:
if (first) {
result = this.Value;
first = false;
} else {
if (sb == null) {
sb = new StringBuilder(result);
}
sb.Append(this.Value);
}
if (! Read())
throw new InvalidOperationException(Res.GetString(Res.Xml_InvalidOperation));
break;
default:
return (sb == null) ? result : sb.ToString();
}
}
}
public override string ReadInnerXml() {
if (ReadState == ReadState.Interactive) {
if (NodeType == XmlNodeType.Element && ! IsEmptyElement) {
StringOutput output = new StringOutput(this.processor);
output.OmitXmlDecl();
int depth = Depth;
Read(); // skeep begin Element
while (depth < Depth) { // process content
Debug.Assert(this.builder != null);
output.RecordDone(this.builder);
Read();
}
Debug.Assert(NodeType == XmlNodeType.EndElement);
Read(); // skeep end element
output.TheEnd();
return output.Result;
}
else if(NodeType == XmlNodeType.Attribute) {
return encoder.AtributeInnerXml(Value);
}
else {
Read();
}
}
return string.Empty;
}
public override string ReadOuterXml() {
if (ReadState == ReadState.Interactive) {
if (NodeType == XmlNodeType.Element) {
StringOutput output = new StringOutput(this.processor);
output.OmitXmlDecl();
bool emptyElement = IsEmptyElement;
int depth = Depth;
// process current record
output.RecordDone(this.builder);
Read();
// process internal elements & text nodes
while(depth < Depth) {
Debug.Assert(this.builder != null);
output.RecordDone(this.builder);
Read();
}
// process end element
if (! emptyElement) {
output.RecordDone(this.builder);
Read();
}
output.TheEnd();
return output.Result;
}
else if(NodeType == XmlNodeType.Attribute) {
return encoder.AtributeOuterXml(Name, Value);
}
else {
Read();
}
}
return string.Empty;
}
//
// Nametable and Namespace Helpers
//
public override XmlNameTable NameTable {
get {
Debug.Assert(this.nameTable != null);
return this.nameTable;
}
}
public override string LookupNamespace(string prefix) {
prefix = this.nameTable.Get(prefix);
if (this.manager != null && prefix != null) {
return this.manager.ResolveNamespace(prefix);
}
return null;
}
public override void ResolveEntity() {
Debug.Assert(NodeType != XmlNodeType.EntityReference);
if (NodeType != XmlNodeType.EntityReference) {
throw new InvalidOperationException(Res.GetString(Res.Xml_InvalidOperation));
}
}
public override bool ReadAttributeValue() {
if (ReadState != ReadState.Interactive || NodeType != XmlNodeType.Attribute) {
return false;
}
if (this.attributeValue == null) {
this.attributeValue = new BuilderInfo();
this.attributeValue.NodeType = XmlNodeType.Text;
}
if (this.currentInfo == this.attributeValue) {
return false;
}
this.attributeValue.Value = this.currentInfo.Value;
this.attributeValue.Depth = this.currentInfo.Depth + 1;
this.currentInfo = this.attributeValue;
return true;
}
//
// RecordOutput interface method implementation
//
public Processor.OutputResult RecordDone(RecordBuilder record) {
this.builder = record;
this.mainNode = record.MainNode;
this.attributeList = record.AttributeList;
this.attributeCount = record.AttributeCount;
this.manager = record.Manager;
this.haveRecord = true;
SetMainNode();
return Processor.OutputResult.Interrupt;
}
public void TheEnd() {
// nothing here, was taken care of by RecordBuilder
}
//
// Implementation internals
//
private void SetMainNode() {
this.currentIndex = -1;
this.currentInfo = this.mainNode;
}
private void SetAttribute(int attrib) {
Debug.Assert(0 <= attrib && attrib < this.attributeCount);
Debug.Assert(0 <= attrib && attrib < this.attributeList.Count);
Debug.Assert(this.attributeList[attrib] is BuilderInfo);
this.currentIndex = attrib;
this.currentInfo = (BuilderInfo) this.attributeList[attrib];
}
private BuilderInfo GetBuilderInfo(int attrib) {
if (attrib < 0 || this.attributeCount <= attrib) {
throw new ArgumentOutOfRangeException("attrib");
}
Debug.Assert(this.attributeList[attrib] is BuilderInfo);
return(BuilderInfo) this.attributeList[attrib];
}
private bool FindAttribute(String localName, String namespaceURI, out int attrIndex) {
if (namespaceURI == null) {
namespaceURI = string.Empty;
}
if (localName == null) {
localName = string.Empty;
}
for (int index = 0; index < this.attributeCount; index ++) {
Debug.Assert(this.attributeList[index] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo) this.attributeList[index];
if (attribute.NamespaceURI == namespaceURI && attribute.LocalName == localName) {
attrIndex = index;
return true;
}
}
attrIndex = -1;
return false;
}
private bool FindAttribute(String name, out int attrIndex) {
if (name == null) {
name = string.Empty;
}
for (int index = 0; index < this.attributeCount; index ++) {
Debug.Assert(this.attributeList[index] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo) this.attributeList[index];
if (attribute.Name == name) {
attrIndex = index;
return true;
}
}
attrIndex = -1;
return false;
}
private void Reset() {
this.currentIndex = -1;
this.currentInfo = s_DefaultInfo;
this.mainNode = s_DefaultInfo;
this.manager = null;
}
[System.Diagnostics.Conditional("DEBUG")]
private void CheckCurrentInfo() {
Debug.Assert(this.currentInfo != null);
Debug.Assert(this.attributeCount == 0 || this.attributeList != null);
Debug.Assert((this.currentIndex == -1) == (this.currentInfo == this.mainNode));
Debug.Assert((this.currentIndex == -1) || (this.currentInfo == this.attributeValue || this.attributeList[this.currentIndex] is BuilderInfo && this.attributeList[this.currentIndex] == this.currentInfo));
}
private class XmlEncoder {
private StringBuilder buffer = null;
private XmlTextEncoder encoder = null;
private void Init() {
buffer = new StringBuilder();
encoder = new XmlTextEncoder(new StringWriter(buffer, CultureInfo.InvariantCulture));
}
public string AtributeInnerXml(string value) {
if(encoder == null) Init();
buffer .Length = 0; // clean buffer
encoder.StartAttribute(/*save:*/false);
encoder.Write(value);
encoder.EndAttribute();
return buffer.ToString();
}
public string AtributeOuterXml(string name, string value) {
if(encoder == null) Init();
buffer .Length = 0; // clean buffer
buffer .Append(name);
buffer .Append('=');
buffer .Append(QuoteChar);
encoder.StartAttribute(/*save:*/false);
encoder.Write(value);
encoder.EndAttribute();
buffer .Append(QuoteChar);
return buffer.ToString();
}
public char QuoteChar {
get { return '"'; }
}
}
}
}
| |
// 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 {
using System.Text;
using System.Runtime.CompilerServices;
using System.Threading;
using System;
using System.Collections;
using System.Security.Permissions;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
#if !FEATURE_PAL
using Microsoft.Win32.SafeHandles;
using System.Security.Principal;
#endif
//FrameSecurityDescriptor.cs
//
// Internal use only.
// DO NOT DOCUMENT
//
[Serializable]
internal class FrameSecurityDescriptor
{
/* EE has native FrameSecurityDescriptorObject definition in object.h
Make sure to update that structure as well, if you make any changes here.
*/
private PermissionSet m_assertions; // imperative asserts
private PermissionSet m_denials; // imperative denials
private PermissionSet m_restriction; // imperative permitonlys
private PermissionSet m_DeclarativeAssertions;
private PermissionSet m_DeclarativeDenials;
private PermissionSet m_DeclarativeRestrictions;
#if !FEATURE_PAL
// if this frame contains a call to any WindowsIdentity.Impersonate(),
// we save the previous SafeTokenHandles here (in the next two fields)
// Used during exceptionstackwalks to revert impersonation before calling filters
[System.Security.SecurityCritical] // auto-generated
[NonSerialized]
private SafeAccessTokenHandle m_callerToken;
[System.Security.SecurityCritical] // auto-generated
[NonSerialized]
private SafeAccessTokenHandle m_impToken;
#endif
private bool m_AssertFT;
private bool m_assertAllPossible;
#pragma warning disable 169
private bool m_declSecComputed; // set from the VM to indicate that the declarative A/PO/D on this frame has been populated
#pragma warning restore 169
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void IncrementOverridesCount();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void DecrementOverridesCount();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void IncrementAssertCount();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void DecrementAssertCount();
// Default constructor.
internal FrameSecurityDescriptor()
{
//m_flags = 0;
}
//-----------------------------------------------------------+
// H E L P E R
//-----------------------------------------------------------+
private PermissionSet CreateSingletonSet(IPermission perm)
{
PermissionSet permSet = new PermissionSet(false);
permSet.AddPermission(perm.Copy());
return permSet;
}
//-----------------------------------------------------------+
// A S S E R T
//-----------------------------------------------------------+
internal bool HasImperativeAsserts()
{
// we store declarative actions in both fields, so check if they are different
return (m_assertions != null);
}
internal bool HasImperativeDenials()
{
// we store declarative actions in both fields, so check if they are different
return (m_denials != null);
}
internal bool HasImperativeRestrictions()
{
// we store declarative actions in both fields, so check if they are different
return (m_restriction != null);
}
[System.Security.SecurityCritical] // auto-generated
internal void SetAssert(IPermission perm)
{
m_assertions = CreateSingletonSet(perm);
IncrementAssertCount();
}
[System.Security.SecurityCritical] // auto-generated
internal void SetAssert(PermissionSet permSet)
{
m_assertions = permSet.Copy();
m_AssertFT = m_AssertFT || m_assertions.IsUnrestricted();
IncrementAssertCount();
}
internal PermissionSet GetAssertions(bool fDeclarative)
{
return (fDeclarative) ? m_DeclarativeAssertions : m_assertions;
}
[System.Security.SecurityCritical] // auto-generated
internal void SetAssertAllPossible()
{
m_assertAllPossible = true;
IncrementAssertCount();
}
internal bool GetAssertAllPossible()
{
return m_assertAllPossible;
}
//-----------------------------------------------------------+
// D E N Y
//-----------------------------------------------------------+
[System.Security.SecurityCritical] // auto-generated
internal void SetDeny(IPermission perm)
{
#if FEATURE_CAS_POLICY
BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Deny is only valid in legacy CAS mode");
#endif // FEATURE_CAS_POLICY
m_denials = CreateSingletonSet(perm);
IncrementOverridesCount();
}
[System.Security.SecurityCritical] // auto-generated
internal void SetDeny(PermissionSet permSet)
{
m_denials = permSet.Copy();
IncrementOverridesCount();
}
internal PermissionSet GetDenials(bool fDeclarative)
{
return (fDeclarative) ? m_DeclarativeDenials: m_denials;
}
//-----------------------------------------------------------+
// R E S T R I C T
//-----------------------------------------------------------+
[System.Security.SecurityCritical] // auto-generated
internal void SetPermitOnly(IPermission perm)
{
m_restriction = CreateSingletonSet(perm);
IncrementOverridesCount();
}
[System.Security.SecurityCritical] // auto-generated
internal void SetPermitOnly(PermissionSet permSet)
{
// permSet must not be null
m_restriction = permSet.Copy();
IncrementOverridesCount();
}
internal PermissionSet GetPermitOnly(bool fDeclarative)
{
return (fDeclarative) ? m_DeclarativeRestrictions : m_restriction;
}
#if !FEATURE_PAL
//-----------------------------------------------------------+
// SafeAccessTokenHandle (Impersonation + EH purposes)
//-----------------------------------------------------------+
[System.Security.SecurityCritical] // auto-generated
internal void SetTokenHandles (SafeAccessTokenHandle callerToken, SafeAccessTokenHandle impToken)
{
m_callerToken = callerToken;
m_impToken = impToken;
}
#endif
//-----------------------------------------------------------+
// R E V E R T
//-----------------------------------------------------------+
[System.Security.SecurityCritical] // auto-generated
internal void RevertAssert()
{
if (m_assertions != null)
{
m_assertions = null;
DecrementAssertCount();
}
if (m_DeclarativeAssertions != null)
{
m_AssertFT = m_DeclarativeAssertions.IsUnrestricted();
}
else
{
m_AssertFT = false;
}
}
[System.Security.SecurityCritical] // auto-generated
internal void RevertAssertAllPossible()
{
if (m_assertAllPossible)
{
m_assertAllPossible = false;
DecrementAssertCount();
}
}
[System.Security.SecurityCritical] // auto-generated
internal void RevertDeny()
{
if (HasImperativeDenials())
{
DecrementOverridesCount();
m_denials = null;
}
}
[System.Security.SecurityCritical] // auto-generated
internal void RevertPermitOnly()
{
if (HasImperativeRestrictions())
{
DecrementOverridesCount();
m_restriction= null;;
}
}
[System.Security.SecurityCritical] // auto-generated
internal void RevertAll()
{
RevertAssert();
RevertAssertAllPossible();
RevertDeny();
RevertPermitOnly();
}
//-----------------------------------------------------------+
// Demand Evaluation
//-----------------------------------------------------------+
// This will get called when we hit a FSD while evaluating a demand on the call stack or compressedstack
[System.Security.SecurityCritical] // auto-generated
internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
{
// imperative security
bool fContinue = CheckDemand2(demand, permToken, rmh, false);
if (fContinue == SecurityRuntime.StackContinue)
{
// declarative security
fContinue = CheckDemand2(demand, permToken, rmh, true);
}
return fContinue;
}
[System.Security.SecurityCritical] // auto-generated
internal bool CheckDemand2(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh, bool fDeclarative)
{
PermissionSet permSet;
// If the demand is null, there is no need to continue
Contract.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point");
// decode imperative
if (GetPermitOnly(fDeclarative) != null)
GetPermitOnly(fDeclarative).CheckDecoded(demand, permToken);
if (GetDenials(fDeclarative) != null)
GetDenials(fDeclarative).CheckDecoded(demand, permToken);
if (GetAssertions(fDeclarative) != null)
GetAssertions(fDeclarative).CheckDecoded(demand, permToken);
// NOTE: See notes about exceptions and exception handling in FrameDescSetHelper
bool bThreadSecurity = SecurityManager._SetThreadSecurity(false);
// Check Reduction
try
{
permSet = GetPermitOnly(fDeclarative);
if (permSet != null)
{
CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand);
// If the permit only set does not contain the demanded permission, throw a security exception
if (perm == null)
{
if (!permSet.IsUnrestricted())
throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demand, demand);
}
else
{
bool bNeedToThrow = true;
try
{
bNeedToThrow = !demand.CheckPermitOnly(perm);
}
catch (ArgumentException)
{
}
if (bNeedToThrow)
throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demand, demand);
}
}
// Check Denials
permSet = GetDenials(fDeclarative);
if (permSet != null)
{
CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand);
// If an unrestricted set was denied and the demand implements IUnrestricted
if (permSet.IsUnrestricted())
throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demand, demand);
// If the deny set does contain the demanded permission, throw a security exception
bool bNeedToThrow = true;
try
{
bNeedToThrow = !demand.CheckDeny(perm);
}
catch (ArgumentException)
{
}
if (bNeedToThrow)
throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demand, demand);
}
if (GetAssertAllPossible())
{
return SecurityRuntime.StackHalt;
}
permSet = GetAssertions(fDeclarative);
// Check Assertions
if (permSet != null)
{
CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand);
// If the assert set does contain the demanded permission, halt the stackwalk
try
{
if (permSet.IsUnrestricted() || demand.CheckAssert(perm))
{
return SecurityRuntime.StackHalt;
}
}
catch (ArgumentException)
{
}
}
}
finally
{
if (bThreadSecurity)
SecurityManager._SetThreadSecurity(true);
}
return SecurityRuntime.StackContinue;
}
[System.Security.SecurityCritical] // auto-generated
internal bool CheckSetDemand(PermissionSet demandSet,
out PermissionSet alteredDemandSet,
RuntimeMethodHandleInternal rmh)
{
// imperative security
PermissionSet altPset1 = null, altPset2 = null;
bool fContinue = CheckSetDemand2(demandSet, out altPset1, rmh, false);
if (altPset1 != null)
{
demandSet = altPset1;
}
if (fContinue == SecurityRuntime.StackContinue)
{
// declarative security
fContinue = CheckSetDemand2(demandSet, out altPset2, rmh, true);
}
// Return the most recent altered set
// If both declarative and imperative asserts modified the demand set: return altPset2
// Else if imperative asserts modified the demand set: return altPset1
// else no alteration: return null
if (altPset2 != null)
alteredDemandSet = altPset2;
else if (altPset1 != null)
alteredDemandSet = altPset1;
else
alteredDemandSet = null;
return fContinue;
}
[System.Security.SecurityCritical] // auto-generated
internal bool CheckSetDemand2(PermissionSet demandSet,
out PermissionSet alteredDemandSet,
RuntimeMethodHandleInternal rmh, bool fDeclarative)
{
PermissionSet permSet;
// In the common case we are not going to alter the demand set, so just to
// be safe we'll set it to null up front.
alteredDemandSet = null;
// There's some oddness in here to deal with exceptions. The general idea behind
// this is that we need some way of dealing with custom permissions that may not
// handle all possible scenarios of Union(), Intersect(), and IsSubsetOf() properly
// (they don't support it, throw null reference exceptions, etc.).
// An empty demand always succeeds.
if (demandSet == null || demandSet.IsEmpty())
return SecurityRuntime.StackHalt;
if (GetPermitOnly(fDeclarative) != null)
GetPermitOnly(fDeclarative).CheckDecoded( demandSet );
if (GetDenials(fDeclarative) != null)
GetDenials(fDeclarative).CheckDecoded( demandSet );
if (GetAssertions(fDeclarative) != null)
GetAssertions(fDeclarative).CheckDecoded( demandSet );
bool bThreadSecurity = SecurityManager._SetThreadSecurity(false);
try
{
// In the case of permit only, we define an exception to be failure of the check
// and therefore we throw a security exception.
permSet = GetPermitOnly(fDeclarative);
if (permSet != null)
{
IPermission permFailed = null;
bool bNeedToThrow = true;
try
{
bNeedToThrow = !demandSet.CheckPermitOnly(permSet, out permFailed);
}
catch (ArgumentException)
{
}
if (bNeedToThrow)
throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demandSet, permFailed);
}
// In the case of denial, we define an exception to be failure of the check
// and therefore we throw a security exception.
permSet = GetDenials(fDeclarative);
if (permSet != null)
{
IPermission permFailed = null;
bool bNeedToThrow = true;
try
{
bNeedToThrow = !demandSet.CheckDeny(permSet, out permFailed);
}
catch (ArgumentException)
{
}
if (bNeedToThrow)
throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demandSet, permFailed);
}
// The assert case is more complex. Since asserts have the ability to "bleed through"
// (where part of a demand is handled by an assertion, but the rest is passed on to
// continue the stackwalk), we need to be more careful in handling the "failure" case.
// Therefore, if an exception is thrown in performing any operation, we make sure to keep
// that permission in the demand set thereby continuing the demand for that permission
// walking down the stack.
if (GetAssertAllPossible())
{
return SecurityRuntime.StackHalt;
}
permSet = GetAssertions(fDeclarative);
if (permSet != null)
{
// If this frame asserts a superset of the demand set we're done
if (demandSet.CheckAssertion( permSet ))
return SecurityRuntime.StackHalt;
// Determine whether any of the demand set asserted. We do this by
// copying the demand set and removing anything in it that is asserted.
if (!permSet.IsUnrestricted())
{
PermissionSet.RemoveAssertedPermissionSet(demandSet, permSet, out alteredDemandSet);
}
}
}
finally
{
if (bThreadSecurity)
SecurityManager._SetThreadSecurity(true);
}
return SecurityRuntime.StackContinue;
}
}
#if FEATURE_COMPRESSEDSTACK
// Used by the stack compressor to communicate a DynamicResolver to managed code during a stackwalk.
// The JIT will not actually place these on frames.
internal class FrameSecurityDescriptorWithResolver : FrameSecurityDescriptor
{
private System.Reflection.Emit.DynamicResolver m_resolver;
public System.Reflection.Emit.DynamicResolver Resolver
{
get
{
return m_resolver;
}
}
}
#endif // FEATURE_COMPRESSEDSTACK
}
| |
//
// Mono.VisualC.Interop.CppType.cs: Abstracts a C++ type declaration
//
// Author:
// Alexander Corrado (alexander.corrado@gmail.com)
// Andreia Gaita (shana@spoiledcat.net)
//
// Copyright (C) 2010 Alexander Corrado
//
// 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.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Collections.Generic;
using Mono.VisualC.Interop.Util;
namespace Mono.VisualC.Interop {
// These can be used anywhere a CppType could be used.
public enum CppTypes {
Unknown,
Class,
Struct,
Enum,
Union,
Void,
Bool,
Char,
Int,
Float,
Double,
WChar_T,
// for template type parameters
Typename
}
public struct CppType {
// FIXME: Passing these as delegates allows for the flexibility of doing processing on the
// type (i.e. to correctly mangle the function pointer arguments if the managed type is a delegate),
// however this does not make it very easy to override the default mappings at runtime.
public static List<Func<CppType,Type>> CppTypeToManagedMap = new List<Func<CppType, Type>> () {
(t) => (t.ElementType == CppTypes.Class ||
t.ElementType == CppTypes.Struct ||
(t.ElementType == CppTypes.Unknown && t.ElementTypeName != null)) &&
(t.Modifiers.Count (m => m == CppModifiers.Pointer) == 1 ||
t.Modifiers.Contains (CppModifiers.Reference))? typeof (ICppObject) : null,
// void* gets IntPtr
(t) => t.ElementType == CppTypes.Void && t.Modifiers.Contains (CppModifiers.Pointer)? typeof (IntPtr) : null,
// single pointer to char gets string
// same with wchar_t (needs marshaling attribute though!)
(t) => (t.ElementType == CppTypes.Char || t.ElementType == CppTypes.WChar_T) && t.Modifiers.Count (m => m == CppModifiers.Pointer) == 1? typeof (string) : null,
// pointer to pointer to char gets string[]
(t) => t.ElementType == CppTypes.Char && t.Modifiers.Count (m => m == CppModifiers.Pointer) == 2? typeof (string).MakeArrayType () : null,
// arrays
(t) => t.Modifiers.Contains (CppModifiers.Array) && (t.Subtract (CppModifiers.Array).ToManagedType () != null)? t.Subtract (CppModifiers.Array).ToManagedType ().MakeArrayType () : null,
// convert single pointers to primatives to managed byref
(t) => t.Modifiers.Count (m => m == CppModifiers.Pointer) == 1 && (t.Subtract (CppModifiers.Pointer).ToManagedType () != null)? t.Subtract (CppModifiers.Pointer).ToManagedType ().MakeByRefType () : null,
// more than one level of indirection gets IntPtr type
(t) => t.Modifiers.Contains (CppModifiers.Pointer)? typeof (IntPtr) : null,
(t) => t.Modifiers.Contains (CppModifiers.Reference) && (t.Subtract (CppModifiers.Reference).ToManagedType () != null)? t.Subtract (CppModifiers.Reference).ToManagedType ().MakeByRefType () : null,
(t) => t.ElementType == CppTypes.Int && t.Modifiers.Contains (CppModifiers.Short) && t.Modifiers.Contains (CppModifiers.Unsigned)? typeof (ushort) : null,
(t) => t.ElementType == CppTypes.Int && t.Modifiers.Contains (CppModifiers.Long) && t.Modifiers.Contains (CppModifiers.Unsigned)? typeof (ulong) : null,
(t) => t.ElementType == CppTypes.Int && t.Modifiers.Contains (CppModifiers.Short)? typeof (short) : null,
(t) => t.ElementType == CppTypes.Int && t.Modifiers.Contains (CppModifiers.Long)? typeof (long) : null,
(t) => t.ElementType == CppTypes.Int && t.Modifiers.Contains (CppModifiers.Unsigned)? typeof (uint) : null,
(t) => t.ElementType == CppTypes.Void? typeof (void) : null,
(t) => t.ElementType == CppTypes.Bool? typeof (bool) : null,
(t) => t.ElementType == CppTypes.Char? typeof (char) : null,
(t) => t.ElementType == CppTypes.Int? typeof (int) : null,
(t) => t.ElementType == CppTypes.Float? typeof (float) : null,
(t) => t.ElementType == CppTypes.Double? typeof (double) : null
};
public static List<Func<Type,CppType>> ManagedToCppTypeMap = new List<Func<Type,CppType>> () {
(t) => typeof (void).Equals (t) ? CppTypes.Void : CppTypes.Unknown,
(t) => typeof (bool).Equals (t) ? CppTypes.Bool : CppTypes.Unknown,
(t) => typeof (char).Equals (t) ? CppTypes.Char : CppTypes.Unknown,
(t) => typeof (int).Equals (t) ? CppTypes.Int : CppTypes.Unknown,
(t) => typeof (float).Equals (t) ? CppTypes.Float : CppTypes.Unknown,
(t) => typeof (double).Equals (t)? CppTypes.Double : CppTypes.Unknown,
(t) => typeof (short).Equals (t) ? new CppType (CppModifiers.Short, CppTypes.Int) : CppTypes.Unknown,
(t) => typeof (long).Equals (t) ? new CppType (CppModifiers.Long, CppTypes.Int) : CppTypes.Unknown,
(t) => typeof (uint).Equals (t) ? new CppType (CppModifiers.Unsigned, CppTypes.Int) : CppTypes.Unknown,
(t) => typeof (ushort).Equals (t)? new CppType (CppModifiers.Unsigned, CppModifiers.Short, CppTypes.Int) : CppTypes.Unknown,
(t) => typeof (ulong).Equals (t)? new CppType (CppModifiers.Unsigned, CppModifiers.Long, CppTypes.Int) : CppTypes.Unknown,
// strings mangle as "const char*" by default
(t) => typeof (string).Equals (t)? new CppType (CppModifiers.Const, CppTypes.Char, CppModifiers.Pointer) : CppTypes.Unknown,
// StringBuilder gets "char*"
(t) => typeof (StringBuilder).Equals (t)? new CppType (CppTypes.Char, CppModifiers.Pointer) : CppTypes.Unknown,
// delegate types get special treatment
(t) => typeof (Delegate).IsAssignableFrom (t)? CppType.ForDelegate (t) : CppTypes.Unknown,
// ... and of course ICppObjects do too!
// FIXME: We assume c++ class not struct. There should probably be an attribute
// we can apply to managed wrappers to indicate if the underlying C++ type is actually declared struct
(t) => typeof (ICppObject).IsAssignableFrom (t)? new CppType (CppTypes.Class, t.Name, CppModifiers.Pointer) : CppTypes.Unknown,
// convert managed type modifiers to C++ type modifiers like so:
// ref types to C++ references
// pointer types to C++ pointers
// array types to C++ arrays
(t) => {
CppType cppType = CppType.ForManagedType (t.GetElementType ());
if (t.IsByRef) cppType.Modifiers.Add (CppModifiers.Reference);
if (t.IsPointer) cppType.Modifiers.Add (CppModifiers.Pointer);
if (t.IsArray) cppType.Modifiers.Add (CppModifiers.Array);
return cppType;
}
};
public CppTypes ElementType { get; set; }
// if the ElementType is Union, Struct, Class, or Enum
// this will contain the name of said type
public string ElementTypeName { get; set; }
// may be null, and will certainly be null if ElementTypeName is null
public string [] Namespaces { get; set; }
// this is initialized lazily to avoid unnecessary heap
// allocations if possible
private List<CppModifiers> internalModifiers;
public List<CppModifiers> Modifiers {
get {
if (internalModifiers == null)
internalModifiers = new List<CppModifiers> ();
return internalModifiers;
}
}
// here, you can pass in things like "const char*" or "const Foo * const"
// DISCLAIMER: this is really just for convenience for now, and is not meant to be able
// to parse even moderately complex C++ type declarations.
public CppType (string type) : this (Regex.Split (type, "\\s+(?![^\\>]*\\>|[^\\[\\]]*\\])"))
{
}
public CppType (params object[] cppTypeSpec) : this ()
{
ElementType = CppTypes.Unknown;
ElementTypeName = null;
Namespaces = null;
internalModifiers = null;
Parse (cppTypeSpec);
}
// FIXME: This makes no attempt to actually verify that the parts compose a valid C++ type.
private void Parse (object [] parts)
{
foreach (object part in parts) {
if (part is CppModifiers) {
Modifiers.Add ((CppModifiers)part);
continue;
}
if (part is CppModifiers []) {
Modifiers.AddRange ((CppModifiers [])part);
continue;
}
if (part is CppTypes) {
ElementType = (CppTypes)part;
continue;
}
Type managedType = part as Type;
if (managedType != null) {
CppType mapped = CppType.ForManagedType (managedType);
CopyTypeFrom (mapped);
continue;
}
string strPart = part as string;
if (strPart != null) {
var parsed = CppModifiers.Parse (strPart);
if (parsed.Count > 0) {
if (internalModifiers == null)
internalModifiers = parsed;
else
internalModifiers.AddRange (parsed);
strPart = CppModifiers.Remove (strPart);
}
// if we have something left, it must be a type name
strPart = strPart.Trim ();
if (strPart != "") {
string [] qualifiedName = strPart.Split (new string [] { "::" }, StringSplitOptions.RemoveEmptyEntries);
int numNamespaces = qualifiedName.Length - 1;
if (numNamespaces > 0) {
Namespaces = new string [numNamespaces];
for (int i = 0; i < numNamespaces; i++)
Namespaces [i] = qualifiedName [i];
}
strPart = qualifiedName [numNamespaces];
// FIXME: Fix this mess
switch (strPart) {
case "void":
ElementType = CppTypes.Void;
break;
case "bool":
ElementType = CppTypes.Bool;
break;
case "char":
ElementType = CppTypes.Char;
break;
case "int":
ElementType = CppTypes.Int;
break;
case "float":
ElementType = CppTypes.Float;
break;
case "double":
ElementType = CppTypes.Double;
break;
default:
// otherwise it is the element type name...
ElementTypeName = strPart;
break;
}
}
}
}
}
// Applies the element type of the passed instance
// and combines its modifiers into this instance.
// Use when THIS instance may have attributes you want,
// but want the element type of the passed instance.
public CppType CopyTypeFrom (CppType type)
{
ElementType = type.ElementType;
ElementTypeName = type.ElementTypeName;
Namespaces = type.Namespaces;
List<CppModifiers> oldModifiers = internalModifiers;
internalModifiers = type.internalModifiers;
if (oldModifiers != null)
Modifiers.AddRange (oldModifiers);
return this;
}
// Removes the modifiers on the passed instance from this instance
public CppType Subtract (CppType type)
{
if (internalModifiers == null)
return this;
CppType current = this;
foreach (var modifier in ((IEnumerable<CppModifiers>)type.Modifiers).Reverse ())
current = current.Subtract (modifier);
return current;
}
public CppType Subtract (CppModifiers modifier)
{
CppType newType = this;
newType.internalModifiers = new List<CppModifiers> (((IEnumerable<CppModifiers>)newType.Modifiers).Reverse ().WithoutFirst (modifier));
return newType;
}
// note: this adds modifiers "backwards" (it is mainly used by the generator)
public CppType Modify (CppModifiers modifier)
{
CppType newType = this;
var newModifier = new CppModifiers [] { modifier };
if (newType.internalModifiers != null)
newType.internalModifiers.AddFirst (newModifier);
else
newType.internalModifiers = new List<CppModifiers> (newModifier);
return newType;
}
public override bool Equals (object obj)
{
if (obj == null)
return false;
if (obj.GetType () == typeof (CppTypes))
return Equals (new CppType (obj));
if (obj.GetType () != typeof (CppType))
return false;
CppType other = (CppType)obj;
return (((internalModifiers == null || !internalModifiers.Any ()) &&
(other.internalModifiers == null || !other.internalModifiers.Any ())) ||
(internalModifiers != null && other.internalModifiers != null &&
CppModifiers.NormalizeOrder (internalModifiers).SequenceEqual (CppModifiers.NormalizeOrder (other.internalModifiers)))) &&
(((Namespaces == null || !Namespaces.Any ()) &&
(other.Namespaces == null || !other.Namespaces.Any ())) ||
(Namespaces != null && other.Namespaces != null &&
Namespaces.SequenceEqual (other.Namespaces))) &&
ElementType == other.ElementType &&
ElementTypeName == other.ElementTypeName;
}
public override int GetHashCode ()
{
unchecked {
return (internalModifiers != null? internalModifiers.SequenceHashCode () : 0) ^
ElementType.GetHashCode () ^
(Namespaces != null? Namespaces.SequenceHashCode () : 0) ^
(ElementTypeName != null? ElementTypeName.GetHashCode () : 0);
}
}
public override string ToString ()
{
StringBuilder cppTypeString = new StringBuilder ();
if (ElementType != CppTypes.Unknown && ElementType != CppTypes.Typename)
cppTypeString.Append (Enum.GetName (typeof (CppTypes), ElementType).ToLower ()).Append (' ');
if (Namespaces != null) {
foreach (var ns in Namespaces)
cppTypeString.Append (ns).Append ("::");
}
if (ElementTypeName != null && ElementType != CppTypes.Typename)
cppTypeString.Append (ElementTypeName);
if (internalModifiers != null) {
foreach (var modifier in internalModifiers)
cppTypeString.Append (' ').Append (modifier.ToString ());
}
return cppTypeString.ToString ().Trim ();
}
public Type ToManagedType ()
{
CppType me = this;
Type mappedType = (from checkType in CppTypeToManagedMap
where checkType (me) != null
select checkType (me)).FirstOrDefault ();
return mappedType;
}
public static CppType ForManagedType (Type type)
{
CppType mappedType = (from checkType in ManagedToCppTypeMap
where checkType (type).ElementType != CppTypes.Unknown
select checkType (type)).FirstOrDefault ();
return mappedType;
}
public static CppType ForDelegate (Type delType)
{
if (!typeof (Delegate).IsAssignableFrom (delType))
throw new ArgumentException ("Argument must be a delegate type");
throw new NotImplementedException ();
}
public static implicit operator CppType (CppTypes type) {
return new CppType (type);
}
}
}
| |
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using Intel.UPNP;
namespace UPnPStackBuilder
{
/// <summary>
/// Summary description for CodeGenerationForm.
/// </summary>
public class CPCodeGenerationForm : System.Windows.Forms.Form
{
private System.ComponentModel.IContainer components;
private UPnPDevice device;
private Hashtable serviceNames;
private Hashtable stackSettings;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TextBox libPrefixTextBox;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox classNameTextBox;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.ComboBox indentComboBox;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox prefixTextBox;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.ComboBox callConventionComboBox;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ComboBox newLineComboBox;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox languageComboBox;
private System.Windows.Forms.ComboBox platformComboBox;
private System.Windows.Forms.Button outputDirectoryButton;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TextBox outputPathTextBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button generateButton;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.TextBox genOutputTextBox;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.TextBox licenseTextBox;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.GroupBox groupBox1;
private System.Data.DataSet dataSet1;
private System.Data.DataTable dataTable1;
private System.Data.DataColumn dataColumn1;
private System.Data.DataColumn dataColumn2;
private System.Windows.Forms.CheckBox SampleApplication;
private System.Windows.Forms.CheckBox HTTP;
private System.Windows.Forms.CheckBox IPAddressMonitor;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.DataGrid dataGrid1;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.CheckBox UPnP1dot1Enabled;
private ArrayList FragResponseActions;
private ArrayList EscapeActions;
public CPCodeGenerationForm(UPnPDevice device, Hashtable serviceNames, Hashtable stackSettings, ArrayList FragResponseActions, ArrayList EscapeActions)
{
InitializeComponent();
platformComboBox.SelectedIndex = 0;
languageComboBox.SelectedIndex = 0;
newLineComboBox.SelectedIndex = 0;
indentComboBox.SelectedIndex = 0;
callConventionComboBox.SelectedIndex = 0;
this.device = device;
this.serviceNames = serviceNames;
this.stackSettings = stackSettings;
this.FragResponseActions = FragResponseActions;
this.EscapeActions = EscapeActions;
}
public Hashtable Settings
{
get
{
Hashtable t = new Hashtable();
t["outputpath"] = outputPathTextBox.Text;
t["platform"] = platformComboBox.SelectedIndex;
t["language"] = languageComboBox.SelectedIndex;
t["newline"] = newLineComboBox.SelectedIndex;
t["callconvention"] = callConventionComboBox.SelectedIndex;
t["prefix"] = prefixTextBox.Text;
t["prefixlib"] = libPrefixTextBox.Text;
t["indent"] = indentComboBox.SelectedIndex;
t["classname"] = classNameTextBox.Text;
t["IPAddressMonitor"] = IPAddressMonitor.Checked;
t["HTTP11Support"] = this.HTTP.Checked;
t["SupressSample"] = !SampleApplication.Checked;
Hashtable cf = new Hashtable();
foreach(System.Data.DataRow r in dataSet1.Tables[0].Rows)
{
cf.Add((string)r.ItemArray[0],(string)r.ItemArray[1]);
}
t["CustomFields"] = cf;
return t;
}
set
{
if (value.Contains("outputpath")) outputPathTextBox.Text = (string)value["outputpath"];
if (value.Contains("platform")) platformComboBox.SelectedIndex = (int)value["platform"];
if (value.Contains("language")) languageComboBox.SelectedIndex = (int)value["language"];
if (value.Contains("newline")) newLineComboBox.SelectedIndex = (int)value["newline"];
if (value.Contains("callconvention")) callConventionComboBox.SelectedIndex = (int)value["callconvention"];
if (value.Contains("prefix")) prefixTextBox.Text = (string)value["prefix"];
if (value.Contains("prefixlib")) libPrefixTextBox.Text = (string)value["prefixlib"];
if (value.Contains("indent")) indentComboBox.SelectedIndex = (int)value["indent"];
if (value.Contains("classname")) classNameTextBox.Text = (string)value["classname"];
if (value.Contains("IPAddressMonitor")) IPAddressMonitor.Checked = (bool)value["IPAddressMonitor"];
if (value.Contains("HTTP11Support")) HTTP.Checked = (bool)value["HTTP11Support"];
if (value.Contains("SupressSample")) {SampleApplication.Checked = !(bool)value["SupressSample"];}
if (value.Contains("CustomFields"))
{
dataSet1.Tables[0].Clear();
IDictionaryEnumerator e = ((Hashtable)value["CustomFields"]).GetEnumerator();
while(e.MoveNext())
{
dataSet1.Tables[0].Rows.Add(new object[2]{e.Key,e.Value});
}
}
classNameTextBox.Enabled = (languageComboBox.SelectedIndex == 1);
}
}
/// <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.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(CPCodeGenerationForm));
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.libPrefixTextBox = new System.Windows.Forms.TextBox();
this.classNameTextBox = new System.Windows.Forms.TextBox();
this.indentComboBox = new System.Windows.Forms.ComboBox();
this.prefixTextBox = new System.Windows.Forms.TextBox();
this.callConventionComboBox = new System.Windows.Forms.ComboBox();
this.newLineComboBox = new System.Windows.Forms.ComboBox();
this.languageComboBox = new System.Windows.Forms.ComboBox();
this.platformComboBox = new System.Windows.Forms.ComboBox();
this.outputPathTextBox = new System.Windows.Forms.TextBox();
this.UPnP1dot1Enabled = new System.Windows.Forms.CheckBox();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.generateButton = new System.Windows.Forms.Button();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.outputDirectoryButton = new System.Windows.Forms.Button();
this.label10 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label17 = new System.Windows.Forms.Label();
this.dataGrid1 = new System.Windows.Forms.DataGrid();
this.dataSet1 = new System.Data.DataSet();
this.dataTable1 = new System.Data.DataTable();
this.dataColumn1 = new System.Data.DataColumn();
this.dataColumn2 = new System.Data.DataColumn();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.SampleApplication = new System.Windows.Forms.CheckBox();
this.HTTP = new System.Windows.Forms.CheckBox();
this.IPAddressMonitor = new System.Windows.Forms.CheckBox();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.licenseTextBox = new System.Windows.Forms.TextBox();
this.label14 = new System.Windows.Forms.Label();
this.genOutputTextBox = new System.Windows.Forms.TextBox();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage3.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataTable1)).BeginInit();
this.groupBox1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.SuspendLayout();
//
// libPrefixTextBox
//
this.libPrefixTextBox.Location = new System.Drawing.Point(131, 178);
this.libPrefixTextBox.Name = "libPrefixTextBox";
this.libPrefixTextBox.Size = new System.Drawing.Size(355, 20);
this.libPrefixTextBox.TabIndex = 51;
this.libPrefixTextBox.Text = "ILib";
this.toolTip1.SetToolTip(this.libPrefixTextBox, "This string prefixes every generated method of common libraries (Parsers, HTTP, S" +
"SDP...)");
//
// classNameTextBox
//
this.classNameTextBox.Enabled = false;
this.classNameTextBox.Location = new System.Drawing.Point(131, 234);
this.classNameTextBox.Name = "classNameTextBox";
this.classNameTextBox.Size = new System.Drawing.Size(355, 20);
this.classNameTextBox.TabIndex = 49;
this.classNameTextBox.Text = "Intel.DeviceBuilder";
this.toolTip1.SetToolTip(this.classNameTextBox, "When generating .net code, the namespace used to wrap the generated control point" +
" stack.");
//
// indentComboBox
//
this.indentComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.indentComboBox.Items.AddRange(new object[] {
"1 Tab",
"1 Space",
"2 Spaces",
"3 Spaces",
"4 Spaces",
"5 Spaces",
"6 Spaces"});
this.indentComboBox.Location = new System.Drawing.Point(131, 205);
this.indentComboBox.Name = "indentComboBox";
this.indentComboBox.Size = new System.Drawing.Size(355, 21);
this.indentComboBox.TabIndex = 47;
this.toolTip1.SetToolTip(this.indentComboBox, "Code indentation setting.");
//
// prefixTextBox
//
this.prefixTextBox.Location = new System.Drawing.Point(131, 150);
this.prefixTextBox.Name = "prefixTextBox";
this.prefixTextBox.Size = new System.Drawing.Size(355, 20);
this.prefixTextBox.TabIndex = 45;
this.prefixTextBox.Text = "UPnP";
this.toolTip1.SetToolTip(this.prefixTextBox, "This string prefixes every generated action. It can be used like a namespace in C" +
".");
//
// callConventionComboBox
//
this.callConventionComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.callConventionComboBox.Items.AddRange(new object[] {
"None - Compiler default calling convention",
"_stdcall - Standard C and C++ calling convention",
"_fastcall - Register passing calling convention"});
this.callConventionComboBox.Location = new System.Drawing.Point(131, 121);
this.callConventionComboBox.Name = "callConventionComboBox";
this.callConventionComboBox.Size = new System.Drawing.Size(355, 21);
this.callConventionComboBox.TabIndex = 43;
this.toolTip1.SetToolTip(this.callConventionComboBox, "This setting can be used to force all generated methods to be implemented with a " +
"given calling convention. _fastcall may lead to smaller and faster code.");
//
// newLineComboBox
//
this.newLineComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.newLineComboBox.Items.AddRange(new object[] {
"CR+LF, Windows style code",
"LF, UNIX style code"});
this.newLineComboBox.Location = new System.Drawing.Point(131, 94);
this.newLineComboBox.Name = "newLineComboBox";
this.newLineComboBox.Size = new System.Drawing.Size(355, 21);
this.newLineComboBox.TabIndex = 41;
this.toolTip1.SetToolTip(this.newLineComboBox, "The type of newline used to generate the code. On UNIX style platforms, using CR+" +
"LF may lead to a compilable stack that will not function correctly.");
//
// languageComboBox
//
this.languageComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.languageComboBox.Items.AddRange(new object[] {
"C (Flat Interface)"});
this.languageComboBox.Location = new System.Drawing.Point(131, 37);
this.languageComboBox.Name = "languageComboBox";
this.languageComboBox.Size = new System.Drawing.Size(355, 21);
this.languageComboBox.TabIndex = 38;
this.toolTip1.SetToolTip(this.languageComboBox, "Target language. Both C and C++ will generate flat interfaces, but C++ is sometim" +
"es favored in some projects & environements.");
this.languageComboBox.Click += new System.EventHandler(this.languageComboBox_SelectedIndexChanged);
//
// platformComboBox
//
this.platformComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.platformComboBox.Items.AddRange(new object[] {
"Intel C Stack - POSIX, Linux (Standard Sockets)",
"Intel C Stack - Windows 95,98,NT,XP (WinSock1)",
"Intel C Stack - Windows 98,NT,XP (WinSock2)",
"Intel C Stack - PocketPC 2002/2003 (WinSock1)",
"Intel .NET Framework Stack (C#)"});
this.platformComboBox.Location = new System.Drawing.Point(131, 9);
this.platformComboBox.Name = "platformComboBox";
this.platformComboBox.Size = new System.Drawing.Size(355, 21);
this.platformComboBox.TabIndex = 36;
this.toolTip1.SetToolTip(this.platformComboBox, "Target platform for generated code.");
this.platformComboBox.SelectedIndexChanged += new System.EventHandler(this.platformComboBox_SelectedIndexChanged);
//
// outputPathTextBox
//
this.outputPathTextBox.Location = new System.Drawing.Point(131, 65);
this.outputPathTextBox.Name = "outputPathTextBox";
this.outputPathTextBox.Size = new System.Drawing.Size(315, 20);
this.outputPathTextBox.TabIndex = 33;
this.outputPathTextBox.Text = "C:\\Temp2";
this.toolTip1.SetToolTip(this.outputPathTextBox, "The output path of the generated files. Generated files will overwrite existing f" +
"iles without prompting.");
//
// UPnP1dot1Enabled
//
this.UPnP1dot1Enabled.Location = new System.Drawing.Point(8, 24);
this.UPnP1dot1Enabled.Name = "UPnP1dot1Enabled";
this.UPnP1dot1Enabled.Size = new System.Drawing.Size(448, 16);
this.UPnP1dot1Enabled.TabIndex = 33;
this.UPnP1dot1Enabled.Text = "UPnP/1.1 Support (UPnP/1.0 Support if unchecked)";
this.toolTip1.SetToolTip(this.UPnP1dot1Enabled, "This box will add UPnP/1.1 support to the total code size of the generated stack." +
"");
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Location = new System.Drawing.Point(9, 9);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(505, 343);
this.tabControl1.TabIndex = 33;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.generateButton);
this.tabPage1.Controls.Add(this.libPrefixTextBox);
this.tabPage1.Controls.Add(this.label8);
this.tabPage1.Controls.Add(this.classNameTextBox);
this.tabPage1.Controls.Add(this.label7);
this.tabPage1.Controls.Add(this.indentComboBox);
this.tabPage1.Controls.Add(this.label6);
this.tabPage1.Controls.Add(this.prefixTextBox);
this.tabPage1.Controls.Add(this.label5);
this.tabPage1.Controls.Add(this.callConventionComboBox);
this.tabPage1.Controls.Add(this.label4);
this.tabPage1.Controls.Add(this.newLineComboBox);
this.tabPage1.Controls.Add(this.label3);
this.tabPage1.Controls.Add(this.languageComboBox);
this.tabPage1.Controls.Add(this.platformComboBox);
this.tabPage1.Controls.Add(this.outputDirectoryButton);
this.tabPage1.Controls.Add(this.label10);
this.tabPage1.Controls.Add(this.outputPathTextBox);
this.tabPage1.Controls.Add(this.label1);
this.tabPage1.Controls.Add(this.label2);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Size = new System.Drawing.Size(497, 317);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "General";
//
// generateButton
//
this.generateButton.Dock = System.Windows.Forms.DockStyle.Bottom;
this.generateButton.Location = new System.Drawing.Point(0, 279);
this.generateButton.Name = "generateButton";
this.generateButton.Size = new System.Drawing.Size(497, 38);
this.generateButton.TabIndex = 52;
this.generateButton.Text = "Click Here To Generate a Control Point Stack";
this.generateButton.Click += new System.EventHandler(this.generateButton_Click);
//
// label8
//
this.label8.Location = new System.Drawing.Point(9, 182);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(122, 14);
this.label8.TabIndex = 50;
this.label8.Text = "Library Code Prefix";
//
// label7
//
this.label7.Location = new System.Drawing.Point(9, 238);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(122, 14);
this.label7.TabIndex = 48;
this.label7.Text = "Namespace";
//
// label6
//
this.label6.Location = new System.Drawing.Point(9, 209);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(122, 19);
this.label6.TabIndex = 46;
this.label6.Text = "Code Indention";
//
// label5
//
this.label5.Location = new System.Drawing.Point(9, 154);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(122, 18);
this.label5.TabIndex = 44;
this.label5.Text = "Code Prefix";
//
// label4
//
this.label4.Location = new System.Drawing.Point(9, 125);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(122, 15);
this.label4.TabIndex = 42;
this.label4.Text = "Calling Convention";
//
// label3
//
this.label3.Location = new System.Drawing.Point(9, 98);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(112, 18);
this.label3.TabIndex = 40;
this.label3.Text = "New Line Format";
//
// outputDirectoryButton
//
this.outputDirectoryButton.Image = ((System.Drawing.Image)(resources.GetObject("outputDirectoryButton.Image")));
this.outputDirectoryButton.Location = new System.Drawing.Point(455, 65);
this.outputDirectoryButton.Name = "outputDirectoryButton";
this.outputDirectoryButton.Size = new System.Drawing.Size(29, 25);
this.outputDirectoryButton.TabIndex = 35;
this.outputDirectoryButton.Click += new System.EventHandler(this.outputDirectoryButton_Click);
//
// label10
//
this.label10.Location = new System.Drawing.Point(9, 69);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(75, 15);
this.label10.TabIndex = 34;
this.label10.Text = "Output Path";
//
// label1
//
this.label1.Location = new System.Drawing.Point(9, 13);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(103, 15);
this.label1.TabIndex = 37;
this.label1.Text = "Target Platform";
//
// label2
//
this.label2.Location = new System.Drawing.Point(9, 41);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(112, 19);
this.label2.TabIndex = 39;
this.label2.Text = "Target Language";
//
// tabPage3
//
this.tabPage3.Controls.Add(this.groupBox2);
this.tabPage3.Controls.Add(this.groupBox1);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Size = new System.Drawing.Size(497, 317);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Advanced";
this.tabPage3.Click += new System.EventHandler(this.tabPage3_Click);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.label17);
this.groupBox2.Controls.Add(this.dataGrid1);
this.groupBox2.Location = new System.Drawing.Point(8, 112);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(480, 200);
this.groupBox2.TabIndex = 5;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Custom Tags";
//
// label17
//
this.label17.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label17.Location = new System.Drawing.Point(8, 16);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(464, 40);
this.label17.TabIndex = 6;
this.label17.Text = @"This tab is used to add custom XML tag support to a control point stack. For example: Adding ""X_DLNADOC"" to the FieldName and ""urn:schemas-dlna.org:device-1-0"" to the FieldNameSpace will add support for detecting if such a tag exists in discovered devices.";
//
// dataGrid1
//
this.dataGrid1.CaptionVisible = false;
this.dataGrid1.DataMember = "Table1";
this.dataGrid1.DataSource = this.dataSet1;
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(8, 64);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.PreferredColumnWidth = 210;
this.dataGrid1.Size = new System.Drawing.Size(464, 128);
this.dataGrid1.TabIndex = 5;
//
// dataSet1
//
this.dataSet1.DataSetName = "NewDataSet";
this.dataSet1.Locale = new System.Globalization.CultureInfo("en-US");
this.dataSet1.Tables.AddRange(new System.Data.DataTable[] {
this.dataTable1});
//
// dataTable1
//
this.dataTable1.Columns.AddRange(new System.Data.DataColumn[] {
this.dataColumn1,
this.dataColumn2});
this.dataTable1.TableName = "Table1";
//
// dataColumn1
//
this.dataColumn1.AllowDBNull = false;
this.dataColumn1.ColumnName = "FieldName";
this.dataColumn1.DefaultValue = "";
//
// dataColumn2
//
this.dataColumn2.AllowDBNull = false;
this.dataColumn2.ColumnName = "FieldNameSpace";
this.dataColumn2.DefaultValue = "";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.UPnP1dot1Enabled);
this.groupBox1.Controls.Add(this.SampleApplication);
this.groupBox1.Controls.Add(this.HTTP);
this.groupBox1.Controls.Add(this.IPAddressMonitor);
this.groupBox1.Location = new System.Drawing.Point(8, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(480, 96);
this.groupBox1.TabIndex = 3;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Control Point Setup";
//
// SampleApplication
//
this.SampleApplication.Checked = true;
this.SampleApplication.CheckState = System.Windows.Forms.CheckState.Checked;
this.SampleApplication.Location = new System.Drawing.Point(8, 72);
this.SampleApplication.Name = "SampleApplication";
this.SampleApplication.Size = new System.Drawing.Size(464, 16);
this.SampleApplication.TabIndex = 5;
this.SampleApplication.Text = "Generate Sample Application";
//
// HTTP
//
this.HTTP.Location = new System.Drawing.Point(8, 40);
this.HTTP.Name = "HTTP";
this.HTTP.Size = new System.Drawing.Size(464, 16);
this.HTTP.TabIndex = 4;
this.HTTP.Text = "HTTP/1.1 Support (HTTP/1.0 Support if unchecked)";
//
// IPAddressMonitor
//
this.IPAddressMonitor.Location = new System.Drawing.Point(8, 56);
this.IPAddressMonitor.Name = "IPAddressMonitor";
this.IPAddressMonitor.Size = new System.Drawing.Size(464, 16);
this.IPAddressMonitor.TabIndex = 3;
this.IPAddressMonitor.Text = "Add default network interface monitoring code to sample application";
//
// tabPage2
//
this.tabPage2.Controls.Add(this.licenseTextBox);
this.tabPage2.Controls.Add(this.label14);
this.tabPage2.Controls.Add(this.genOutputTextBox);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Size = new System.Drawing.Size(497, 317);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Generator Log";
//
// licenseTextBox
//
this.licenseTextBox.Location = new System.Drawing.Point(18, 37);
this.licenseTextBox.Multiline = true;
this.licenseTextBox.Name = "licenseTextBox";
this.licenseTextBox.Size = new System.Drawing.Size(459, 253);
this.licenseTextBox.TabIndex = 43;
this.licenseTextBox.Text = @"/*
* INTEL CONFIDENTIAL
* Copyright (c) 2002, 2003 Intel Corporation. All rights reserved.
*
* The source code contained or described herein and all documents
* related to the source code (""Material"") are owned by Intel
* Corporation or its suppliers or licensors. Title to the
* Material remains with Intel Corporation or its suppliers and
* licensors. The Material contains trade secrets and proprietary
* and confidential information of Intel or its suppliers and
* licensors. The Material is protected by worldwide copyright and
* trade secret laws and treaty provisions. No part of the Material
* may be used, copied, reproduced, modified, published, uploaded,
* posted, transmitted, distributed, or disclosed in any way without
* Intel's prior express written permission.
* No license under any patent, copyright, trade secret or other
* intellectual property right is granted to or conferred upon you
* by disclosure or delivery of the Materials, either expressly, by
* implication, inducement, estoppel or otherwise. Any license
* under such intellectual property rights must be express and
* approved by Intel in writing.
*
* $Workfile: <FILE>
* $Revision: <REVISION>
* $Author: <AUTHOR>
* $Date: <DATE>
*
*/";
this.licenseTextBox.Visible = false;
//
// label14
//
this.label14.Location = new System.Drawing.Point(9, 9);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(178, 19);
this.label14.TabIndex = 16;
this.label14.Text = "Code Generation Output";
//
// genOutputTextBox
//
this.genOutputTextBox.Location = new System.Drawing.Point(9, 28);
this.genOutputTextBox.Multiline = true;
this.genOutputTextBox.Name = "genOutputTextBox";
this.genOutputTextBox.ReadOnly = true;
this.genOutputTextBox.Size = new System.Drawing.Size(477, 271);
this.genOutputTextBox.TabIndex = 13;
this.genOutputTextBox.Text = "";
//
// CPCodeGenerationForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(520, 356);
this.Controls.Add(this.tabControl1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "CPCodeGenerationForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Control Point Stack Code Generation";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage3.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataTable1)).EndInit();
this.groupBox1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public void generateButton_Click(object sender, System.EventArgs e)
{
DirectoryInfo outputDir = new DirectoryInfo(outputPathTextBox.Text);
if (outputDir.Exists == false)
{
MessageBox.Show(this,"Output Path is invalid","Code Generator");
return;
}
string buttonText = generateButton.Text;
generateButton.Text = "Generating Stack...";
generateButton.Enabled = false;
if(UPnP1dot1Enabled.Checked==true)
{
device.ArchitectureVersion = "1.1";
}
else
{
device.ArchitectureVersion = "1.0";
}
if(platformComboBox.SelectedIndex==4)
{
// .net
CPDotNetGenerator gen = new CPDotNetGenerator(classNameTextBox.Text);
genOutputTextBox.Clear();
gen.VersionString = "Intel StackBuilder Build#" + Application.ProductVersion;
gen.StartupPath = Application.StartupPath;
gen.OnLogOutput += new CPDotNetGenerator.LogOutputHandler(Log);
try
{
gen.Generate(device,outputDir,serviceNames);
}
catch
{
MessageBox.Show(this,"Error Generating Code","Code Generator");
}
gen.OnLogOutput -= new CPDotNetGenerator.LogOutputHandler(Log);
}
else
{
CPEmbeddedCGenerator gen = new CPEmbeddedCGenerator();
LibraryGenerator libgen = new LibraryGenerator();
genOutputTextBox.Clear();
gen.EnableDefaultIPAddressMonitor = IPAddressMonitor.Checked;
switch (platformComboBox.SelectedIndex)
{
case 0:
gen.Platform = CPEmbeddedCGenerator.PLATFORMS.POSIX;
gen.SubTarget = CPEmbeddedCGenerator.SUBTARGETS.NONE;
libgen.Platform = LibraryGenerator.PLATFORMS.POSIX;
libgen.SubTarget = LibraryGenerator.SUBTARGETS.NONE;
break;
case 1:
gen.Platform = CPEmbeddedCGenerator.PLATFORMS.WINDOWS;
gen.SubTarget = CPEmbeddedCGenerator.SUBTARGETS.NONE;
gen.WinSock = 1;
libgen.Platform = LibraryGenerator.PLATFORMS.WINDOWS;
libgen.SubTarget = LibraryGenerator.SUBTARGETS.NONE;
libgen.WinSock = 1;
break;
case 2:
gen.Platform = CPEmbeddedCGenerator.PLATFORMS.WINDOWS;
gen.SubTarget = CPEmbeddedCGenerator.SUBTARGETS.NONE;
gen.WinSock = 2;
libgen.Platform = LibraryGenerator.PLATFORMS.WINDOWS;
libgen.SubTarget = LibraryGenerator.SUBTARGETS.NONE;
libgen.WinSock = 2;
break;
case 3:
gen.Platform = CPEmbeddedCGenerator.PLATFORMS.WINDOWS;
gen.SubTarget = CPEmbeddedCGenerator.SUBTARGETS.PPC2003;
gen.WinSock = 1;
libgen.Platform = LibraryGenerator.PLATFORMS.WINDOWS;
libgen.SubTarget = LibraryGenerator.SUBTARGETS.PPC2003;
libgen.WinSock = 1;
break;
case 4:
gen.Platform = CPEmbeddedCGenerator.PLATFORMS.POSIX;
gen.SubTarget = CPEmbeddedCGenerator.SUBTARGETS.NUCLEUS;
gen.WinSock = 1;
libgen.Platform = LibraryGenerator.PLATFORMS.POSIX;
libgen.SubTarget = LibraryGenerator.SUBTARGETS.NUCLEUS;
libgen.WinSock = 1;
break;
}
switch (languageComboBox.SelectedIndex)
{
case 0:
gen.Language = CPEmbeddedCGenerator.LANGUAGES.C;
libgen.Language = LibraryGenerator.LANGUAGES.C;
break;
case 1:
gen.Language = CPEmbeddedCGenerator.LANGUAGES.CPP;
libgen.Language = LibraryGenerator.LANGUAGES.CPP;
break;
}
switch (newLineComboBox.SelectedIndex)
{
case 0:
gen.CodeNewLine = "\r\n"; break;
case 1:
gen.CodeNewLine = "\n"; break;
}
switch (callConventionComboBox.SelectedIndex)
{
case 0:
gen.CallingConvention = ""; break;
case 1:
gen.CallingConvention = "_stdcall "; break;
case 2:
gen.CallingConvention = "_fastcall "; break;
}
switch (indentComboBox.SelectedIndex)
{
case 0:
gen.CodeTab = "\t"; break;
case 1:
gen.CodeTab = " "; break;
case 2:
gen.CodeTab = " "; break;
case 3:
gen.CodeTab = " "; break;
case 4:
gen.CodeTab = " "; break;
case 5:
gen.CodeTab = " "; break;
case 6:
gen.CodeTab = " "; break;
}
gen.CallPrefix = prefixTextBox.Text;
gen.CallLibPrefix = libPrefixTextBox.Text;
gen.Settings = Settings;
gen.FragResponseActions = FragResponseActions;
gen.EscapeActions = EscapeActions;
gen.VersionString = "Intel DeviceBuilder Build#" + Application.ProductVersion;
gen.ClassName = classNameTextBox.Text;
gen.UseVersion = Application.ProductVersion.Substring(0,Application.ProductVersion.LastIndexOf("."));
gen.BasicHTTP = !(HTTP.Checked);
libgen.CodeNewLine = gen.CodeNewLine;
libgen.CallingConvention = gen.CallingConvention;
libgen.CodeTab = gen.CodeTab;
libgen.CodeNewLine = gen.CodeNewLine;
libgen.CallPrefix = libPrefixTextBox.Text;
libgen.VersionString = gen.VersionString;
libgen.ClassName = gen.ClassName;
foreach(System.Data.DataRow r in dataSet1.Tables[0].Rows)
{
gen.CustomTagList.Add(new object[2]{(string)r.ItemArray[0],(string)r.ItemArray[1]});
}
// Setup License
string license = licenseTextBox.Text;
license = license.Replace("<AUTHOR>","Intel Corporation, Intel Device Builder");
license = license.Replace("<REVISION>","#" + Application.ProductVersion);
license = license.Replace("<DATE>",DateTime.Now.ToLongDateString());
gen.License = license;
libgen.License = license;
gen.OnLogOutput += new CPEmbeddedCGenerator.LogOutputHandler(Log);
libgen.OnLogOutput += new LibraryGenerator.LogOutputHandler(Log);
try
{
SourceCodeRepository.Generate_UPnPControlPointStructs(libPrefixTextBox.Text,outputDir);
SourceCodeRepository.Generate_Parsers(this.libPrefixTextBox.Text,outputDir);
SourceCodeRepository.Generate_SSDPClient(this.libPrefixTextBox.Text,outputDir,UPnP1dot1Enabled.Checked);
SourceCodeRepository.Generate_AsyncSocket(this.libPrefixTextBox.Text,outputDir);
SourceCodeRepository.Generate_AsyncServerSocket(this.libPrefixTextBox.Text,outputDir);
SourceCodeRepository.Generate_WebClient(this.libPrefixTextBox.Text,outputDir,!HTTP.Checked);
SourceCodeRepository.Generate_WebServer(this.libPrefixTextBox.Text,outputDir,!HTTP.Checked);
gen.Generate(device,outputDir,serviceNames,!(bool)gen.Settings["SupressSample"]);
}
catch(Exception ddd)
{
MessageBox.Show(this,"Error Generating Code","Code Generator");
}
libgen.OnLogOutput -= new LibraryGenerator.LogOutputHandler(Log);
gen.OnLogOutput -= new CPEmbeddedCGenerator.LogOutputHandler(Log);
}
generateButton.Enabled = true;
generateButton.Text = buttonText;
}
private void Log(object sender, string msg)
{
genOutputTextBox.Text += msg + "\r\n";
}
private void outputDirectoryButton_Click(object sender, System.EventArgs e)
{
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.BrowseForFolder(this.Handle.ToInt32(),"Select a directory to share. That directory and all sub-folders will also be made available on the network.",1,null);
string directoryString = null;
if (folder != null)
{
if (folder.ParentFolder != null)
{
for (int i = 0 ; i < folder.ParentFolder.Items().Count ; i++)
{
if (folder.ParentFolder.Items().Item(i).IsFolder)
{
if (((Shell32.Folder)(folder.ParentFolder.Items().Item(i).GetFolder)).Title == folder.Title)
{
directoryString = folder.ParentFolder.Items().Item(i).Path;
break;
}
}
}
}
if (directoryString == null || directoryString.StartsWith("::") == true)
{
MessageBox.Show(this,"Invalid folder","Output Folder",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
else
{
outputPathTextBox.Text = directoryString;
}
}
}
private void languageComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
classNameTextBox.Enabled = (languageComboBox.SelectedIndex == 1);
}
private void tabPage3_Click(object sender, System.EventArgs e)
{
}
private void platformComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(platformComboBox.SelectedIndex==4)
{
// .net
this.languageComboBox.Enabled = false;
this.newLineComboBox.Enabled = false;
this.callConventionComboBox.Enabled = false;
this.prefixTextBox.Enabled = false;
this.libPrefixTextBox.Enabled = false;
this.indentComboBox.Enabled = false;
this.classNameTextBox.Enabled = true;
}
else
{
this.languageComboBox.Enabled = true;
this.newLineComboBox.Enabled = true;
this.callConventionComboBox.Enabled = true;
this.prefixTextBox.Enabled = true;
this.libPrefixTextBox.Enabled = true;
this.indentComboBox.Enabled = true;
this.classNameTextBox.Enabled = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace Application
{
class Person
{
public int Rank;
public string Name;
public string Citizenship;
public int Age;
public double Worth;
public string Source;
public override string ToString()
{
return Rank.ToString() + " " + Name + " " + Citizenship + " " + Age + " " + Worth + " " + Source;
}
};
class CountryBalance
{
public string Name;
public int Billionare;
public double Worth;
public override string ToString()
{
return Name.ToString() + " " + Billionare + " " + Math.Round(Worth,2);
}
};
class Program
{
private static void Main(string[] args)
{
var streamReader = new StreamReader("WorldWealthList.txt");
string record;
int size = 2;
var data = new List<Person>();
while (!streamReader.EndOfStream && size > 0)
{
record = streamReader.ReadLine();
--size;
}
while (!streamReader.EndOfStream)
{
record = streamReader.ReadLine();
var person2 = new Person();
if (SetPerson(record, person2))
data.Add(person2);
}
Console.WriteLine("loaded Records =" + data.Count);
Console.Write("Balance over all = ");
double balance = 0.0;
for (int count = 0; count < data.Count; ++count)
{
if (data[count].Worth > 0) balance += data[count].Worth;
}
Console.Write(balance);
Console.WriteLine(" billions US$\n");
Console.Write("average age over all = ");
double avgAge = 0.0;
for (int count = 0; count < data.Count; ++count)
{
if (data[count].Age > 0) avgAge += data[count].Age;
}
avgAge = avgAge / data.Count;
Console.WriteLine(avgAge);
Console.Write("average balance over all = ");
double avgBalance = 0.0;
for (int count = 0; count < data.Count; ++count)
{
if (data[count].Worth > 0) avgBalance += data[count].Worth;
}
avgBalance = avgBalance / data.Count;
Console.Write(avgBalance);
Console.WriteLine(" billions US$\n");
Console.WriteLine("**** Top 10 ****\n");
var data2 = new List<Person>();
for (int count = 0; count < data.Count; ++count)
{
int count2 = 0;
for (; count2 < data2.Count; ++count2)
{
if (data[count].Worth > data2[count2].Worth)
{
break;
}
}
data2.Insert(count2, data[count]);
}
for (int count = 0; count < 10; ++count)
{
if (count < data2.Count)
Console.WriteLine(data2[count].ToString());
}
Console.WriteLine("****************");
Console.WriteLine("*** country balance ***");
List<CountryBalance> data3 = new List<CountryBalance>();
for (int count = 0; count < data.Count; ++count)
{
var p1 = data[count];
CountryBalance found = null;
for (int count2 = 0; count2 < data3.Count; ++count2)
{
if (p1.Citizenship == data3[count2].Name)
{
found = data3[count2];
break;
}
}
if (found == null)
{
found = new CountryBalance();
found.Name = p1.Citizenship;
data3.Add(found);
}
found.Billionare += 1;
found.Worth += p1.Worth;
}
var data4 = new List<CountryBalance>();
for (int count = 0; count < data3.Count; ++count)
{
int count2 = 0;
for (; count2 < data4.Count; ++count2)
{
if (data3[count].Worth > data4[count2].Worth)
{
break;
}
}
data4.Insert(count2, data3[count]);
}
for (int count = 0; count < data4.Count; ++count)
{
Console.WriteLine(data4[count].ToString());
}
}
static List<string> splitString(string x, char y)
{
int i = 0, j = 0;
var split = new List<string>();
foreach (char c in x)
{
if (y == c)
{
split.Add(x.Substring(j, i - j));
++i;
j = i;
continue;
}
++i;
if (i == x.Length)
split.Add(x.Substring(j, i - j));
}
return split;
}
static bool SetPerson(string listRecord, Person person)
{
var split = splitString(listRecord, '\t');
if (split.Count < 6)
return false;
setPartsToPerson(split, person);
return true;
}
static void setPartsToPerson(List<string> split, Person person)
{
try
{
person.Rank = int.Parse(split[0]);
}
catch (Exception e)
{
}
person.Name = split[1];
person.Citizenship = split[2];
try
{
person.Age = int.Parse(split[3]);
}
catch (Exception e)
{
}
try
{
person.Worth = float.Parse(split[4], System.Globalization.CultureInfo.InvariantCulture);
}
catch (Exception e)
{
}
person.Source = split[5];
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the RemEstudioOcular class.
/// </summary>
[Serializable]
public partial class RemEstudioOcularCollection : ActiveList<RemEstudioOcular, RemEstudioOcularCollection>
{
public RemEstudioOcularCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>RemEstudioOcularCollection</returns>
public RemEstudioOcularCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
RemEstudioOcular o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Rem_EstudioOcular table.
/// </summary>
[Serializable]
public partial class RemEstudioOcular : ActiveRecord<RemEstudioOcular>, IActiveRecord
{
#region .ctors and Default Settings
public RemEstudioOcular()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public RemEstudioOcular(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public RemEstudioOcular(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public RemEstudioOcular(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Rem_EstudioOcular", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdEstudioOcular = new TableSchema.TableColumn(schema);
colvarIdEstudioOcular.ColumnName = "idEstudioOcular";
colvarIdEstudioOcular.DataType = DbType.Int32;
colvarIdEstudioOcular.MaxLength = 0;
colvarIdEstudioOcular.AutoIncrement = true;
colvarIdEstudioOcular.IsNullable = false;
colvarIdEstudioOcular.IsPrimaryKey = true;
colvarIdEstudioOcular.IsForeignKey = false;
colvarIdEstudioOcular.IsReadOnly = false;
colvarIdEstudioOcular.DefaultSetting = @"";
colvarIdEstudioOcular.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEstudioOcular);
TableSchema.TableColumn colvarIdClasificacion = new TableSchema.TableColumn(schema);
colvarIdClasificacion.ColumnName = "idClasificacion";
colvarIdClasificacion.DataType = DbType.Int32;
colvarIdClasificacion.MaxLength = 0;
colvarIdClasificacion.AutoIncrement = false;
colvarIdClasificacion.IsNullable = false;
colvarIdClasificacion.IsPrimaryKey = false;
colvarIdClasificacion.IsForeignKey = true;
colvarIdClasificacion.IsReadOnly = false;
colvarIdClasificacion.DefaultSetting = @"";
colvarIdClasificacion.ForeignKeyTableName = "Rem_Clasificacion";
schema.Columns.Add(colvarIdClasificacion);
TableSchema.TableColumn colvarOIRpHipertensiva = new TableSchema.TableColumn(schema);
colvarOIRpHipertensiva.ColumnName = "OIRpHipertensiva";
colvarOIRpHipertensiva.DataType = DbType.Boolean;
colvarOIRpHipertensiva.MaxLength = 0;
colvarOIRpHipertensiva.AutoIncrement = false;
colvarOIRpHipertensiva.IsNullable = false;
colvarOIRpHipertensiva.IsPrimaryKey = false;
colvarOIRpHipertensiva.IsForeignKey = false;
colvarOIRpHipertensiva.IsReadOnly = false;
colvarOIRpHipertensiva.DefaultSetting = @"((0))";
colvarOIRpHipertensiva.ForeignKeyTableName = "";
schema.Columns.Add(colvarOIRpHipertensiva);
TableSchema.TableColumn colvarOIRpDNoProliferativo = new TableSchema.TableColumn(schema);
colvarOIRpDNoProliferativo.ColumnName = "OIRpDNoProliferativo";
colvarOIRpDNoProliferativo.DataType = DbType.Boolean;
colvarOIRpDNoProliferativo.MaxLength = 0;
colvarOIRpDNoProliferativo.AutoIncrement = false;
colvarOIRpDNoProliferativo.IsNullable = false;
colvarOIRpDNoProliferativo.IsPrimaryKey = false;
colvarOIRpDNoProliferativo.IsForeignKey = false;
colvarOIRpDNoProliferativo.IsReadOnly = false;
colvarOIRpDNoProliferativo.DefaultSetting = @"((0))";
colvarOIRpDNoProliferativo.ForeignKeyTableName = "";
schema.Columns.Add(colvarOIRpDNoProliferativo);
TableSchema.TableColumn colvarOIRpDProliferativo = new TableSchema.TableColumn(schema);
colvarOIRpDProliferativo.ColumnName = "OIRpDProliferativo";
colvarOIRpDProliferativo.DataType = DbType.Boolean;
colvarOIRpDProliferativo.MaxLength = 0;
colvarOIRpDProliferativo.AutoIncrement = false;
colvarOIRpDProliferativo.IsNullable = false;
colvarOIRpDProliferativo.IsPrimaryKey = false;
colvarOIRpDProliferativo.IsForeignKey = false;
colvarOIRpDProliferativo.IsReadOnly = false;
colvarOIRpDProliferativo.DefaultSetting = @"((0))";
colvarOIRpDProliferativo.ForeignKeyTableName = "";
schema.Columns.Add(colvarOIRpDProliferativo);
TableSchema.TableColumn colvarOIRpDRetina = new TableSchema.TableColumn(schema);
colvarOIRpDRetina.ColumnName = "OIRpDRetina";
colvarOIRpDRetina.DataType = DbType.Boolean;
colvarOIRpDRetina.MaxLength = 0;
colvarOIRpDRetina.AutoIncrement = false;
colvarOIRpDRetina.IsNullable = false;
colvarOIRpDRetina.IsPrimaryKey = false;
colvarOIRpDRetina.IsForeignKey = false;
colvarOIRpDRetina.IsReadOnly = false;
colvarOIRpDRetina.DefaultSetting = @"((0))";
colvarOIRpDRetina.ForeignKeyTableName = "";
schema.Columns.Add(colvarOIRpDRetina);
TableSchema.TableColumn colvarODRpHipertensiva = new TableSchema.TableColumn(schema);
colvarODRpHipertensiva.ColumnName = "ODRpHipertensiva";
colvarODRpHipertensiva.DataType = DbType.Boolean;
colvarODRpHipertensiva.MaxLength = 0;
colvarODRpHipertensiva.AutoIncrement = false;
colvarODRpHipertensiva.IsNullable = false;
colvarODRpHipertensiva.IsPrimaryKey = false;
colvarODRpHipertensiva.IsForeignKey = false;
colvarODRpHipertensiva.IsReadOnly = false;
colvarODRpHipertensiva.DefaultSetting = @"((0))";
colvarODRpHipertensiva.ForeignKeyTableName = "";
schema.Columns.Add(colvarODRpHipertensiva);
TableSchema.TableColumn colvarODRpDNoProliferativo = new TableSchema.TableColumn(schema);
colvarODRpDNoProliferativo.ColumnName = "ODRpDNoProliferativo";
colvarODRpDNoProliferativo.DataType = DbType.Boolean;
colvarODRpDNoProliferativo.MaxLength = 0;
colvarODRpDNoProliferativo.AutoIncrement = false;
colvarODRpDNoProliferativo.IsNullable = false;
colvarODRpDNoProliferativo.IsPrimaryKey = false;
colvarODRpDNoProliferativo.IsForeignKey = false;
colvarODRpDNoProliferativo.IsReadOnly = false;
colvarODRpDNoProliferativo.DefaultSetting = @"((0))";
colvarODRpDNoProliferativo.ForeignKeyTableName = "";
schema.Columns.Add(colvarODRpDNoProliferativo);
TableSchema.TableColumn colvarODRpDProliferativo = new TableSchema.TableColumn(schema);
colvarODRpDProliferativo.ColumnName = "ODRpDProliferativo";
colvarODRpDProliferativo.DataType = DbType.Boolean;
colvarODRpDProliferativo.MaxLength = 0;
colvarODRpDProliferativo.AutoIncrement = false;
colvarODRpDProliferativo.IsNullable = false;
colvarODRpDProliferativo.IsPrimaryKey = false;
colvarODRpDProliferativo.IsForeignKey = false;
colvarODRpDProliferativo.IsReadOnly = false;
colvarODRpDProliferativo.DefaultSetting = @"((0))";
colvarODRpDProliferativo.ForeignKeyTableName = "";
schema.Columns.Add(colvarODRpDProliferativo);
TableSchema.TableColumn colvarODRpDRetina = new TableSchema.TableColumn(schema);
colvarODRpDRetina.ColumnName = "ODRpDRetina";
colvarODRpDRetina.DataType = DbType.Boolean;
colvarODRpDRetina.MaxLength = 0;
colvarODRpDRetina.AutoIncrement = false;
colvarODRpDRetina.IsNullable = false;
colvarODRpDRetina.IsPrimaryKey = false;
colvarODRpDRetina.IsForeignKey = false;
colvarODRpDRetina.IsReadOnly = false;
colvarODRpDRetina.DefaultSetting = @"((0))";
colvarODRpDRetina.ForeignKeyTableName = "";
schema.Columns.Add(colvarODRpDRetina);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Rem_EstudioOcular",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdEstudioOcular")]
[Bindable(true)]
public int IdEstudioOcular
{
get { return GetColumnValue<int>(Columns.IdEstudioOcular); }
set { SetColumnValue(Columns.IdEstudioOcular, value); }
}
[XmlAttribute("IdClasificacion")]
[Bindable(true)]
public int IdClasificacion
{
get { return GetColumnValue<int>(Columns.IdClasificacion); }
set { SetColumnValue(Columns.IdClasificacion, value); }
}
[XmlAttribute("OIRpHipertensiva")]
[Bindable(true)]
public bool OIRpHipertensiva
{
get { return GetColumnValue<bool>(Columns.OIRpHipertensiva); }
set { SetColumnValue(Columns.OIRpHipertensiva, value); }
}
[XmlAttribute("OIRpDNoProliferativo")]
[Bindable(true)]
public bool OIRpDNoProliferativo
{
get { return GetColumnValue<bool>(Columns.OIRpDNoProliferativo); }
set { SetColumnValue(Columns.OIRpDNoProliferativo, value); }
}
[XmlAttribute("OIRpDProliferativo")]
[Bindable(true)]
public bool OIRpDProliferativo
{
get { return GetColumnValue<bool>(Columns.OIRpDProliferativo); }
set { SetColumnValue(Columns.OIRpDProliferativo, value); }
}
[XmlAttribute("OIRpDRetina")]
[Bindable(true)]
public bool OIRpDRetina
{
get { return GetColumnValue<bool>(Columns.OIRpDRetina); }
set { SetColumnValue(Columns.OIRpDRetina, value); }
}
[XmlAttribute("ODRpHipertensiva")]
[Bindable(true)]
public bool ODRpHipertensiva
{
get { return GetColumnValue<bool>(Columns.ODRpHipertensiva); }
set { SetColumnValue(Columns.ODRpHipertensiva, value); }
}
[XmlAttribute("ODRpDNoProliferativo")]
[Bindable(true)]
public bool ODRpDNoProliferativo
{
get { return GetColumnValue<bool>(Columns.ODRpDNoProliferativo); }
set { SetColumnValue(Columns.ODRpDNoProliferativo, value); }
}
[XmlAttribute("ODRpDProliferativo")]
[Bindable(true)]
public bool ODRpDProliferativo
{
get { return GetColumnValue<bool>(Columns.ODRpDProliferativo); }
set { SetColumnValue(Columns.ODRpDProliferativo, value); }
}
[XmlAttribute("ODRpDRetina")]
[Bindable(true)]
public bool ODRpDRetina
{
get { return GetColumnValue<bool>(Columns.ODRpDRetina); }
set { SetColumnValue(Columns.ODRpDRetina, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a RemClasificacion ActiveRecord object related to this RemEstudioOcular
///
/// </summary>
public DalSic.RemClasificacion RemClasificacion
{
get { return DalSic.RemClasificacion.FetchByID(this.IdClasificacion); }
set { SetColumnValue("idClasificacion", value.IdClasificacion); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdClasificacion,bool varOIRpHipertensiva,bool varOIRpDNoProliferativo,bool varOIRpDProliferativo,bool varOIRpDRetina,bool varODRpHipertensiva,bool varODRpDNoProliferativo,bool varODRpDProliferativo,bool varODRpDRetina)
{
RemEstudioOcular item = new RemEstudioOcular();
item.IdClasificacion = varIdClasificacion;
item.OIRpHipertensiva = varOIRpHipertensiva;
item.OIRpDNoProliferativo = varOIRpDNoProliferativo;
item.OIRpDProliferativo = varOIRpDProliferativo;
item.OIRpDRetina = varOIRpDRetina;
item.ODRpHipertensiva = varODRpHipertensiva;
item.ODRpDNoProliferativo = varODRpDNoProliferativo;
item.ODRpDProliferativo = varODRpDProliferativo;
item.ODRpDRetina = varODRpDRetina;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdEstudioOcular,int varIdClasificacion,bool varOIRpHipertensiva,bool varOIRpDNoProliferativo,bool varOIRpDProliferativo,bool varOIRpDRetina,bool varODRpHipertensiva,bool varODRpDNoProliferativo,bool varODRpDProliferativo,bool varODRpDRetina)
{
RemEstudioOcular item = new RemEstudioOcular();
item.IdEstudioOcular = varIdEstudioOcular;
item.IdClasificacion = varIdClasificacion;
item.OIRpHipertensiva = varOIRpHipertensiva;
item.OIRpDNoProliferativo = varOIRpDNoProliferativo;
item.OIRpDProliferativo = varOIRpDProliferativo;
item.OIRpDRetina = varOIRpDRetina;
item.ODRpHipertensiva = varODRpHipertensiva;
item.ODRpDNoProliferativo = varODRpDNoProliferativo;
item.ODRpDProliferativo = varODRpDProliferativo;
item.ODRpDRetina = varODRpDRetina;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdEstudioOcularColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdClasificacionColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn OIRpHipertensivaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn OIRpDNoProliferativoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn OIRpDProliferativoColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn OIRpDRetinaColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn ODRpHipertensivaColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn ODRpDNoProliferativoColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn ODRpDProliferativoColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn ODRpDRetinaColumn
{
get { return Schema.Columns[9]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdEstudioOcular = @"idEstudioOcular";
public static string IdClasificacion = @"idClasificacion";
public static string OIRpHipertensiva = @"OIRpHipertensiva";
public static string OIRpDNoProliferativo = @"OIRpDNoProliferativo";
public static string OIRpDProliferativo = @"OIRpDProliferativo";
public static string OIRpDRetina = @"OIRpDRetina";
public static string ODRpHipertensiva = @"ODRpHipertensiva";
public static string ODRpDNoProliferativo = @"ODRpDNoProliferativo";
public static string ODRpDProliferativo = @"ODRpDProliferativo";
public static string ODRpDRetina = @"ODRpDRetina";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2014-2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
#if UNITY
using System.Collections;
#endif // UNITY
using System.Collections.Generic;
#if UNITY
using System.Reflection;
#endif // UNITY
using MsgPack.Serialization.CollectionSerializers;
namespace MsgPack.Serialization.DefaultSerializers
{
#if !UNITY
/// <summary>
/// Provides default implementation for <see cref="Dictionary{TKey,TValue}"/>.
/// </summary>
/// <typeparam name="TKey">The type of keys of the <see cref="Dictionary{TKey,TValue}"/>.</typeparam>
/// <typeparam name="TValue">The type of values of the <see cref="Dictionary{TKey,TValue}"/>.</typeparam>
// ReSharper disable once InconsistentNaming
internal class System_Collections_Generic_Dictionary_2MessagePackSerializer<TKey, TValue> : MessagePackSerializer<Dictionary<TKey, TValue>>, ICollectionInstanceFactory
{
private readonly MessagePackSerializer<TKey> _keySerializer;
private readonly MessagePackSerializer<TValue> _valueSerializer;
public System_Collections_Generic_Dictionary_2MessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema )
: base( ownerContext )
{
this._keySerializer = ownerContext.GetSerializer<TKey>( keysSchema );
this._valueSerializer = ownerContext.GetSerializer<TValue>( valuesSchema );
}
protected internal override void PackToCore( Packer packer, Dictionary<TKey, TValue> objectTree )
{
PackerUnpackerExtensions.PackDictionaryCore( packer, objectTree, this._keySerializer, this._valueSerializer );
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )]
protected internal override Dictionary<TKey, TValue> UnpackFromCore( Unpacker unpacker )
{
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotMapHeader();
}
var count = UnpackHelpers.GetItemsCount( unpacker );
var collection = new Dictionary<TKey, TValue>( count );
this.UnpackToCore( unpacker, collection, count );
return collection;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )]
protected internal override void UnpackToCore( Unpacker unpacker, Dictionary<TKey, TValue> collection )
{
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotMapHeader();
}
this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) );
}
private void UnpackToCore( Unpacker unpacker, Dictionary<TKey, TValue> collection, int count )
{
for ( int i = 0; i < count; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewUnexpectedEndOfStream();
}
TKey key;
if ( unpacker.IsCollectionHeader )
{
using ( var subTreeUnpacker = unpacker.ReadSubtree() )
{
key = this._keySerializer.UnpackFromCore( subTreeUnpacker );
}
}
else
{
key = this._keySerializer.UnpackFromCore( unpacker );
}
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewUnexpectedEndOfStream();
}
if ( unpacker.IsCollectionHeader )
{
using ( var subTreeUnpacker = unpacker.ReadSubtree() )
{
collection.Add( key, this._valueSerializer.UnpackFromCore( subTreeUnpacker ) );
}
}
else
{
collection.Add( key, this._valueSerializer.UnpackFromCore( unpacker ) );
}
}
}
public object CreateInstance( int initialCapacity )
{
return new Dictionary<TKey, TValue>( initialCapacity );
}
}
#else
// ReSharper disable once InconsistentNaming
internal class System_Collections_Generic_Dictionary_2MessagePackSerializer : NonGenericMessagePackSerializer, ICollectionInstanceFactory
{
private readonly IMessagePackSingleObjectSerializer _keySerializer;
private readonly IMessagePackSingleObjectSerializer _valueSerializer;
private readonly Type _keyType;
private readonly ConstructorInfo _constructor;
private readonly MethodInfo _add;
public System_Collections_Generic_Dictionary_2MessagePackSerializer( SerializationContext ownerContext, Type targetType, CollectionTraits traits, Type keyType, Type valueType, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema )
: base( ownerContext, targetType )
{
this._keySerializer = ownerContext.GetSerializer( keyType, keysSchema );
this._valueSerializer = ownerContext.GetSerializer( valueType, valuesSchema );
this._keyType = keyType;
this._constructor =
targetType.GetConstructor( new[] { typeof( int ), typeof( IEqualityComparer<> ).MakeGenericType( keyType ) } );
this._add = traits.AddMethod;
}
protected internal override void PackToCore( Packer packer, object objectTree )
{
var asDictionary = objectTree as IDictionary;
if ( asDictionary == null )
{
packer.PackNull();
return;
}
packer.PackMapHeader( asDictionary.Count );
foreach ( DictionaryEntry entry in asDictionary )
{
this._keySerializer.PackTo( packer, entry.Key );
this._valueSerializer.PackTo( packer, entry.Value );
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )]
protected internal override object UnpackFromCore( Unpacker unpacker )
{
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotMapHeader();
}
var count = UnpackHelpers.GetItemsCount( unpacker );
var collection = this.CreateInstance( count );
this.UnpackToCore( unpacker, collection, count );
return collection;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Asserted internally" )]
protected internal override void UnpackToCore( Unpacker unpacker, object collection )
{
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotMapHeader();
}
this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) );
}
private void UnpackToCore( Unpacker unpacker, object collection, int count )
{
for ( int i = 0; i < count; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewUnexpectedEndOfStream();
}
object key;
if ( unpacker.IsCollectionHeader )
{
using ( var subTreeUnpacker = unpacker.ReadSubtree() )
{
key = this._keySerializer.UnpackFrom( subTreeUnpacker );
}
}
else
{
key = this._keySerializer.UnpackFrom( unpacker );
}
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewUnexpectedEndOfStream();
}
if ( unpacker.IsCollectionHeader )
{
using ( var subTreeUnpacker = unpacker.ReadSubtree() )
{
this._add.InvokePreservingExceptionType( collection, key, this._valueSerializer.UnpackFrom( subTreeUnpacker ) );
}
}
else
{
this._add.InvokePreservingExceptionType( collection, key, this._valueSerializer.UnpackFrom( unpacker ) );
}
}
}
public object CreateInstance( int initialCapacity )
{
return AotHelper.CreateSystemCollectionsGenericDictionary( this._constructor, this._keyType, initialCapacity );
}
}
#endif // !UNITY
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
namespace GameAnalyticsSDK
{
public class GA_SignUp : EditorWindow
{
private GUIContent _firstNameLabel = new GUIContent("First name", "Your first name.");
private GUIContent _lastNameLabel = new GUIContent("Last name", "Your last name (surname).");
private GUIContent _studioNameLabel = new GUIContent("Studio name", "Your studio's name. You can add more studios and games on the GameAnalytics website.");
private GUIContent _gameNameLabel = new GUIContent("Game name", "Your game's name. You can add more studies and games on the GameAnalytics website.");
private GUIContent _passwordConfirmLabel = new GUIContent("Confirm password", "Your GameAnalytics user account password.");
private GUIContent _emailOptInLabel = new GUIContent("Subscribe to release updates, news and tips and tricks.", "If enabled GameAnalytics may send you news about updates, cool tips and tricks, and other news to help you get the most out of our service.");
private GUIContent _emailLabel = new GUIContent("Email", "Your GameAnalytics user account email.");
private GUIContent _passwordLabel = new GUIContent("Password", "Your GameAnalytics user account password. Must be at least 8 characters in length.");
//private GUIContent _studiosLabel = new GUIContent("Studio", "Studios tied to your GameAnalytics user account.");
//private GUIContent _gamesLabel = new GUIContent("Game", "Games tied to the selected GameAnalytics studio.");
public int TourStep = 0;
private Vector2 _appScrollPos;
private string _appFigName;
private const int INPUT_WIDTH = 230;
private List<AppFiguresGame> _appFiguresGames;
private AppFiguresGame _appFiguresGame;
private static GA_SignUp _instance;
private bool _signUpInProgress = false;
private bool _createGameInProgress = false;
private string _googlePlayPublicKey = "";
private GAPlatformSignUp _selectedPlatform;
private int _selectedStudio;
private enum StringType
{
Label,
TextBox,
Link
}
private struct StringWithType
{
public string Text;
public StringType Type;
public string Link;
}
public void Opened()
{
if(_instance == null)
{
_instance = this;
}
else
{
Close();
}
}
void OnDisable()
{
if(_instance == this)
{
_instance = null;
}
}
void OnGUI()
{
switch(TourStep)
{
#region sign up
case 0: // sign up
GUILayout.Space(20);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(GameAnalytics.SettingsGA.UserIcon, new GUILayoutOption[] {
GUILayout.Width(40),
GUILayout.MaxHeight(40)
});
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Create your account", EditorStyles.whiteLargeLabel);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
// first name
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(_firstNameLabel, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GameAnalytics.SettingsGA.FirstName = EditorGUILayout.TextField("", GameAnalytics.SettingsGA.FirstName, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
// last name
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(_lastNameLabel, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GameAnalytics.SettingsGA.LastName = EditorGUILayout.TextField("", GameAnalytics.SettingsGA.LastName, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
// e-mail
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(_emailLabel, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GameAnalytics.SettingsGA.EmailGA = EditorGUILayout.TextField("", GameAnalytics.SettingsGA.EmailGA, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
// password
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(_passwordLabel, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GameAnalytics.SettingsGA.PasswordGA = EditorGUILayout.PasswordField("", GameAnalytics.SettingsGA.PasswordGA, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
// confirm password
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(_passwordConfirmLabel, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GameAnalytics.SettingsGA.PasswordConfirm = EditorGUILayout.PasswordField("", GameAnalytics.SettingsGA.PasswordConfirm, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
// studio name
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(_studioNameLabel, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GameAnalytics.SettingsGA.StudioName = EditorGUILayout.TextField("", GameAnalytics.SettingsGA.StudioName, GUILayout.Width(INPUT_WIDTH));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
// email opt in
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GameAnalytics.SettingsGA.EmailOptIn = EditorGUILayout.Toggle("", GameAnalytics.SettingsGA.EmailOptIn, GUILayout.Width(15));
GUILayout.Label(_emailOptInLabel);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
// terms of service
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("By activating your account you agree with our", GUILayout.Width(248));
GUILayout.Space(-5);
GUILayout.BeginVertical();
GUILayout.Space(2);
if(GUILayout.Button("Terms of Service", EditorStyles.boldLabel, GUILayout.Width(105)))
{
Application.OpenURL("http://www.gameanalytics.com/terms.html");
}
EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link);
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
// create account button
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.enabled = !_signUpInProgress;
if(GUILayout.Button("Create account", new GUILayoutOption[] {
GUILayout.Width(200),
GUILayout.MaxHeight(30)
}))
{
_signUpInProgress = true;
GA_SettingsInspector.SignupUser(GameAnalytics.SettingsGA, this);
}
GUI.enabled = true;
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
break;
#endregion // sign up
#region add your game
case 1: // add your game
GUILayout.Space(20);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(GameAnalytics.SettingsGA.GameIcon, new GUILayoutOption[] {
GUILayout.Width(40),
GUILayout.MaxHeight(40)
});
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Add your game", EditorStyles.whiteLargeLabel);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("You can quickly add your game by searching the app store.");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
// game name
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(_gameNameLabel, GUILayout.Width(500));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
int tmpFontSize = GUI.skin.textField.fontSize;
Vector2 tmpOffset = GUI.skin.textField.contentOffset;
GUI.skin.textField.fontSize = 12;
GUI.skin.textField.contentOffset = new Vector2(6, 6);
GameAnalytics.SettingsGA.GameName = EditorGUILayout.TextField("", GameAnalytics.SettingsGA.GameName, new GUILayoutOption[] {
GUILayout.Width(300),
GUILayout.Height(30)
});
GUI.skin.textField.fontSize = tmpFontSize;
GUI.skin.textField.contentOffset = tmpOffset;
if(GUILayout.Button("Find your game", new GUILayoutOption[] {
GUILayout.Width(200),
GUILayout.MaxHeight(30)
}))
{
GA_SettingsInspector.GetAppFigures(GameAnalytics.SettingsGA, this);
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GA_SettingsInspector.Splitter(new Color(0.35f, 0.35f, 0.35f), 1, 30);
if(_appFiguresGames != null && _appFiguresGames.Count > 0)
{
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("'" + _appFigName + "' matched " + _appFiguresGames.Count + " titles.", EditorStyles.boldLabel);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
_appScrollPos = GUILayout.BeginScrollView(_appScrollPos, GUI.skin.box, GUILayout.Width(571));
for(int i = 0; i < _appFiguresGames.Count; i++)
{
GUILayout.BeginHorizontal();
if(_appFiguresGames[i].Icon != null)
{
GUILayout.Label(_appFiguresGames[i].Icon, new GUILayoutOption[] {
GUILayout.Width(32),
GUILayout.Height(32)
});
}
else
{
GUILayout.Label("", new GUILayoutOption[] {
GUILayout.Width(32),
GUILayout.Height(32)
});
}
Rect lastRect = GUILayoutUtility.GetLastRect();
Vector2 tmpOffsetLabel = GUI.skin.label.contentOffset;
GUI.skin.label.contentOffset = new Vector2(0, 9);
GUILayout.Label(_appFiguresGames[i].Name, GUILayout.Width(200));
GUILayout.Label(_appFiguresGames[i].Developer, GUILayout.Width(200));
PaintAppStoreIcon(_appFiguresGames[i].Store);
GUI.skin.label.contentOffset = tmpOffsetLabel;
GUILayout.EndHorizontal();
GA_SettingsInspector.Splitter(new Color(0.35f, 0.35f, 0.35f), 1, 10);
Rect appFigRect = new Rect(lastRect.x - 5, lastRect.y - 5, lastRect.width + 520, lastRect.height + 10);
if(GUI.Button(appFigRect, "", GUIStyle.none))
{
_appFiguresGame = _appFiguresGames[i];
TourStep = 3;
}
EditorGUIUtility.AddCursorRect(appFigRect, MouseCursor.Link);
}
GUILayout.EndScrollView();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("If your game is still in development or not in the app store, please add it manually.");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
// create new game button
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if(GUILayout.Button("Create new game", new GUILayoutOption[] {
GUILayout.Width(200),
GUILayout.Height(30)
}))
{
TourStep = 2;
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
break;
#endregion // add your game
#region create new game
case 2: // create new game
GUILayout.Space(20);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(GameAnalytics.SettingsGA.GameIcon, new GUILayoutOption[] {
GUILayout.Width(40),
GUILayout.MaxHeight(40)
});
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Create new game", EditorStyles.whiteLargeLabel);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
// game name
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(_gameNameLabel, GUILayout.Width(300));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
int tmpFontSize2 = GUI.skin.textField.fontSize;
Vector2 tmpOffset2 = GUI.skin.textField.contentOffset;
GUI.skin.textField.fontSize = 12;
GUI.skin.textField.contentOffset = new Vector2(5, 5);
GameAnalytics.SettingsGA.GameName = EditorGUILayout.TextField("", GameAnalytics.SettingsGA.GameName, new GUILayoutOption[] {
GUILayout.Width(300),
GUILayout.Height(30)
});
GUI.skin.textField.fontSize = tmpFontSize2;
GUI.skin.textField.contentOffset = tmpOffset2;
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
this._selectedStudio = EditorGUILayout.Popup("", this._selectedStudio, Studio.GetStudioNames(GameAnalytics.SettingsGA.Studios, false), GUILayout.Width(200));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
this._selectedPlatform = (GAPlatformSignUp)EditorGUILayout.Popup("", (int)this._selectedPlatform, System.Enum.GetNames(typeof(GAPlatformSignUp)), GUILayout.Width(200));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if(this._selectedPlatform == GAPlatformSignUp.Android)
{
GUILayout.BeginHorizontal();
EditorGUILayout.HelpBox("PLEASE NOTICE: If you want to validate your Android in-app purchase please enter your Google Play License key (public key). Click here to learn more about the Google Play License key.", MessageType.Info);
if(GUI.Button(GUILayoutUtility.GetLastRect(), "", GUIStyle.none))
{
//Application.OpenURL("https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/Configure%20XCode");
}
EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link);
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label("Google Play License key", GUILayout.Width(150));
this._googlePlayPublicKey = GUILayout.TextField(this._googlePlayPublicKey);
GUILayout.EndHorizontal();
}
EditorGUILayout.Space();
EditorGUILayout.Space();
// create game button
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.enabled = !_createGameInProgress;
if(GUILayout.Button("Create game", new GUILayoutOption[] {
GUILayout.Width(200),
GUILayout.MaxHeight(30)
}))
{
_createGameInProgress = true;
GA_SettingsInspector.CreateGame(GameAnalytics.SettingsGA, this, this._selectedStudio, GameAnalytics.SettingsGA.GameName, this._googlePlayPublicKey, this._selectedPlatform, null);
}
GUI.enabled = true;
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GA_SettingsInspector.Splitter(new Color(0.35f, 0.35f, 0.35f), 1, 30);
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Go back to ");
Rect r1 = GUILayoutUtility.GetLastRect();
GUILayout.Space(-5);
GUILayout.BeginVertical();
GUILayout.Space(2);
GUILayout.Label("Add your game", EditorStyles.boldLabel);
GUILayout.EndVertical();
Rect r2 = GUILayoutUtility.GetLastRect();
Rect r3 = new Rect(r1.x, r1.y, r1.width + r2.width, r2.height);
if(GUI.Button(r3, "", GUIStyle.none))
{
TourStep = 1;
}
EditorGUIUtility.AddCursorRect(r3, MouseCursor.Link);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
break;
#endregion // create new game
#region app figures add game
case 3: // app figures add game
GUILayout.Space(20);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(GameAnalytics.SettingsGA.GameIcon, new GUILayoutOption[] {
GUILayout.Width(40),
GUILayout.MaxHeight(40)
});
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Is this your game?", EditorStyles.whiteLargeLabel);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Please confirm that this is the game you want to add.");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
// game name
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if(_appFiguresGame.Icon != null)
{
GUILayout.Label(_appFiguresGame.Icon, new GUILayoutOption[] {
GUILayout.Width(100),
GUILayout.Height(100)
});
}
else
{
GUILayout.Label("", new GUILayoutOption[] {
GUILayout.Width(100),
GUILayout.Height(100)
});
}
GUILayout.Label("", GUILayout.Width(25));
GUILayout.BeginVertical();
GUILayout.Label(_appFiguresGame.Name, EditorStyles.whiteLargeLabel, GUILayout.Width(200));
GUILayout.Label(_appFiguresGame.Developer, GUILayout.Width(200));
GUILayout.Label("", GUILayout.Height(20));
PaintAppStoreIcon(_appFiguresGame.Store);
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
if(_appFiguresGame.Store.Equals("google_play"))
{
GUILayout.BeginHorizontal();
EditorGUILayout.HelpBox("PLEASE NOTICE: If you want to validate your Android in-app purchase please enter your Google Play License key (public key). Click here to learn more about the Google Play License key.", MessageType.Info);
if(GUI.Button(GUILayoutUtility.GetLastRect(), "", GUIStyle.none))
{
//Application.OpenURL("https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/Configure%20XCode");
}
EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link);
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label("Google Play License key", GUILayout.Width(150));
this._googlePlayPublicKey = GUILayout.TextField(this._googlePlayPublicKey);
GUILayout.EndHorizontal();
}
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
this._selectedStudio = EditorGUILayout.Popup("", this._selectedStudio, Studio.GetStudioNames(GameAnalytics.SettingsGA.Studios, false), GUILayout.Width(200));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
// create game button
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.enabled = !_createGameInProgress;
if(GUILayout.Button("Add game", new GUILayoutOption[] {
GUILayout.Width(200),
GUILayout.MaxHeight(30)
}))
{
_createGameInProgress = true;
this._selectedPlatform = _appFiguresGame.Store.Equals("google_play") || _appFiguresGame.Store.Equals("amazon_appstore") ? GAPlatformSignUp.Android : GAPlatformSignUp.iOS;
GA_SettingsInspector.CreateGame(GameAnalytics.SettingsGA, this, this._selectedStudio, _appFiguresGame.Name, this._googlePlayPublicKey, this._selectedPlatform, _appFiguresGame);
}
GUI.enabled = true;
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Go back to ");
Rect r21 = GUILayoutUtility.GetLastRect();
GUILayout.Space(-5);
GUILayout.BeginVertical();
GUILayout.Space(2);
GUILayout.Label("results", EditorStyles.boldLabel);
GUILayout.EndVertical();
Rect r22 = GUILayoutUtility.GetLastRect();
Rect r23 = new Rect(r21.x, r21.y, r21.width + r22.width, r22.height);
if(GUI.Button(r23, "", GUIStyle.none))
{
TourStep = 1;
}
EditorGUIUtility.AddCursorRect(r23, MouseCursor.Link);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GA_SettingsInspector.Splitter(new Color(0.35f, 0.35f, 0.35f), 1, 30);
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("If your game is still in development or not in the app store, please add it manually.");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
// create new game button
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if(GUILayout.Button("Create new game", new GUILayoutOption[] {
GUILayout.Width(200),
GUILayout.MaxHeight(30)
}))
{
TourStep = 2;
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
break;
#endregion // app figures add game
#region game created
case 4:
GUILayout.Space(20);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(GameAnalytics.SettingsGA.Logo, new GUILayoutOption[] {
GUILayout.Width(40),
GUILayout.Height(40)
});
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Congratulations!", EditorStyles.whiteLargeLabel);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Your game has been created successfully.");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GA_SettingsInspector.Splitter(new Color(0.35f, 0.35f, 0.35f), 1, 30);
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
TextAnchor tmpLA = GUI.skin.label.alignment;
GUI.skin.label.alignment = TextAnchor.UpperCenter;
GUILayout.Label("We've put together a simple guide to help you instrument GameAnalytics in your game.", GUILayout.MaxWidth(540));
GUI.skin.label.alignment = tmpLA;
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
// create game button
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if(GUILayout.Button("Start guide", new GUILayoutOption[] {
GUILayout.Width(200),
GUILayout.MaxHeight(30)
}))
{
TourStep = 5;
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
break;
#endregion // game created
#region guide
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
int guideStep = TourStep - 4;
GUILayout.Space(20);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(GameAnalytics.SettingsGA.InstrumentIcon, new GUILayoutOption[] {
GUILayout.Width(40),
GUILayout.Height(40)
});
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Start instrumenting", EditorStyles.whiteLargeLabel);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Let us guide you through getting properly setup with GameAnalytics.");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GA_SettingsInspector.Splitter(new Color(0.35f, 0.35f, 0.35f), 1, 30);
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if(guideStep == 10)
GUILayout.Label(GetGuideStepTitle(guideStep), EditorStyles.whiteLargeLabel, GUILayout.Width(464));
else
GUILayout.Label(GetGuideStepTitle(guideStep), EditorStyles.whiteLargeLabel, GUILayout.Width(470));
GUILayout.BeginVertical();
GUILayout.Space(7);
if(guideStep == 10)
GUILayout.Label("STEP " + (guideStep) + " OF 10", GUILayout.Width(87));
else
GUILayout.Label("STEP " + (guideStep) + " OF 10", GUILayout.Width(80));
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
StringWithType[] guideStepTexts = GetGuideStepText(guideStep);
foreach(StringWithType s in guideStepTexts)
{
if(s.Type == StringType.Label)
{
GUILayout.Label(s.Text, EditorStyles.wordWrappedLabel, GUILayout.MaxWidth(550));
}
else if(s.Type == StringType.TextBox)
{
TextAnchor tmpA = GUI.skin.textField.alignment;
int tmpFS = GUI.skin.textField.fontSize;
GUI.skin.textField.alignment = TextAnchor.MiddleLeft;
GUI.skin.textField.fontSize = 12;
GUI.skin.textField.padding = new RectOffset(10, 1, 10, 10);
GUILayout.TextField(s.Text, new GUILayoutOption[] {
GUILayout.MaxWidth(550),
GUILayout.Height(34)
});
GUI.skin.textField.alignment = tmpA;
GUI.skin.textField.fontSize = tmpFS;
GUI.skin.textField.padding = new RectOffset(3, 3, 1, 2);
}
else if(s.Type == StringType.Link)
{
GUI.skin.label.fontStyle = FontStyle.Bold;
float sl = GUI.skin.button.CalcSize(new GUIContent(s.Text)).x;
if(GUILayout.Button(s.Text, EditorStyles.whiteLabel, GUILayout.MaxWidth(sl)))
{
Application.OpenURL(s.Link);
}
GUI.skin.label.fontStyle = FontStyle.Normal;
EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link);
}
}
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
GA_SettingsInspector.Splitter(new Color(0.35f, 0.35f, 0.35f), 1, 30);
// create game button
string buttonText = "Next step";
if(TourStep == 14)
{
buttonText = "Done";
}
GUI.BeginGroup(new Rect(0, 420, 640, 50));
//GUILayout.BeginHorizontal();
//GUILayout.FlexibleSpace();
//GUILayout.BeginVertical();
//GUILayout.Space(7);
GUI.Label(new Rect(43, 7, 500, 50), GetGuideStepNext(guideStep));
//GUILayout.EndVertical();
if(guideStep > 1 && GUI.Button(new Rect(454, 0, 30, 30), "<"))
{
TourStep--;
}
if(GUI.Button(new Rect(489, 0, 100, 30), buttonText))
{
if(TourStep < 14)
TourStep++;
else
Close();
}
//GUILayout.FlexibleSpace();
//GUILayout.EndHorizontal();
GUI.EndGroup();
break;
#endregion // guide
}
}
public void AppFigComplete(string gameName, List<AppFiguresGame> appFiguresGames)
{
_appFigName = gameName;
_appFiguresGames = appFiguresGames;
Repaint();
}
public void SignUpComplete()
{
_instance.TourStep = 1;
_signUpInProgress = false;
Repaint();
}
public void SignUpFailed()
{
_signUpInProgress = false;
Repaint();
}
public void CreateGameComplete()
{
TourStep = 4;
_createGameInProgress = false;
Repaint();
}
public void CreateGameFailed()
{
_createGameInProgress = false;
Repaint();
}
public void SwitchToGuideStep()
{
TourStep = 5;
}
private string GetGuideStepTitle(int step)
{
switch(step)
{
case 1:
return "1. SETUP GAME KEYS";
case 2:
return "2. ADD GAMEANALYTICS OBJECT";
case 3:
return "3. START TRACKING EVENTS";
case 4:
return "4. TRACK REAL MONEY TRANSACTIONS";
case 5:
return "5. BALANCE VIRTUAL ECONOMY";
case 6:
return "6. TRACK PLAYER PROGRESSION";
case 7:
return "7. USE CUSTOM DESIGN EVENTS";
case 8:
return "8. LOG ERROR EVENTS";
case 9:
return "9. USE CUSTOM DIMENSIONS";
case 10:
return "10. BUILD AND COMPLETE INTEGRATION";
default:
return "-";
}
}
private StringWithType[] GetGuideStepText(int step)
{
switch(step)
{
case 1:
return new StringWithType[] {
new StringWithType { Text = "The unique game and secret key are used to authenticate your game. If you're logged into GameAnalytics, in Settings under the Account tab, choose your studio and game to sync your keys with your Unity project. If you don't have an account, choose Sign up to create your account and game." },
new StringWithType { Text = "You can also input your keys manually in Settings under the Setup tab. The keys can always be found under Game Settings in the webtool." },
new StringWithType { Text = "" },
new StringWithType {
Text = "Click here to learn more about the Game and Secret keys.",
Type = StringType.Link,
Link = "https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/Settings#setup"
},
};
case 2:
return new StringWithType[] {
new StringWithType { Text = "To use GameAnalytics you need to add the GameAnalytics object to your starting scene. To add this object go to Window/GameAnalytics/Create GameAnalytics Object." },
new StringWithType { Text = "Now you're set up to start tracking data - it's that easy! Out of the box GameAnalytics will give you access to lots of core metrics, such as daily active users (DAU), without implementing any custom events." },
new StringWithType { Text = "" },
new StringWithType {
Text = "Click here to learn more about the full list of core metrics and dimensions.",
Type = StringType.Link,
Link = "http://www.gameanalytics.com/docs/metric-and-dimensions-reference/"
}
};
case 3:
return new StringWithType[] {
new StringWithType { Text = "GameAnalytics supports 5 different types of events: Business, Resource, Progression, Error and Design." },
new StringWithType { Text = "To send an event, remember to include the namespace GameAnalyticsSDK:" },
new StringWithType {
Text = "using GameAnalyticsSDK;",
Type = StringType.TextBox
},
new StringWithType { Text = "" },
new StringWithType { Text = "The next steps will guide you through the instrumentation of each of the different event types." },
};
case 4:
return new StringWithType[] {
new StringWithType { Text = "With the Business event, you can include information on the specific type of in-app item purchased, and where in the game the purchase was made. Additionally, the GameAnalytics SDK captures the app store receipt to validate the purchases." },
new StringWithType { Text = "To add a business event call the following function:" },
new StringWithType {
Text = "GameAnalytics.NewBusinessEvent (string currency, int amount, string itemType, string itemId, string cartType, string receipt, bool autoFetchReceipt);",
Type = StringType.TextBox
},
new StringWithType { Text = "" },
new StringWithType {
Text = "Click here to learn more about the Business event and purchase validation.",
Type = StringType.Link,
Link = "https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/Business%20Event"
}
};
case 5:
return new StringWithType[] {
new StringWithType { Text = "Resources events are used to track your in-game economy. From setting up the event you will be able to see three types of events in the tool. Flow, the total balance from currency spent and rewarded. Sink is all currency spent on items, and lastly source, being all currency rewarded in game." },
new StringWithType { Text = "To add a resource event call the following function:" },
new StringWithType {
Text = "GameAnalytics.NewResourceEvent (GA_Resource.GAResourceFlowType flowType, string resourceType, float amount, string itemType, string itemId);",
Type = StringType.TextBox
},
new StringWithType { Text = "Please note that any Resource Currencies and Resource Item Types you want to use must first be defined in Settings, under the Setup tab. Any value which is not defined will be ignored." },
new StringWithType { Text = "" },
new StringWithType {
Text = "Click here to learn more about the Resource event.",
Type = StringType.Link,
Link = "https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/Resource%20Event"
}
};
case 6:
return new StringWithType[] {
new StringWithType { Text = "Use this event to track when players start and finish levels in your game. This event follows a 3 tier hierarchy structure (World, Level and Phase) to indicate a player's path or place in the game." },
new StringWithType { Text = "To add a progression event call the following function:" },
new StringWithType {
Text = "GameAnalytics.NewProgressionEvent (GA_Progression.GAProgressionStatus progressionStatus, string progression01, string progression02);",
Type = StringType.TextBox
},
new StringWithType { Text = "" },
new StringWithType {
Text = "Click here to learn more about the Progression event.",
Type = StringType.Link,
Link = "https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/Progression%20Event"
}
};
case 7:
return new StringWithType[] {
new StringWithType { Text = "Track any other concept in your game using this event type. For example, you could use this event to track GUI elements or tutorial steps. Custom dimensions are not supported on this event type." },
new StringWithType { Text = "To add a design event call the following function:" },
new StringWithType {
Text = "GameAnalytics.NewDesignEvent (string eventName, float eventValue);",
Type = StringType.TextBox
},
new StringWithType { Text = "" },
new StringWithType {
Text = "Click here to learn more about the Design event.",
Type = StringType.Link,
Link = "https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/Design%20Event"
}
};
case 8:
return new StringWithType[] {
new StringWithType { Text = "You can use the Error event to log errors or warnings that players generate in your game. You can group the events by severity level and attach a message, such as the stack trace." },
new StringWithType { Text = "To add a custom error event call the following function:" },
new StringWithType {
Text = "GameAnalytics.NewErrorEvent (GA_Error.GAErrorSeverity severity, string message);",
Type = StringType.TextBox
},
new StringWithType { Text = "" },
new StringWithType {
Text = "Click here to learn more about the Error event.",
Type = StringType.Link,
Link = "https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/Error%20Event"
}
};
case 9:
return new StringWithType[] {
new StringWithType { Text = "Custom Dimensions can be used to filter your data in the GameAnalytics webtool. To add custom dimensions to your events you will first have to create a list of all the allowed values. You can do this in Settings under the Setup tab. Any value which is not defined will be ignored." },
new StringWithType { Text = "For example, to set Custom Dimension 01, call the following function:" },
new StringWithType {
Text = "GameAnalytics.SetCustomDimension01(string customDimension);",
Type = StringType.TextBox
},
new StringWithType { Text = "" },
new StringWithType {
Text = "Click here to learn more about Custom Dimensions.",
Type = StringType.Link,
Link = "https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/Set%20Custom%20Dimension"
}
};
case 10:
return new StringWithType[] {
new StringWithType { Text = "You're almost there! To complete the integration and start sending data to GameAnalytics, all you need to do is build and run your game. The link below describes the important last steps you need to complete to build for your platform." },
new StringWithType { Text = "" },
#if UNITY_IOS
new StringWithType {
Text = "iOS",
Type = StringType.Link,
Link = "https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/iOS%20Build"
}
#elif UNITY_ANDROID
new StringWithType {
Text = "Android",
Type = StringType.Link,
Link = "https://github.com/GameAnalytics/GA-SDK-UNITY/wiki/Android%20Build"
}
#else
new StringWithType { Text = "Your selected build platform is not currently supported by GameAnalytics." },
new StringWithType { Text = "Read about our supported platforms.", Type = StringType.Link, Link = "http://www.gameanalytics.com/docs" },
#endif
};
default:
return new StringWithType[] {
new StringWithType { Text = "-" }
};
}
}
private string GetGuideStepNext(int step)
{
switch(step)
{
case 1:
return "In the next step we look at how to add the GameAnalytics object.";
case 2:
return "In the next step we look at how to start tracking events.";
case 3:
return "In the next step we look at how to track real money transactions.";
case 4:
return "In the next step we look at how to balance your virtual economy.";
case 5:
return "In the next step we look at how to track player progression.";
case 6:
return "In the next step we look at how to use custom design events.";
case 7:
return "In the next step we look at how to log error events.";
case 8:
return "In the next step we look at how to use custom dimensions.";
case 9:
return "In the last step we look at completing the integration.";
case 10:
return "Thank you for choosing GameAnalytics!";
default:
return "-";
}
}
private void PaintAppStoreIcon(string storeName)
{
switch(storeName)
{
case "amazon_appstore":
if(GameAnalytics.SettingsGA.AmazonIcon != null)
{
//GUILayout.Label("", GUILayout.Height(-20));
GUILayout.Label(GameAnalytics.SettingsGA.AmazonIcon, new GUILayoutOption[] {
GUILayout.Width(20),
GUILayout.MaxHeight(20)
});
}
GUILayout.Label("Amazon", GUILayout.Width(80));
break;
case "google_play":
if(GameAnalytics.SettingsGA.GooglePlayIcon != null)
{
//GUILayout.Label("", GUILayout.Height(-20));
GUILayout.Label(GameAnalytics.SettingsGA.GooglePlayIcon, new GUILayoutOption[] {
GUILayout.Width(20),
GUILayout.MaxHeight(20)
});
}
GUILayout.Label("Google Play", GUILayout.Width(80));
break;
case "apple":
if(GameAnalytics.SettingsGA.iosIcon != null)
{
//GUILayout.Label("", GUILayout.Height(-20));
GUILayout.Label(GameAnalytics.SettingsGA.iosIcon, new GUILayoutOption[] {
GUILayout.Width(20),
GUILayout.MaxHeight(20)
});
}
GUILayout.Label("iOS", GUILayout.Width(80));
break;
case "apple:mac":
if(GameAnalytics.SettingsGA.macIcon != null)
{
//GUILayout.Label("", GUILayout.Height(-20));
GUILayout.Label(GameAnalytics.SettingsGA.macIcon, new GUILayoutOption[] {
GUILayout.Width(20),
GUILayout.MaxHeight(20)
});
}
GUILayout.Label("Mac", GUILayout.Width(80));
break;
case "windows_phone":
if(GameAnalytics.SettingsGA.windowsPhoneIcon != null)
{
//GUILayout.Label("", GUILayout.Height(-20));
GUILayout.Label(GameAnalytics.SettingsGA.windowsPhoneIcon, new GUILayoutOption[] {
GUILayout.Width(20),
GUILayout.MaxHeight(20)
});
}
GUILayout.Label("Win. Phone", GUILayout.Width(80));
break;
default:
GUILayout.Label(storeName, GUILayout.Width(100));
break;
}
}
public IEnumerator<WWW> GetAppStoreIconTexture(WWW www, string storeName, GA_SignUp signup)
{
yield return www;
try
{
if(string.IsNullOrEmpty(www.error))
{
switch(storeName)
{
case "amazon_appstore":
GameAnalytics.SettingsGA.AmazonIcon = www.texture;
break;
case "google_play":
GameAnalytics.SettingsGA.GooglePlayIcon = www.texture;
break;
case "apple:ios":
GameAnalytics.SettingsGA.iosIcon = www.texture;
break;
case "apple:mac":
GameAnalytics.SettingsGA.macIcon = www.texture;
break;
case "windows_phone":
GameAnalytics.SettingsGA.windowsPhoneIcon = www.texture;
break;
}
signup.Repaint();
}
}
catch
{
}
}
}
public class AppFiguresGame
{
public string Name { get; private set; }
public string AppID { get; private set; }
public string Store { get; private set; }
public string Developer { get; private set; }
public string IconUrl { get; private set; }
public Texture2D Icon { get; private set; }
public AppFiguresGame(string name, string appID, string store, string developer, string iconUrl, GA_SignUp signup)
{
Name = name;
AppID = appID;
Store = store;
Developer = developer;
IconUrl = iconUrl;
WWW www = new WWW(iconUrl);
GA_ContinuationManager.StartCoroutine(GetIconTexture(www, signup), () => www.isDone);
}
private IEnumerator<WWW> GetIconTexture(WWW www, GA_SignUp signup)
{
yield return www;
try
{
if(string.IsNullOrEmpty(www.error))
{
Icon = www.texture;
signup.Repaint();
}
else
{
Debug.LogError("Failed to get icon: " + www.error);
}
}
catch
{
Debug.LogError("Failed to get icon");
}
}
}
}
| |
// ZipConstants.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// HISTORY
// 22-12-2009 DavidPierson Added AES support
// 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7
using System;
using System.Text;
using System.Threading;
namespace ICSharpCode.SharpZipLib.Zip
{
#region Enumerations
/// <summary>
/// Determines how entries are tested to see if they should use Zip64 extensions or not.
/// </summary>
internal enum UseZip64
{
/// <summary>
/// Zip64 will not be forced on entries during processing.
/// </summary>
/// <remarks>An entry can have this overridden if required <see cref="ZipEntry.ForceZip64"></see></remarks>
Off,
/// <summary>
/// Zip64 should always be used.
/// </summary>
On,
/// <summary>
/// #ZipLib will determine use based on entry values when added to archive.
/// </summary>
Dynamic,
}
/// <summary>
/// The kind of compression used for an entry in an archive
/// </summary>
internal enum CompressionMethod
{
/// <summary>
/// A direct copy of the file contents is held in the archive
/// </summary>
Stored = 0,
/// <summary>
/// Common Zip compression method using a sliding dictionary
/// of up to 32KB and secondary compression from Huffman/Shannon-Fano trees
/// </summary>
Deflated = 8,
/// <summary>
/// An extension to deflate with a 64KB window. Not supported by #Zip currently
/// </summary>
Deflate64 = 9,
/// <summary>
/// BZip2 compression. Not supported by #Zip.
/// </summary>
BZip2 = 11,
/// <summary>
/// WinZip special for AES encryption, Now supported by #Zip.
/// </summary>
WinZipAES = 99,
}
/// <summary>
/// Identifies the encryption algorithm used for an entry
/// </summary>
internal enum EncryptionAlgorithm
{
/// <summary>
/// No encryption has been used.
/// </summary>
None = 0,
/// <summary>
/// Encrypted using PKZIP 2.0 or 'classic' encryption.
/// </summary>
PkzipClassic = 1,
/// <summary>
/// DES encryption has been used.
/// </summary>
Des = 0x6601,
/// <summary>
/// RCS encryption has been used for encryption.
/// </summary>
RC2 = 0x6602,
/// <summary>
/// Triple DES encryption with 168 bit keys has been used for this entry.
/// </summary>
TripleDes168 = 0x6603,
/// <summary>
/// Triple DES with 112 bit keys has been used for this entry.
/// </summary>
TripleDes112 = 0x6609,
/// <summary>
/// AES 128 has been used for encryption.
/// </summary>
Aes128 = 0x660e,
/// <summary>
/// AES 192 has been used for encryption.
/// </summary>
Aes192 = 0x660f,
/// <summary>
/// AES 256 has been used for encryption.
/// </summary>
Aes256 = 0x6610,
/// <summary>
/// RC2 corrected has been used for encryption.
/// </summary>
RC2Corrected = 0x6702,
/// <summary>
/// Blowfish has been used for encryption.
/// </summary>
Blowfish = 0x6720,
/// <summary>
/// Twofish has been used for encryption.
/// </summary>
Twofish = 0x6721,
/// <summary>
/// RC4 has been used for encryption.
/// </summary>
RC4 = 0x6801,
/// <summary>
/// An unknown algorithm has been used for encryption.
/// </summary>
Unknown = 0xffff
}
/// <summary>
/// Defines the contents of the general bit flags field for an archive entry.
/// </summary>
[Flags]
internal enum GeneralBitFlags : int
{
/// <summary>
/// Bit 0 if set indicates that the file is encrypted
/// </summary>
Encrypted = 0x0001,
/// <summary>
/// Bits 1 and 2 - Two bits defining the compression method (only for Method 6 Imploding and 8,9 Deflating)
/// </summary>
Method = 0x0006,
/// <summary>
/// Bit 3 if set indicates a trailing data desciptor is appended to the entry data
/// </summary>
Descriptor = 0x0008,
/// <summary>
/// Bit 4 is reserved for use with method 8 for enhanced deflation
/// </summary>
ReservedPKware4 = 0x0010,
/// <summary>
/// Bit 5 if set indicates the file contains Pkzip compressed patched data.
/// Requires version 2.7 or greater.
/// </summary>
Patched = 0x0020,
/// <summary>
/// Bit 6 if set indicates strong encryption has been used for this entry.
/// </summary>
StrongEncryption = 0x0040,
/// <summary>
/// Bit 7 is currently unused
/// </summary>
Unused7 = 0x0080,
/// <summary>
/// Bit 8 is currently unused
/// </summary>
Unused8 = 0x0100,
/// <summary>
/// Bit 9 is currently unused
/// </summary>
Unused9 = 0x0200,
/// <summary>
/// Bit 10 is currently unused
/// </summary>
Unused10 = 0x0400,
/// <summary>
/// Bit 11 if set indicates the filename and
/// comment fields for this file must be encoded using UTF-8.
/// </summary>
UnicodeText = 0x0800,
/// <summary>
/// Bit 12 is documented as being reserved by PKware for enhanced compression.
/// </summary>
EnhancedCompress = 0x1000,
/// <summary>
/// Bit 13 if set indicates that values in the local header are masked to hide
/// their actual values, and the central directory is encrypted.
/// </summary>
/// <remarks>
/// Used when encrypting the central directory contents.
/// </remarks>
HeaderMasked = 0x2000,
/// <summary>
/// Bit 14 is documented as being reserved for use by PKware
/// </summary>
ReservedPkware14 = 0x4000,
/// <summary>
/// Bit 15 is documented as being reserved for use by PKware
/// </summary>
ReservedPkware15 = 0x8000
}
#endregion
/// <summary>
/// This class contains constants used for Zip format files
/// </summary>
internal sealed class ZipConstants
{
#region Versions
/// <summary>
/// The version made by field for entries in the central header when created by this library
/// </summary>
/// <remarks>
/// This is also the Zip version for the library when comparing against the version required to extract
/// for an entry. See <see cref="ZipEntry.CanDecompress"/>.
/// </remarks>
public const int VersionMadeBy = 51; // was 45 before AES
/// <summary>
/// The version made by field for entries in the central header when created by this library
/// </summary>
/// <remarks>
/// This is also the Zip version for the library when comparing against the version required to extract
/// for an entry. See <see cref="ZipInputStream.CanDecompressEntry">ZipInputStream.CanDecompressEntry</see>.
/// </remarks>
[Obsolete("Use VersionMadeBy instead")]
public const int VERSION_MADE_BY = 51;
/// <summary>
/// The minimum version required to support strong encryption
/// </summary>
public const int VersionStrongEncryption = 50;
/// <summary>
/// The minimum version required to support strong encryption
/// </summary>
[Obsolete("Use VersionStrongEncryption instead")]
public const int VERSION_STRONG_ENCRYPTION = 50;
/// <summary>
/// Version indicating AES encryption
/// </summary>
public const int VERSION_AES = 51;
/// <summary>
/// The version required for Zip64 extensions (4.5 or higher)
/// </summary>
public const int VersionZip64 = 45;
#endregion
#region Header Sizes
/// <summary>
/// Size of local entry header (excluding variable length fields at end)
/// </summary>
public const int LocalHeaderBaseSize = 30;
/// <summary>
/// Size of local entry header (excluding variable length fields at end)
/// </summary>
[Obsolete("Use LocalHeaderBaseSize instead")]
public const int LOCHDR = 30;
/// <summary>
/// Size of Zip64 data descriptor
/// </summary>
public const int Zip64DataDescriptorSize = 24;
/// <summary>
/// Size of data descriptor
/// </summary>
public const int DataDescriptorSize = 16;
/// <summary>
/// Size of data descriptor
/// </summary>
[Obsolete("Use DataDescriptorSize instead")]
public const int EXTHDR = 16;
/// <summary>
/// Size of central header entry (excluding variable fields)
/// </summary>
public const int CentralHeaderBaseSize = 46;
/// <summary>
/// Size of central header entry
/// </summary>
[Obsolete("Use CentralHeaderBaseSize instead")]
public const int CENHDR = 46;
/// <summary>
/// Size of end of central record (excluding variable fields)
/// </summary>
public const int EndOfCentralRecordBaseSize = 22;
/// <summary>
/// Size of end of central record (excluding variable fields)
/// </summary>
[Obsolete("Use EndOfCentralRecordBaseSize instead")]
public const int ENDHDR = 22;
/// <summary>
/// Size of 'classic' cryptographic header stored before any entry data
/// </summary>
public const int CryptoHeaderSize = 12;
/// <summary>
/// Size of cryptographic header stored before entry data
/// </summary>
[Obsolete("Use CryptoHeaderSize instead")]
public const int CRYPTO_HEADER_SIZE = 12;
#endregion
#region Header Signatures
/// <summary>
/// Signature for local entry header
/// </summary>
public const int LocalHeaderSignature = 'P' | ('K' << 8) | (3 << 16) | (4 << 24);
/// <summary>
/// Signature for local entry header
/// </summary>
[Obsolete("Use LocalHeaderSignature instead")]
public const int LOCSIG = 'P' | ('K' << 8) | (3 << 16) | (4 << 24);
/// <summary>
/// Signature for spanning entry
/// </summary>
public const int SpanningSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for spanning entry
/// </summary>
[Obsolete("Use SpanningSignature instead")]
public const int SPANNINGSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for temporary spanning entry
/// </summary>
public const int SpanningTempSignature = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24);
/// <summary>
/// Signature for temporary spanning entry
/// </summary>
[Obsolete("Use SpanningTempSignature instead")]
public const int SPANTEMPSIG = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24);
/// <summary>
/// Signature for data descriptor
/// </summary>
/// <remarks>
/// This is only used where the length, Crc, or compressed size isnt known when the
/// entry is created and the output stream doesnt support seeking.
/// The local entry cannot be 'patched' with the correct values in this case
/// so the values are recorded after the data prefixed by this header, as well as in the central directory.
/// </remarks>
public const int DataDescriptorSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for data descriptor
/// </summary>
/// <remarks>
/// This is only used where the length, Crc, or compressed size isnt known when the
/// entry is created and the output stream doesnt support seeking.
/// The local entry cannot be 'patched' with the correct values in this case
/// so the values are recorded after the data prefixed by this header, as well as in the central directory.
/// </remarks>
[Obsolete("Use DataDescriptorSignature instead")]
public const int EXTSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for central header
/// </summary>
[Obsolete("Use CentralHeaderSignature instead")]
public const int CENSIG = 'P' | ('K' << 8) | (1 << 16) | (2 << 24);
/// <summary>
/// Signature for central header
/// </summary>
public const int CentralHeaderSignature = 'P' | ('K' << 8) | (1 << 16) | (2 << 24);
/// <summary>
/// Signature for Zip64 central file header
/// </summary>
public const int Zip64CentralFileHeaderSignature = 'P' | ('K' << 8) | (6 << 16) | (6 << 24);
/// <summary>
/// Signature for Zip64 central file header
/// </summary>
[Obsolete("Use Zip64CentralFileHeaderSignature instead")]
public const int CENSIG64 = 'P' | ('K' << 8) | (6 << 16) | (6 << 24);
/// <summary>
/// Signature for Zip64 central directory locator
/// </summary>
public const int Zip64CentralDirLocatorSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24);
/// <summary>
/// Signature for archive extra data signature (were headers are encrypted).
/// </summary>
public const int ArchiveExtraDataSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24);
/// <summary>
/// Central header digitial signature
/// </summary>
public const int CentralHeaderDigitalSignature = 'P' | ('K' << 8) | (5 << 16) | (5 << 24);
/// <summary>
/// Central header digitial signature
/// </summary>
[Obsolete("Use CentralHeaderDigitalSignaure instead")]
public const int CENDIGITALSIG = 'P' | ('K' << 8) | (5 << 16) | (5 << 24);
/// <summary>
/// End of central directory record signature
/// </summary>
public const int EndOfCentralDirectorySignature = 'P' | ('K' << 8) | (5 << 16) | (6 << 24);
/// <summary>
/// End of central directory record signature
/// </summary>
[Obsolete("Use EndOfCentralDirectorySignature instead")]
public const int ENDSIG = 'P' | ('K' << 8) | (5 << 16) | (6 << 24);
#endregion
// This isnt so great but is better than nothing.
// Trying to work out an appropriate OEM code page would be good.
// 850 is a good default for english speakers particularly in Europe.
static string defaultCodePage = Encoding.UTF8.WebName;
/// <summary>
/// Default encoding used for string conversion. 0 gives the default system OEM code page.
/// Dont use unicode encodings if you want to be Zip compatible!
/// Using the default code page isnt the full solution neccessarily
/// there are many variable factors, codepage 850 is often a good choice for
/// European users, however be careful about compatability.
/// </summary>
public static string DefaultCodePage {
get {
return defaultCodePage;
}
set {
defaultCodePage = value;
}
}
/// <summary>
/// Convert a portion of a byte array to a string.
/// </summary>
/// <param name="data">
/// Data to convert to string
/// </param>
/// <param name="count">
/// Number of bytes to convert starting from index 0
/// </param>
/// <returns>
/// data[0]..data[length - 1] converted to a string
/// </returns>
public static string ConvertToString(byte[] data, int count)
{
if ( data == null ) {
return string.Empty;
}
return Encoding.GetEncoding(DefaultCodePage).GetString(data, 0, count);
}
/// <summary>
/// Convert a byte array to string
/// </summary>
/// <param name="data">
/// Byte array to convert
/// </param>
/// <returns>
/// <paramref name="data">data</paramref>converted to a string
/// </returns>
public static string ConvertToString(byte[] data)
{
if ( data == null ) {
return string.Empty;
}
return ConvertToString(data, data.Length);
}
/// <summary>
/// Convert a byte array to string
/// </summary>
/// <param name="flags">The applicable general purpose bits flags</param>
/// <param name="data">
/// Byte array to convert
/// </param>
/// <param name="count">The number of bytes to convert.</param>
/// <returns>
/// <paramref name="data">data</paramref>converted to a string
/// </returns>
public static string ConvertToStringExt(int flags, byte[] data, int count)
{
if ( data == null ) {
return string.Empty;
}
if ( (flags & (int)GeneralBitFlags.UnicodeText) != 0 ) {
return Encoding.UTF8.GetString(data, 0, count);
}
else {
return ConvertToString(data, count);
}
}
/// <summary>
/// Convert a byte array to string
/// </summary>
/// <param name="data">
/// Byte array to convert
/// </param>
/// <param name="flags">The applicable general purpose bits flags</param>
/// <returns>
/// <paramref name="data">data</paramref>converted to a string
/// </returns>
public static string ConvertToStringExt(int flags, byte[] data)
{
if ( data == null ) {
return string.Empty;
}
if ( (flags & (int)GeneralBitFlags.UnicodeText) != 0 ) {
return Encoding.UTF8.GetString(data, 0, data.Length);
}
else {
return ConvertToString(data, data.Length);
}
}
/// <summary>
/// Convert a string to a byte array
/// </summary>
/// <param name="str">
/// String to convert to an array
/// </param>
/// <returns>Converted array</returns>
public static byte[] ConvertToArray(string str)
{
if ( str == null ) {
return new byte[0];
}
return Encoding.GetEncoding(DefaultCodePage).GetBytes(str);
}
/// <summary>
/// Convert a string to a byte array
/// </summary>
/// <param name="flags">The applicable <see cref="GeneralBitFlags">general purpose bits flags</see></param>
/// <param name="str">
/// String to convert to an array
/// </param>
/// <returns>Converted array</returns>
public static byte[] ConvertToArray(int flags, string str)
{
if (str == null) {
return new byte[0];
}
if ((flags & (int)GeneralBitFlags.UnicodeText) != 0) {
return Encoding.UTF8.GetBytes(str);
}
else {
return ConvertToArray(str);
}
}
/// <summary>
/// Initialise default instance of <see cref="ZipConstants">ZipConstants</see>
/// </summary>
/// <remarks>
/// Private to prevent instances being created.
/// </remarks>
ZipConstants()
{
// Do nothing
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.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 OpenSimulator 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 log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.HypergridService
{
/// <summary>
/// This service is for HG1.5 only, to make up for the fact that clients don't
/// keep any private information in themselves, and that their 'home service'
/// needs to do it for them.
/// Once we have better clients, this shouldn't be needed.
/// </summary>
public class UserAgentService : UserAgentServiceBase, IUserAgentService
{
protected static bool m_BypassClientVerification;
protected static IFriendsSimConnector m_FriendsLocalSimConnector;
protected static IFriendsService m_FriendsService;
// standalone, points to HGFriendsModule
protected static FriendsSimConnector m_FriendsSimConnector;
protected static GatekeeperServiceConnector m_GatekeeperConnector;
protected static IGatekeeperService m_GatekeeperService;
protected static string m_GridName;
protected static IGridService m_GridService;
protected static IGridUserService m_GridUserService;
// grid
protected static int m_LevelOutsideContacts;
protected static IPresenceService m_PresenceService;
protected static IUserAccountService m_UserAccountService;
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// This will need to go into a DB table
//static Dictionary<UUID, TravelingAgentInfo> m_Database = new Dictionary<UUID, TravelingAgentInfo>();
private static Dictionary<int, bool> m_ForeignTripsAllowed = new Dictionary<int, bool>();
private static bool m_Initialized = false;
private static Dictionary<int, List<string>> m_TripsAllowedExceptions = new Dictionary<int, List<string>>();
private static Dictionary<int, List<string>> m_TripsDisallowedExceptions = new Dictionary<int, List<string>>();
public UserAgentService(IConfigSource config)
: this(config, null)
{
}
public UserAgentService(IConfigSource config, IFriendsSimConnector friendsConnector)
: base(config)
{
// Let's set this always, because we don't know the sequence
// of instantiations
if (friendsConnector != null)
m_FriendsLocalSimConnector = friendsConnector;
if (!m_Initialized)
{
m_Initialized = true;
m_log.DebugFormat("[HOME USERS SECURITY]: Starting...");
m_FriendsSimConnector = new FriendsSimConnector();
IConfig serverConfig = config.Configs["UserAgentService"];
if (serverConfig == null)
throw new Exception(String.Format("No section UserAgentService in config file"));
string gridService = serverConfig.GetString("GridService", String.Empty);
string gridUserService = serverConfig.GetString("GridUserService", String.Empty);
string gatekeeperService = serverConfig.GetString("GatekeeperService", String.Empty);
string friendsService = serverConfig.GetString("FriendsService", String.Empty);
string presenceService = serverConfig.GetString("PresenceService", String.Empty);
string userAccountService = serverConfig.GetString("UserAccountService", String.Empty);
m_BypassClientVerification = serverConfig.GetBoolean("BypassClientVerification", false);
if (gridService == string.Empty || gridUserService == string.Empty || gatekeeperService == string.Empty)
throw new Exception(String.Format("Incomplete specifications, UserAgent Service cannot function."));
Object[] args = new Object[] { config };
m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args);
m_GatekeeperConnector = new GatekeeperServiceConnector();
m_GatekeeperService = ServerUtils.LoadPlugin<IGatekeeperService>(gatekeeperService, args);
m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(friendsService, args);
m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(userAccountService, args);
m_LevelOutsideContacts = serverConfig.GetInt("LevelOutsideContacts", 0);
LoadTripPermissionsFromConfig(serverConfig, "ForeignTripsAllowed");
LoadDomainExceptionsFromConfig(serverConfig, "AllowExcept", m_TripsAllowedExceptions);
LoadDomainExceptionsFromConfig(serverConfig, "DisallowExcept", m_TripsDisallowedExceptions);
m_GridName = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "UserAgentService" }, String.Empty);
if (string.IsNullOrEmpty(m_GridName)) // Legacy. Remove soon.
{
m_GridName = serverConfig.GetString("ExternalName", string.Empty);
if (m_GridName == string.Empty)
{
serverConfig = config.Configs["GatekeeperService"];
m_GridName = serverConfig.GetString("ExternalName", string.Empty);
}
}
if (!m_GridName.EndsWith("/"))
m_GridName = m_GridName + "/";
// Finally some cleanup
m_Database.DeleteOld();
}
}
public GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt)
{
position = new Vector3(128, 128, 0); lookAt = Vector3.UnitY;
m_log.DebugFormat("[USER AGENT SERVICE]: Request to get home region of user {0}", userID);
GridRegion home = null;
GridUserInfo uinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
if (uinfo != null)
{
if (uinfo.HomeRegionID != UUID.Zero)
{
home = m_GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
position = uinfo.HomePosition;
lookAt = uinfo.HomeLookAt;
}
if (home == null)
{
List<GridRegion> defs = m_GridService.GetDefaultRegions(UUID.Zero);
if (defs != null && defs.Count > 0)
home = defs[0];
}
}
return home;
}
public List<UUID> GetOnlineFriends(UUID foreignUserID, List<string> friends)
{
List<UUID> online = new List<UUID>();
if (m_FriendsService == null || m_PresenceService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get online friends because friends or presence services are missing");
return online;
}
m_log.DebugFormat("[USER AGENT SERVICE]: Foreign user {0} wants to know status of {1} local friends", foreignUserID, friends.Count);
// First, let's double check that the reported friends are, indeed, friends of that user
// And let's check that the secret matches and the rights
List<string> usersToBeNotified = new List<string>();
foreach (string uui in friends)
{
UUID localUserID;
string secret = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
{
FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
foreach (FriendInfo finfo in friendInfos)
{
if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret) &&
(finfo.TheirFlags & (int)FriendRights.CanSeeOnline) != 0 && (finfo.TheirFlags != -1))
{
// great!
usersToBeNotified.Add(localUserID.ToString());
}
}
}
}
// Now, let's find out their status
m_log.DebugFormat("[USER AGENT SERVICE]: GetOnlineFriends: user has {0} local friends with status rights", usersToBeNotified.Count);
// First, let's send notifications to local users who are online in the home grid
PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
if (friendSessions != null && friendSessions.Length > 0)
{
foreach (PresenceInfo pi in friendSessions)
{
UUID presenceID;
if (UUID.TryParse(pi.UserID, out presenceID))
online.Add(presenceID);
}
}
return online;
}
public Dictionary<string, object> GetServerURLs(UUID userID)
{
if (m_UserAccountService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get server URLs because user account service is missing");
return new Dictionary<string, object>();
}
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero /*!!!*/, userID);
if (account != null)
return account.ServiceURLs;
return new Dictionary<string, object>();
}
public Dictionary<string, object> GetUserInfo(UUID userID)
{
Dictionary<string, object> info = new Dictionary<string, object>();
if (m_UserAccountService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get user flags because user account service is missing");
info["result"] = "fail";
info["message"] = "UserAccountService is missing!";
return info;
}
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero /*!!!*/, userID);
if (account != null)
{
info.Add("user_flags", (object)account.UserFlags);
info.Add("user_created", (object)account.Created);
info.Add("user_title", (object)account.UserTitle);
info.Add("result", "success");
}
return info;
}
public string GetUUI(UUID userID, UUID targetUserID)
{
// Let's see if it's a local user
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, targetUserID);
if (account != null)
return targetUserID.ToString() + ";" + m_GridName + ";" + account.FirstName + " " + account.LastName;
// Let's try the list of friends
FriendInfo[] friends = m_FriendsService.GetFriends(userID);
if (friends != null && friends.Length > 0)
{
foreach (FriendInfo f in friends)
if (f.Friend.StartsWith(targetUserID.ToString()))
{
// Let's remove the secret
UUID id; string tmp = string.Empty, secret = string.Empty;
if (Util.ParseUniversalUserIdentifier(f.Friend, out id, out tmp, out tmp, out tmp, out secret))
return f.Friend.Replace(secret, "0");
}
}
return string.Empty;
}
public UUID GetUUID(String first, String last)
{
// Let's see if it's a local user
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, first, last);
if (account != null)
{
// check user level
if (account.UserLevel < m_LevelOutsideContacts)
return UUID.Zero;
else
return account.PrincipalID;
}
else
return UUID.Zero;
}
// We need to prevent foreign users with the same UUID as a local user
public bool IsAgentComingHome(UUID sessionID, string thisGridExternalName)
{
HGTravelingData hgt = m_Database.Get(sessionID);
if (hgt == null)
return false;
TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
return travel.GridExternalName.ToLower() == thisGridExternalName.ToLower();
}
public string LocateUser(UUID userID)
{
HGTravelingData[] hgts = m_Database.GetSessions(userID);
if (hgts == null)
return string.Empty;
foreach (HGTravelingData t in hgts)
if (t.Data.ContainsKey("GridExternalName") && !m_GridName.Equals(t.Data["GridExternalName"]))
return t.Data["GridExternalName"];
return string.Empty;
}
public bool LoginAgentToGrid(GridRegion source, AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, bool fromLogin, out string reason)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Request to login user {0} {1} (@{2}) to grid {3}",
agentCircuit.firstname, agentCircuit.lastname, (fromLogin ? agentCircuit.IPAddress : "stored IP"), gatekeeper.ServerURI);
string gridName = gatekeeper.ServerURI;
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, agentCircuit.AgentID);
if (account == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Someone attempted to lauch a foreign user from here {0} {1}", agentCircuit.firstname, agentCircuit.lastname);
reason = "Forbidden to launch your agents from here";
return false;
}
// Is this user allowed to go there?
if (m_GridName != gridName)
{
if (m_ForeignTripsAllowed.ContainsKey(account.UserLevel))
{
bool allowed = m_ForeignTripsAllowed[account.UserLevel];
if (m_ForeignTripsAllowed[account.UserLevel] && IsException(gridName, account.UserLevel, m_TripsAllowedExceptions))
allowed = false;
if (!m_ForeignTripsAllowed[account.UserLevel] && IsException(gridName, account.UserLevel, m_TripsDisallowedExceptions))
allowed = true;
if (!allowed)
{
reason = "Your world does not allow you to visit the destination";
m_log.InfoFormat("[USER AGENT SERVICE]: Agents not permitted to visit {0}. Refusing service.", gridName);
return false;
}
}
}
// Take the IP address + port of the gatekeeper (reg) plus the info of finalDestination
GridRegion region = new GridRegion(gatekeeper);
region.ServerURI = gatekeeper.ServerURI;
region.ExternalHostName = finalDestination.ExternalHostName;
region.InternalEndPoint = finalDestination.InternalEndPoint;
region.RegionName = finalDestination.RegionName;
region.RegionID = finalDestination.RegionID;
region.RegionLocX = finalDestination.RegionLocX;
region.RegionLocY = finalDestination.RegionLocY;
// Generate a new service session
agentCircuit.ServiceSessionID = region.ServerURI + ";" + UUID.Random();
TravelingAgentInfo old = null;
TravelingAgentInfo travel = CreateTravelInfo(agentCircuit, region, fromLogin, out old);
bool success = false;
string myExternalIP = string.Empty;
m_log.DebugFormat("[USER AGENT SERVICE]: this grid: {0}, desired grid: {1}, desired region: {2}", m_GridName, gridName, region.RegionID);
if (m_GridName == gridName)
{
success = m_GatekeeperService.LoginAgent(source, agentCircuit, finalDestination, out reason);
}
else
{
success = m_GatekeeperConnector.CreateAgent(source, region, agentCircuit, (uint)Constants.TeleportFlags.ViaLogin, out myExternalIP, out reason);
}
if (!success)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Unable to login user {0} {1} to grid {2}, reason: {3}",
agentCircuit.firstname, agentCircuit.lastname, region.ServerURI, reason);
if (old != null)
StoreTravelInfo(old);
else
m_Database.Delete(agentCircuit.SessionID);
return false;
}
// Everything is ok
// Update the perceived IP Address of our grid
m_log.DebugFormat("[USER AGENT SERVICE]: Gatekeeper sees me as {0}", myExternalIP);
travel.MyIpAddress = myExternalIP;
StoreTravelInfo(travel);
return true;
}
public bool LoginAgentToGrid(GridRegion source, AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, out string reason)
{
reason = string.Empty;
return LoginAgentToGrid(source, agentCircuit, gatekeeper, finalDestination, false, out reason);
}
public void LogoutAgent(UUID userID, UUID sessionID)
{
m_log.DebugFormat("[USER AGENT SERVICE]: User {0} logged out", userID);
m_Database.Delete(sessionID);
GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
if (guinfo != null)
m_GridUserService.LoggedOut(userID.ToString(), sessionID, guinfo.LastRegionID, guinfo.LastPosition, guinfo.LastLookAt);
}
[Obsolete]
public List<UUID> StatusNotification(List<string> friends, UUID foreignUserID, bool online)
{
if (m_FriendsService == null || m_PresenceService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to perform status notifications because friends or presence services are missing");
return new List<UUID>();
}
List<UUID> localFriendsOnline = new List<UUID>();
m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: foreign user {0} wants to notify {1} local friends", foreignUserID, friends.Count);
// First, let's double check that the reported friends are, indeed, friends of that user
// And let's check that the secret matches
List<string> usersToBeNotified = new List<string>();
foreach (string uui in friends)
{
UUID localUserID;
string secret = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
{
FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
foreach (FriendInfo finfo in friendInfos)
{
if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret))
{
// great!
usersToBeNotified.Add(localUserID.ToString());
}
}
}
}
// Now, let's send the notifications
m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: user has {0} local friends", usersToBeNotified.Count);
// First, let's send notifications to local users who are online in the home grid
PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = null;
foreach (PresenceInfo pinfo in friendSessions)
if (pinfo.RegionID != UUID.Zero) // let's guard against traveling agents
{
friendSession = pinfo;
break;
}
if (friendSession != null)
{
ForwardStatusNotificationToSim(friendSession.RegionID, foreignUserID, friendSession.UserID, online);
usersToBeNotified.Remove(friendSession.UserID.ToString());
UUID id;
if (UUID.TryParse(friendSession.UserID, out id))
localFriendsOnline.Add(id);
}
}
//// Lastly, let's notify the rest who may be online somewhere else
//foreach (string user in usersToBeNotified)
//{
// UUID id = new UUID(user);
// if (m_Database.ContainsKey(id) && m_Database[id].GridExternalName != m_GridName)
// {
// string url = m_Database[id].GridExternalName;
// // forward
// m_log.WarnFormat("[USER AGENT SERVICE]: User {0} is visiting {1}. HG Status notifications still not implemented.", user, url);
// }
//}
// and finally, let's send the online friends
if (online)
{
return localFriendsOnline;
}
else
return new List<UUID>();
}
public bool VerifyAgent(UUID sessionID, string token)
{
HGTravelingData hgt = m_Database.Get(sessionID);
if (hgt == null)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Token verification for session {0}: no such session", sessionID);
return false;
}
TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
m_log.DebugFormat("[USER AGENT SERVICE]: Verifying agent token {0} against {1}", token, travel.ServiceToken);
return travel.ServiceToken == token;
}
public bool VerifyClient(UUID sessionID, string reportedIP)
{
if (m_BypassClientVerification)
return true;
m_log.DebugFormat("[USER AGENT SERVICE]: Verifying Client session {0} with reported IP {1}.",
sessionID, reportedIP);
HGTravelingData hgt = m_Database.Get(sessionID);
if (hgt == null)
return false;
TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
bool result = travel.ClientIPAddress == reportedIP || travel.MyIpAddress == reportedIP; // NATed
m_log.DebugFormat("[USER AGENT SERVICE]: Comparing {0} with login IP {1} and MyIP {1}; result is {3}",
reportedIP, travel.ClientIPAddress, travel.MyIpAddress, result);
return result;
}
[Obsolete]
protected void ForwardStatusNotificationToSim(UUID regionID, UUID foreignUserID, string user, bool online)
{
UUID userID;
if (UUID.TryParse(user, out userID))
{
if (m_FriendsLocalSimConnector != null)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Local Notify, user {0} is {1}", foreignUserID, (online ? "online" : "offline"));
m_FriendsLocalSimConnector.StatusNotify(foreignUserID, userID, online);
}
else
{
GridRegion region = m_GridService.GetRegionByUUID(UUID.Zero /* !!! */, regionID);
if (region != null)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Remote Notify to region {0}, user {1} is {2}", region.RegionName, foreignUserID, (online ? "online" : "offline"));
m_FriendsSimConnector.StatusNotify(region, foreignUserID, userID.ToString(), online);
}
}
}
}
protected void LoadDomainExceptionsFromConfig(IConfig config, string variable, Dictionary<int, List<string>> exceptions)
{
foreach (string keyName in config.GetKeys())
{
if (keyName.StartsWith(variable + "_Level_"))
{
int level = 0;
if (Int32.TryParse(keyName.Replace(variable + "_Level_", ""), out level) && !exceptions.ContainsKey(level))
{
exceptions.Add(level, new List<string>());
string value = config.GetString(keyName, string.Empty);
string[] parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in parts)
exceptions[level].Add(s.Trim());
}
}
}
}
protected void LoadTripPermissionsFromConfig(IConfig config, string variable)
{
foreach (string keyName in config.GetKeys())
{
if (keyName.StartsWith(variable + "_Level_"))
{
int level = 0;
if (Int32.TryParse(keyName.Replace(variable + "_Level_", ""), out level))
m_ForeignTripsAllowed.Add(level, config.GetBoolean(keyName, true));
}
}
}
private TravelingAgentInfo CreateTravelInfo(AgentCircuitData agentCircuit, GridRegion region, bool fromLogin, out TravelingAgentInfo existing)
{
HGTravelingData hgt = m_Database.Get(agentCircuit.SessionID);
existing = null;
if (hgt != null)
{
// Very important! Override whatever this agent comes with.
// UserAgentService always sets the IP for every new agent
// with the original IP address.
existing = new TravelingAgentInfo(hgt);
agentCircuit.IPAddress = existing.ClientIPAddress;
}
TravelingAgentInfo travel = new TravelingAgentInfo(existing);
travel.SessionID = agentCircuit.SessionID;
travel.UserID = agentCircuit.AgentID;
travel.GridExternalName = region.ServerURI;
travel.ServiceToken = agentCircuit.ServiceSessionID;
if (fromLogin)
travel.ClientIPAddress = agentCircuit.IPAddress;
StoreTravelInfo(travel);
return travel;
}
#region Misc
private bool IsException(string dest, int level, Dictionary<int, List<string>> exceptions)
{
if (!exceptions.ContainsKey(level))
return false;
bool exception = false;
if (exceptions[level].Count > 0) // we have exceptions
{
string destination = dest;
if (!destination.EndsWith("/"))
destination += "/";
if (exceptions[level].Find(delegate(string s)
{
if (!s.EndsWith("/"))
s += "/";
return s == destination;
}) != null)
exception = true;
}
return exception;
}
private void StoreTravelInfo(TravelingAgentInfo travel)
{
if (travel == null)
return;
HGTravelingData hgt = new HGTravelingData();
hgt.SessionID = travel.SessionID;
hgt.UserID = travel.UserID;
hgt.Data = new Dictionary<string, string>();
hgt.Data["GridExternalName"] = travel.GridExternalName;
hgt.Data["ServiceToken"] = travel.ServiceToken;
hgt.Data["ClientIPAddress"] = travel.ClientIPAddress;
hgt.Data["MyIPAddress"] = travel.MyIpAddress;
m_Database.Store(hgt);
}
#endregion Misc
}
internal class TravelingAgentInfo
{
public string ClientIPAddress = string.Empty;
public string GridExternalName = string.Empty;
// as seen from this user agent service
public string MyIpAddress = string.Empty;
public string ServiceToken = string.Empty;
public UUID SessionID;
public UUID UserID;
// the user agent service's external IP, as seen from the next gatekeeper
public TravelingAgentInfo(HGTravelingData t)
{
if (t.Data != null)
{
SessionID = new UUID(t.SessionID);
UserID = new UUID(t.UserID);
GridExternalName = t.Data["GridExternalName"];
ServiceToken = t.Data["ServiceToken"];
ClientIPAddress = t.Data["ClientIPAddress"];
MyIpAddress = t.Data["MyIPAddress"];
}
}
public TravelingAgentInfo(TravelingAgentInfo old)
{
if (old != null)
{
SessionID = old.SessionID;
UserID = old.UserID;
GridExternalName = old.GridExternalName;
ServiceToken = old.ServiceToken;
ClientIPAddress = old.ClientIPAddress;
MyIpAddress = old.MyIpAddress;
}
}
}
}
| |
using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Scintilla;
using Scintilla.Enums;
using Scintilla.Configuration;
namespace Scintilla.Configuration
{
public class ScintillaPropertiesHelper
{
private static IScintillaConfig config;
private ScintillaPropertiesHelper() { }
public static void Populate(IScintillaConfig scintillaConfig, FileInfo file)
{
config = scintillaConfig;
if (config != null)
{
PropertiesReader.Read(new ConfigResource(file), PropertyRead);
}
}
public static void Populate(IScintillaConfig scintillaConfig, ConfigResource resource)
{
config = scintillaConfig;
if (config != null)
{
PropertiesReader.Read(resource, PropertyRead);
}
}
private static bool PropertyRead(ConfigResource resource, PropertyType propertyType, Queue<string> keyQueue, string key, string val)
{
bool success = false;
if (config != null)
{
switch (propertyType)
{
case PropertyType.Property:
success = true;
ApplyProperty(keyQueue, key, val);
break;
case PropertyType.If:
if (config.Properties.ContainsKey(val))
{
success = !Convert.ToBoolean(config.Properties[val]);
}
break;
case PropertyType.Import:
ConfigResource res = resource.GetLocalConfigResource(string.Format(@"{0}.properties", val));
success = res.Exists;
break;
}
}
return success;
}
private static void ApplyProperty(Queue<string> keyQueue, string key, string val)
{
string tokenKey = keyQueue.Dequeue();
switch (tokenKey)
{
case "lang":
ApplyLanguageProperty(keyQueue, val);
break;
case "global":
ApplyGlobalProperty(keyQueue, val);
break;
case "lex":
ApplyLexerProperty(keyQueue, val);
break;
case "var":
config.Properties[key.Substring(4)] = Evaluate(val);
break;
default:
ApplyGeneralProperty(key, val);
break;
}
}
private static void ApplyGeneralProperty(string key, string var)
{
string val = Evaluate(var);
switch (key)
{
case "menu-language":
string[] menuItems = val.Split('|');
for (int i = 2; i < menuItems.Length; i += 3)
{
MenuItemConfig menuItem = new MenuItemConfig();
menuItem.Text = menuItems[i - 2];
menuItem.Value = menuItems[i - 1];
menuItem.ShortcutKeys = GetKeys(menuItems[i]);
config.LanguageMenuItems.Add(menuItem);
}
break;
case "language-names":
config.LanguageNames.AddRange(val.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
break;
case "extension-languages":
PropertiesReader.GetKeyValuePairs(val, config.ExtensionLanguages);
break;
case "open-filter":
config.FileOpenFilter = val;
break;
case "default-file-ext":
config.DefaultFileExtention = val;
break;
default:
config.Properties[key] = Evaluate(val);
break;
}
}
#region Apply Lexer Properties
private static void ApplyLexerProperty(Queue<string> keyQueue, string val)
{
if (keyQueue.Count > 1)
{
string lexerName = keyQueue.Dequeue();
string key = keyQueue.Dequeue();
ILexerConfig lexerConf = config.Lexers[lexerName];
switch (key)
{
case "style":
ApplyStyle(lexerConf.Type, lexerConf.Styles, keyQueue, val);
break;
default:
config.Lexers[lexerName].Properties[key] = Evaluate(val);
break;
}
}
}
#endregion
#region Apply Language Properties
private static void ApplyGlobalProperty(Queue<string> keyQueue, string val)
{
if (keyQueue.Count >= 1)
{
ApplyLanguageProperty(config.LanguageDefaults, keyQueue, val);
}
}
private static void ApplyLanguageProperty(Queue<string> keyQueue, string val)
{
if (keyQueue.Count > 1)
{
string langName = keyQueue.Dequeue();
ILanguageConfig langConf = config.Languages[langName];
ApplyLanguageProperty(langConf, keyQueue, val);
}
}
private static void ApplyLanguageProperty(ILanguageConfig langConf, Queue<string> keyQueue, string val)
{
if (keyQueue.Count > 0)
{
string key = keyQueue.Dequeue();
switch (key)
{
case "style":
ApplyStyle(langConf.Lexer.Type, langConf.Styles, keyQueue, val);
break;
case "keywords":
ApplyKeywords(langConf, keyQueue, val);
break;
case "lexer":
langConf.Lexer = config.Lexers[Evaluate(val)];
break;
case "word-characters":
langConf.WordCharacters = Evaluate(val);
break;
case "whitespace-characters":
langConf.WhitespaceCharacters = Evaluate(val);
break;
case "code-page":
langConf.CodePage = GetInt(val);
break;
case "selection-alpha":
langConf.SelectionAlpha = GetInt(val);
break;
case "selection-back":
langConf.SelectionBackColor = GetColor(val, Color.Empty);
break;
case "tabsize":
langConf.TabSize = GetInt(val);
break;
case "indent-size":
langConf.IndentSize = GetInt(val);
break;
case "fold":
langConf.Fold = GetBool(val);
break;
case "fold-compact":
langConf.FoldCompact = GetBool(val);
break;
case "fold-symbols":
langConf.FoldSymbols = GetBool(val);
break;
case "fold-comment":
langConf.FoldComment = GetBool(val);
break;
case "fold-on-open":
langConf.FoldOnOpen = GetBool(val);
break;
case "fold-preprocessor":
langConf.FoldPreprocessor = GetBool(val);
break;
case "fold-html":
langConf.HtmlFold = GetBool(val);
break;
case "fold-html-preprocessor":
langConf.HtmlFoldPreprocessor = GetBool(val);
break;
case "fold-flags":
langConf.FoldFlags = GetInt(val);
break;
case "fold-margin-width":
langConf.FoldMarginWidth = GetInt(val);
break;
case "fold-margin-color":
langConf.FoldMarginColor = GetColor(val, Color.Empty);
break;
case "fold-margin-highlight-color":
langConf.FoldMarginHighlightColor = GetColor(val, Color.Empty);
break;
default:
config.Properties[key] = Evaluate(val);
break;
}
}
}
private static void ApplyKeywords(ILanguageConfig langConf, Queue<string> keyQueue, string var)
{
int styleIndex;
if (keyQueue.Count == 1)
{
string strIndex = keyQueue.Dequeue();
if (!int.TryParse(strIndex, out styleIndex))
{
styleIndex = 0;
}
}
else
{
styleIndex = 0;
}
langConf.KeywordLists[styleIndex] = Evaluate(var);
}
private static void ApplyStyle(Lexer lexerType, SortedDictionary<int, ILexerStyle> styles, Queue<string> keyQueue, string var)
{
int styleIndex;
if (keyQueue.Count == 1)
{
string strIndex = keyQueue.Dequeue();
if (!int.TryParse(strIndex, out styleIndex))
{
if (lexerType != Lexer.Null)
{
object lexStyle = Enum.Parse(Utilities.GetLexerEnumFromLexerType(lexerType), strIndex, true);
styleIndex = (int)lexStyle;
}
else
{
styleIndex = 0;
}
}
}
else
{
styleIndex = 0;
}
ILexerStyle style = new LexerStyle(styleIndex);
string styleData = Evaluate(var);
Dictionary<string, string> dict = PropertiesReader.GetKeyValuePairs(styleData);
foreach (string styleKey in dict.Keys)
{
styleData = dict[styleKey];
switch (styleKey)
{
case "font":
style.FontName = styleData;
break;
case "size":
style.FontSize = Convert.ToInt32(styleData);
break;
case "fore":
style.ForeColor = ColorTranslator.FromHtml(styleData);
break;
case "back":
style.BackColor = ColorTranslator.FromHtml(styleData);
break;
case "italics":
style.Italics = true;
break;
case "notitalics":
style.Italics = false;
break;
case "bold":
style.Bold = true;
break;
case "notbold":
style.Bold = false;
break;
case "eolfilled":
style.EOLFilled = true;
break;
case "noteolfilled":
style.EOLFilled = false;
break;
case "underlined":
style.Underline = true;
break;
case "notunderlined":
style.Underline = false;
break;
case "case":
style.CaseVisibility = ((styleData == "m") ? CaseVisible.Mixed : ((styleData == "u") ? CaseVisible.Upper : CaseVisible.Lower));
break;
}
}
styles[styleIndex] = style;
}
#endregion
#region Evaluating valiables helper methods
private static string Evaluate(string data)
{
return PropertiesReader.Evaluate(data, GetByKey, ContainsKey);
}
private static bool ContainsKey(string key)
{
return config.Properties.ContainsKey(key);
}
private static string GetByKey(string key)
{
return config.Properties[key];
}
#endregion
#region Helper Methods for pulling data out of the scite config files
private static System.Windows.Forms.Keys GetKeys(string data)
{
System.Windows.Forms.Keys shortcutKeys = System.Windows.Forms.Keys.None;
if (!string.IsNullOrEmpty(data))
{
string[] keys = data.Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string key in keys)
{
shortcutKeys = shortcutKeys | (System.Windows.Forms.Keys)Enum.Parse(
typeof(System.Windows.Forms.Keys),
(key.Equals("Ctrl", StringComparison.CurrentCultureIgnoreCase) ? "Control" : key),
true);
}
}
return shortcutKeys;
}
private static Color GetColor(string data, Color colorIfNull)
{
Color val = colorIfNull;
string sval = data;
if (sval != null) val = ColorTranslator.FromHtml(sval);
return val;
}
private static int? GetInt(string data)
{
int? val = null;
string sval = data;
if (sval != null) val = Convert.ToInt32(sval);
return val;
}
private static bool? GetBool(string data)
{
bool? val = null;
string sval = data;
if (sval != null)
{
sval = sval.ToLower();
switch (sval)
{
case "1":
case "y":
case "t":
case "yes":
case "true":
val = true;
break;
default:
val = false;
break;
}
}
return val;
}
#endregion
}
}
| |
#define MCG_WINRT_SUPPORTED
using Mcg.System;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
// -----------------------------------------------------------------------------------------------------------
//
// WARNING: THIS SOURCE FILE IS FOR 32-BIT BUILDS ONLY!
//
// MCG GENERATED CODE
//
// This C# source file is generated by MCG and is added into the application at compile time to support interop features.
//
// It has three primary components:
//
// 1. Public type definitions with interop implementation used by this application including WinRT & COM data structures and P/Invokes.
//
// 2. The 'McgInterop' class containing marshaling code that acts as a bridge from managed code to native code.
//
// 3. The 'McgNative' class containing marshaling code and native type definitions that call into native code and are called by native code.
//
// -----------------------------------------------------------------------------------------------------------
//
// warning CS0067: The event 'event' is never used
#pragma warning disable 67
// warning CS0169: The field 'field' is never used
#pragma warning disable 169
// warning CS0649: Field 'field' is never assigned to, and will always have its default value 0
#pragma warning disable 414
// warning CS0414: The private field 'field' is assigned but its value is never used
#pragma warning disable 649
// warning CS1591: Missing XML comment for publicly visible type or member 'Type_or_Member'
#pragma warning disable 1591
// warning CS0108 'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.
#pragma warning disable 108
// warning CS0114 'member1' hides inherited member 'member2'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.
#pragma warning disable 114
// warning CS0659 'type' overrides Object.Equals but does not override GetHashCode.
#pragma warning disable 659
// warning CS0465 Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?
#pragma warning disable 465
// warning CS0028 'function declaration' has the wrong signature to be an entry point
#pragma warning disable 28
// warning CS0162 Unreachable code Detected
#pragma warning disable 162
// warning CS0628 new protected member declared in sealed class
#pragma warning disable 628
namespace McgInterop
{
/// <summary>
/// P/Invoke class for module '[MRT]'
/// </summary>
public unsafe static partial class _MRT_
{
// Signature, RhWaitForPendingFinalizers, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhWaitForPendingFinalizers")]
public static void RhWaitForPendingFinalizers(int allowReentrantWait)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.RhWaitForPendingFinalizers(allowReentrantWait);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, RhCompatibleReentrantWaitAny, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr___ptr__w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhCompatibleReentrantWaitAny")]
public static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop._MRT__PInvokes.RhCompatibleReentrantWaitAny(
alertable,
timeout,
count,
((global::System.IntPtr*)handles)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, _ecvt_s, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "_ecvt_s")]
public static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes._ecvt_s(
((byte*)buffer),
sizeInBytes,
value,
count,
((int*)dec),
((int*)sign)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, memmove, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "memmove")]
public static void memmove(
byte* dmem,
byte* smem,
uint size)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.memmove(
((byte*)dmem),
((byte*)smem),
size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module '*'
/// </summary>
public unsafe static partial class _
{
// Signature, CallingConventionConverter_GetStubs, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_GetStubs")]
public static void CallingConventionConverter_GetStubs(
out global::System.IntPtr returnVoidStub,
out global::System.IntPtr returnIntegerStub,
out global::System.IntPtr commonStub,
out global::System.IntPtr returnFloatingPointReturn4Thunk,
out global::System.IntPtr returnFloatingPointReturn8Thunk)
{
// Setup
global::System.IntPtr unsafe_returnVoidStub;
global::System.IntPtr unsafe_returnIntegerStub;
global::System.IntPtr unsafe_commonStub;
global::System.IntPtr unsafe_returnFloatingPointReturn4Thunk;
global::System.IntPtr unsafe_returnFloatingPointReturn8Thunk;
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_GetStubs(
&(unsafe_returnVoidStub),
&(unsafe_returnIntegerStub),
&(unsafe_commonStub),
&(unsafe_returnFloatingPointReturn4Thunk),
&(unsafe_returnFloatingPointReturn8Thunk)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
returnFloatingPointReturn8Thunk = unsafe_returnFloatingPointReturn8Thunk;
returnFloatingPointReturn4Thunk = unsafe_returnFloatingPointReturn4Thunk;
commonStub = unsafe_commonStub;
returnIntegerStub = unsafe_returnIntegerStub;
returnVoidStub = unsafe_returnVoidStub;
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-errorhandling-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll
{
// Signature, GetLastError, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.Extensions, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetLastError")]
public static int GetLastError()
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes.GetLastError();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll
{
// Signature, RoInitialize, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "RoInitialize")]
public static int RoInitialize(uint initType)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_l1_1_0_dll_PInvokes.RoInitialize(initType);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-handle-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_handle_l1_1_0_dll
{
// Signature, CloseHandle, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CloseHandle")]
public static bool CloseHandle(global::System.IntPtr handle)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_handle_l1_1_0_dll_PInvokes.CloseHandle(handle);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
// Return
return unsafe___value != 0;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-localization-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll
{
// Signature, IsValidLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "IsValidLocaleName")]
public static int IsValidLocaleName(char* lpLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.IsValidLocaleName(((ushort*)lpLocaleName));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ResolveLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "ResolveLocaleName")]
public static int ResolveLocaleName(
char* lpNameToResolve,
char* lpLocaleName,
int cchLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.ResolveLocaleName(
((ushort*)lpNameToResolve),
((ushort*)lpLocaleName),
cchLocaleName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, GetCPInfoExW, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages___ptr__Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Text.Encoding.CodePages, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetCPInfoExW")]
public static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.GetCPInfoExW(
CodePage,
dwFlags,
((global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages*)lpCPInfoEx)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-com-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll
{
// Signature, CoCreateInstance, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.StackTraceGenerator.StackTraceGenerator", "CoCreateInstance")]
public static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
out global::System.IntPtr ppv)
{
// Setup
global::System.IntPtr unsafe_ppv;
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_com_l1_1_0_dll_PInvokes.CoCreateInstance(
((byte*)rclsid),
pUnkOuter,
dwClsContext,
((byte*)riid),
&(unsafe_ppv)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
ppv = unsafe_ppv;
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'clrcompression.dll'
/// </summary>
public unsafe static partial class clrcompression_dll
{
// Signature, deflateInit2_, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflateInit2_")]
public static int deflateInit2_(
byte* stream,
int level,
int method,
int windowBits,
int memLevel,
int strategy,
byte* version,
int stream_size)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflateInit2_(
((byte*)stream),
level,
method,
windowBits,
memLevel,
strategy,
((byte*)version),
stream_size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, deflateEnd, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflateEnd")]
public static int deflateEnd(byte* strm)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflateEnd(((byte*)strm));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, inflateEnd, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "inflateEnd")]
public static int inflateEnd(byte* stream)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.inflateEnd(((byte*)stream));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, deflate, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflate")]
public static int deflate(
byte* stream,
int flush)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflate(
((byte*)stream),
flush
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'OleAut32'
/// </summary>
public unsafe static partial class OleAut32
{
// Signature, SysFreeString, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.LightweightInterop.MarshalExtensions", "SysFreeString")]
public static void SysFreeString(global::System.IntPtr bstr)
{
// Marshalling
// Call to native method
global::McgInterop.OleAut32_PInvokes.SysFreeString(bstr);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-robuffer-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll
{
// Signature, RoGetBufferMarshaler, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.ComInterfaceMarshaller] System_Runtime_InteropServices_IMarshal__System_Runtime_WindowsRuntime__System_Runtime_InteropServices__IMarshal__System_Runtime_WindowsRuntime *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop+mincore_PInvokes", "RoGetBufferMarshaler")]
public static int RoGetBufferMarshaler(out global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime bufferMarshalerPtr)
{
// Setup
global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl** unsafe_bufferMarshalerPtr = default(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl**);
int unsafe___value;
try
{
// Marshalling
unsafe_bufferMarshalerPtr = null;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes.RoGetBufferMarshaler(&(unsafe_bufferMarshalerPtr));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
bufferMarshalerPtr = (global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime)global::System.Runtime.InteropServices.McgModuleManager.ComInterfaceToObject(
((global::System.IntPtr)unsafe_bufferMarshalerPtr),
global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("System.Runtime.InteropServices.IMarshal,System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, Public" +
"KeyToken=b77a5c561934e089")
);
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(new global::System.IntPtr(((void*)unsafe_bufferMarshalerPtr)));
}
}
}
public unsafe static partial class _MRT__PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void RhWaitForPendingFinalizers(int allowReentrantWait);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void memmove(
byte* dmem,
byte* smem,
uint size);
}
public unsafe static partial class __PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_GetStubs(
global::System.IntPtr* returnVoidStub,
global::System.IntPtr* returnIntegerStub,
global::System.IntPtr* commonStub,
global::System.IntPtr* returnFloatingPointReturn4Thunk,
global::System.IntPtr* returnFloatingPointReturn8Thunk);
}
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-errorhandling-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetLastError();
}
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RoInitialize(uint initType);
}
public unsafe static partial class api_ms_win_core_handle_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-handle-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CloseHandle(global::System.IntPtr handle);
}
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int IsValidLocaleName(ushort* lpLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ResolveLocaleName(
ushort* lpNameToResolve,
ushort* lpLocaleName,
int cchLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx);
}
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-com-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
global::System.IntPtr* ppv);
}
public unsafe static partial class clrcompression_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflateInit2_(
byte* stream,
int level,
int method,
int windowBits,
int memLevel,
int strategy,
byte* version,
int stream_size);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflateEnd(byte* strm);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int inflateEnd(byte* stream);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflate(
byte* stream,
int flush);
}
public unsafe static partial class OleAut32_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("oleaut32.dll", EntryPoint="#6", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void SysFreeString(global::System.IntPtr bstr);
}
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-robuffer-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.StdCall)]
public extern static int RoGetBufferMarshaler(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl*** bufferMarshalerPtr);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace RFIDLIB
{
#if REMOVED
class rfidlib_aip_iso18000p6C
{
#if UNICODE
/**********************************************Use Unicode Character Set********************************************/
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern UInt32 ISO18000p6C_GetLibVersion(StringBuilder buf, UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateInvenParam(UIntPtr hInvenParamSpecList,
Byte AntennaID /* By default set to 0,apply to all antenna */,
Byte Sel,
Byte Session,
Byte Target,
Byte Q) ;
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenSelectParam(UIntPtr hIso18000p6CInvenParam ,
Byte target ,
Byte action ,
Byte memBank ,
UInt32 dwPointer,
Byte[] maskBits,
Byte maskBitLen,
Byte truncate) ;
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenMetaDataFlags(UIntPtr hIso18000p6CInvenParam ,UInt32 flags) ;
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenReadParam(UIntPtr hIso18000p6CInvenParam, Byte MemBank, UInt32 WordPtr, Byte WordCount);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_ParseTagReport(UIntPtr hTagReport,
ref UInt32 aip_id,
ref UInt32 tag_id,
ref UInt32 ant_id,
ref UInt32 metaFlags,
Byte[] tagdata,
ref UInt32 tdLen /* IN:max size of the tagdata buffer ,OUT:bytes written into tagdata buffer */) ;
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateTAWrite(UIntPtr hIso18000p6CInvenParam,
Byte memBank,
UInt32 wordPtr ,
UInt32 wordCnt ,
Byte[] pdatas,
UInt32 nSize) ;
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_CheckTAWriteResult(UIntPtr hTagReport);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenAccessPassword(UIntPtr hIso18000p6CInvenParam, UInt32 pwd);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateTALock(UIntPtr hIso18000p6CInvenParam,
UInt16 mask,
UInt16 action);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_CheckTALockResult(UIntPtr hTagReport);
#else
/**************************************************Use Multi-Byte Character Set**********************************************/
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern UInt32 ISO18000p6C_GetLibVersion(StringBuilder buf, UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateInvenParam(UIntPtr hInvenParamSpecList,
Byte AntennaID /* By default set to 0,apply to all antenna */,
Byte Sel,
Byte Session,
Byte Target,
Byte Q);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenSelectParam(UIntPtr hIso18000p6CInvenParam,
Byte target,
Byte action,
Byte memBank,
UInt32 dwPointer,
Byte[] maskBits,
Byte maskBitLen,
Byte truncate);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenMetaDataFlags(UIntPtr hIso18000p6CInvenParam, UInt32 flags);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenReadParam(UIntPtr hIso18000p6CInvenParam, Byte MemBank, UInt32 WordPtr, Byte WordCount);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_ParseTagReport(UIntPtr hTagReport,
ref UInt32 aip_id,
ref UInt32 tag_id,
ref UInt32 ant_id,
ref UInt32 metaFlags,
Byte[] tagdata,
ref UInt32 tdLen /* IN:max size of the tagdata buffer ,OUT:bytes written into tagdata buffer */);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateTAWrite(UIntPtr hIso18000p6CInvenParam,
Byte memBank,
UInt32 wordPtr,
UInt32 wordCnt,
Byte[] pdatas,
UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_CheckTAWriteResult(UIntPtr hTagReport);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenAccessPassword(UIntPtr hIso18000p6CInvenParam, UInt32 pwd);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateTALock(UIntPtr hIso18000p6CInvenParam,
UInt16 mask,
UInt16 action);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_CheckTALockResult(UIntPtr hTagReport);
#endif
}
#endif
class rfidlib_aip_iso18000p6C
{
#if UNICODE
/**********************************************Use Unicode Character Set********************************************/
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern UInt32 ISO18000p6C_GetLibVersion(StringBuilder buf, UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateInvenParam(UIntPtr hInvenParamSpecList,
Byte AntennaID /* By default set to 0,apply to all antenna */,
Byte Sel,
Byte Session,
Byte Target,
Byte Q);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenSelectParam(UIntPtr hIso18000p6CInvenParam,
Byte target,
Byte action,
Byte memBank,
UInt32 dwPointer,
Byte[] maskBits,
Byte maskBitLen,
Byte truncate);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenMetaDataFlags(UIntPtr hIso18000p6CInvenParam, UInt32 flags);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenReadParam(UIntPtr hIso18000p6CInvenParam, Byte MemBank, UInt32 WordPtr, Byte WordCount);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_ParseTagReport(UIntPtr hTagReport,
ref UInt32 aip_id,
ref UInt32 tag_id,
ref UInt32 ant_id,
ref UInt32 metaFlags,
Byte[] tagdata,
ref UInt32 tdLen /* IN:max size of the tagdata buffer ,OUT:bytes written into tagdata buffer */);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateTAWrite(UIntPtr hIso18000p6CInvenParam,
Byte memBank,
UInt32 wordPtr,
UInt32 wordCnt,
Byte[] pdatas,
UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_CheckTAWriteResult(UIntPtr hTagReport);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenAccessPassword(UIntPtr hIso18000p6CInvenParam, UInt32 pwd);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateTALock(UIntPtr hIso18000p6CInvenParam,
UInt16 mask,
UInt16 action);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_CheckTALockResult(UIntPtr hTagReport);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateTAKill(UIntPtr hIso18000p6CInvenParam, UInt32 password, Byte rfu);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_CheckTAKillResult(UIntPtr hTagReport);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_ParseTagReportV2(UIntPtr hTagReport,
ref UInt32 aip_id,
ref UInt32 tag_id,
ref UInt32 ant_id,
Byte[] epc,
ref UInt32 dLen);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_Connect(UIntPtr hr,
UInt32 tag_id,
Byte[] epc,
Byte epcLen,
UInt32 accessPwb,
ref UIntPtr ht);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_Read(UIntPtr hr,
UIntPtr ht,
Byte memBank,
UInt32 wordStart,
UInt32 wordCnt,
Byte[] wordData,
ref UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_Write(UIntPtr hr,
UIntPtr ht,
Byte memBank,
UInt32 wordStart,
UInt32 workCnt,
Byte[] wordData,
UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_Lock(UIntPtr hr,
UIntPtr ht,
UInt16 mask,
UInt16 action);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_Kill(UIntPtr hr,
UIntPtr ht,
UInt32 killPwb,
Byte rfu);
#else
/**************************************************Use Multi-Byte Character Set**********************************************/
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern UInt32 ISO18000p6C_GetLibVersion(StringBuilder buf, UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateInvenParam(UIntPtr hInvenParamSpecList,
Byte AntennaID /* By default set to 0,apply to all antenna */,
Byte Sel,
Byte Session,
Byte Target,
Byte Q);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenSelectParam(UIntPtr hIso18000p6CInvenParam,
Byte target,
Byte action,
Byte memBank,
UInt32 dwPointer,
Byte[] maskBits,
Byte maskBitLen,
Byte truncate);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenMetaDataFlags(UIntPtr hIso18000p6CInvenParam, UInt32 flags);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenReadParam(UIntPtr hIso18000p6CInvenParam, Byte MemBank, UInt32 WordPtr, Byte WordCount);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_ParseTagReport(UIntPtr hTagReport,
ref UInt32 aip_id,
ref UInt32 tag_id,
ref UInt32 ant_id,
ref UInt32 metaFlags,
Byte[] tagdata,
ref UInt32 tdLen /* IN:max size of the tagdata buffer ,OUT:bytes written into tagdata buffer */);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateTAWrite(UIntPtr hIso18000p6CInvenParam,
Byte memBank,
UInt32 wordPtr,
UInt32 wordCnt,
Byte[] pdatas,
UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_CheckTAWriteResult(UIntPtr hTagReport);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_SetInvenAccessPassword(UIntPtr hIso18000p6CInvenParam, UInt32 pwd);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateTALock(UIntPtr hIso18000p6CInvenParam,
UInt16 mask,
UInt16 action);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_CheckTALockResult(UIntPtr hTagReport);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern UIntPtr ISO18000p6C_CreateTAKill(UIntPtr hIso18000p6CInvenParam, UInt32 password, Byte rfu);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_CheckTAKillResult(UIntPtr hTagReport);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_ParseTagReportV2(UIntPtr hTagReport,
ref UInt32 aip_id,
ref UInt32 tag_id,
ref UInt32 ant_id,
Byte[] epc,
ref UInt32 dLen);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_Connect(UIntPtr hr,
UInt32 tag_id,
Byte[] epc,
Byte epcLen,
UInt32 accessPwb,
ref UIntPtr ht);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_Read(UIntPtr hr,
UIntPtr ht,
Byte memBank,
UInt32 wordStart,
UInt32 wordCnt,
Byte[] wordData,
ref UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_Write(UIntPtr hr,
UIntPtr ht,
Byte memBank,
UInt32 wordStart,
UInt32 workCnt,
Byte[] wordData,
UInt32 nSize);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_Lock(UIntPtr hr,
UIntPtr ht,
UInt16 mask,
UInt16 action);
[DllImport("rfidlib_aip_iso18000p6C.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int ISO18000p6C_Kill(UIntPtr hr,
UIntPtr ht,
UInt32 killPwb,
Byte rfu);
#endif
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
/*
* AvaTax API Client Library
*
* (c) 2004-2019 Avalara, Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Genevieve Conty
* @author Greg Hester
* Swagger name: AvaTaxClient
*/
namespace Avalara.AvaTax.RestClient
{
/// <summary>
/// A MultiDocument transaction represents a sale or purchase that occurred between more than two companies.
///
/// A traditional transaction requires exactly two parties: a seller and a buyer. MultiDocument transactions can
/// involve a marketplace of vendors, each of which contributes some portion of the final transaction. Within
/// a MultiDocument transaction, each individual buyer and seller pair are matched up and converted to a separate
/// document. This separation of documents allows each seller to file their taxes separately.
/// </summary>
public class CreateMultiDocumentModel
{
/// <summary>
/// The transaction code of the MultiDocument transaction.
///
/// All individual transactions within this MultiDocument object will have this code as a prefix.
///
/// If you leave the `code` field blank, a GUID will be assigned.
/// </summary>
public String code { get; set; }
/// <summary>
/// Lines that will appear on the invoice.
///
/// For a MultiDocument transaction, each line may represent a different company or reporting location code. AvaTax
/// will separate this MultiDocument transaction object into many different transactions, one for each pair of legal
/// entities, so that each legal entity can file their transactional taxes correctly.
/// </summary>
public List<MultiDocumentLineItemModel> lines { get; set; }
/// <summary>
/// Set this value to true to allow this API call to adjust the MultiDocument model if one already exists.
///
/// If you omit this field, or if the value is `null`, you will receive an error if you try to create two MultiDocument
/// objects with the same `code`.
/// </summary>
public Boolean? allowAdjust { get; set; }
/// <summary>
/// Specifies the type of document to create. A document type ending with `Invoice` is a permanent transaction
/// that will be recorded in AvaTax. A document type ending with `Order` is a temporary estimate that will not
/// be preserved.
///
/// If you omit this value, the API will assume you want to create a `SalesOrder`.
/// </summary>
public DocumentType? type { get; set; }
/// <summary>
/// Company Code - Specify the code of the company creating this transaction here. If you leave this value null,
/// your account's default company will be used instead.
/// </summary>
public String companyCode { get; set; }
/// <summary>
/// Transaction Date - The date on the invoice, purchase order, etc.
///
/// By default, this date will be used to calculate the tax rates for the transaction. If you wish to use a
/// different date to calculate tax rates, please specify a `taxOverride` of type `taxDate`.
/// </summary>
public DateTime date { get; set; }
/// <summary>
/// Salesperson Code - The client application salesperson reference code.
/// </summary>
public String salespersonCode { get; set; }
/// <summary>
/// Customer Code - The client application customer reference code.
/// Note: This field is case sensitive. To have exemption certificates apply, this value should
/// be the same as the one passed to create a customer.
/// </summary>
public String customerCode { get; set; }
/// <summary>
/// DEPRECATED - Date: 10/16/2017, Version: 17.11, Message: Please use entityUseCode instead.
/// Customer Usage Type - The client application customer or usage type.
/// </summary>
public String customerUsageType { get; set; }
/// <summary>
/// Entity Use Code - The client application customer or usage type. For a list of
/// available usage types, use [ListEntityUseCodes](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListEntityUseCodes/) API.
/// </summary>
public String entityUseCode { get; set; }
/// <summary>
/// Discount - The discount amount to apply to the document. This value will be applied only to lines
/// that have the `discounted` flag set to true. If no lines have `discounted` set to true, this discount
/// cannot be applied.
/// </summary>
public Decimal? discount { get; set; }
/// <summary>
/// Purchase Order Number for this document.
///
/// This is required for single use exemption certificates to match the order and invoice with the certificate.
/// </summary>
public String purchaseOrderNo { get; set; }
/// <summary>
/// Exemption Number for this document.
///
/// If you specify an exemption number for this document, this document will be considered exempt, and you
/// may be asked to provide proof of this exemption certificate in the event that you are asked by an auditor
/// to verify your exemptions.
/// Note: This is same as 'exemptNo' in TransactionModel.
/// </summary>
public String exemptionNo { get; set; }
/// <summary>
///
/// </summary>
public AddressesModel addresses { get; set; }
/// <summary>
/// Special parameters for this transaction.
///
/// To get a full list of available parameters, please use the [ListParameters](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListParameters/) endpoint.
/// </summary>
public List<TransactionParameterModel> parameters { get; set; }
/// <summary>
/// Custom user fields/flex fields for this transaction.
/// </summary>
public List<TransactionUserDefinedFieldModel> userDefinedFields { get; set; }
/// <summary>
/// Customer-provided Reference Code with information about this transaction.
///
/// This field could be used to reference the original document for a return invoice, or for any other
/// reference purpose.
/// </summary>
public String referenceCode { get; set; }
/// <summary>
/// Sets the sale location code (Outlet ID) for reporting this document to the tax authority.
///
/// This value is used by Avalara Managed Returns to group documents together by reporting locations
/// for tax authorities that require location-based reporting.
/// </summary>
public String reportingLocationCode { get; set; }
/// <summary>
/// Causes the document to be committed if true. This option is only applicable for invoice document
/// types, not orders.
/// </summary>
public Boolean? commit { get; set; }
/// <summary>
/// BatchCode for batch operations.
/// </summary>
public String batchCode { get; set; }
/// <summary>
///
/// </summary>
public TaxOverrideModel taxOverride { get; set; }
/// <summary>
/// The three-character ISO 4217 currency code for this transaction.
/// </summary>
public String currencyCode { get; set; }
/// <summary>
/// Specifies whether the tax calculation is handled Local, Remote, or Automatic (default). This only
/// applies when using an AvaLocal server.
/// </summary>
public ServiceMode? serviceMode { get; set; }
/// <summary>
/// Currency exchange rate from this transaction to the company base currency.
///
/// This only needs to be set if the transaction currency is different than the company base currency.
/// It defaults to 1.0.
/// </summary>
public Decimal? exchangeRate { get; set; }
/// <summary>
/// Effective date of the exchange rate.
/// </summary>
public DateTime? exchangeRateEffectiveDate { get; set; }
/// <summary>
/// Optional three-character ISO 4217 reporting exchange rate currency code for this transaction. The default value is USD.
/// </summary>
public String exchangeRateCurrencyCode { get; set; }
/// <summary>
/// Sets the Point of Sale Lane Code sent by the User for this document.
/// </summary>
public String posLaneCode { get; set; }
/// <summary>
/// VAT business identification number for the customer for this transaction. This number will be used for all lines
/// in the transaction, except for those lines where you have defined a different business identification number.
///
/// If you specify a VAT business identification number for the customer in this transaction and you have also set up
/// a business identification number for your company during company setup, this transaction will be treated as a
/// business-to-business transaction for VAT purposes and it will be calculated according to VAT tax rules.
/// </summary>
public String businessIdentificationNo { get; set; }
/// <summary>
/// Specifies if the transaction should have value-added and cross-border taxes calculated with the seller as the importer of record.
///
/// Some taxes only apply if the seller is the importer of record for a product. In cases where companies are working together to
/// ship products, there may be mutual agreement as to which company is the entity designated as importer of record. The importer
/// of record will then be the company designated to pay taxes marked as being obligated to the importer of record.
///
/// Set this value to `true` to consider your company as the importer of record and collect these taxes.
///
/// This value may also be set at the Nexus level. See `NexusModel` for more information.
/// </summary>
public Boolean? isSellerImporterOfRecord { get; set; }
/// <summary>
/// User-supplied description for this transaction.
/// </summary>
public String description { get; set; }
/// <summary>
/// User-supplied email address relevant for this transaction.
/// </summary>
public String email { get; set; }
/// <summary>
/// If the user wishes to request additional debug information from this transaction, specify a level higher than `normal`.
/// </summary>
public TaxDebugLevel? debugLevel { get; set; }
/// <summary>
/// The name of the supplier / exporter / seller.
/// For sales doctype enter the name of your own company for which you are reporting.
/// For purchases doctype enter the name of the supplier you have purchased from.
/// </summary>
public String customerSupplierName { get; set; }
/// <summary>
/// The Id of the datasource from which this transaction originated.
/// This value will be overridden by the system to take the datasource Id from the call header.
/// </summary>
public Int32? dataSourceId { get; set; }
/// <summary>
/// The Delivery Terms is a field used in conjunction with Importer of Record to influence whether AvaTax includes Import Duty and Tax values in the transaction totals or not.
/// Delivered at Place (DAP) and Delivered Duty Paid (DDP) are two delivery terms that indicate that Import Duty and Tax should be included in the transaction total.
/// This field is also used for reports.
/// This field is used for future feature support. This field is not currently in use.
/// </summary>
public DeliveryTerms? deliveryTerms { get; set; }
/// <summary>
/// Convert this object to a JSON string of itself
/// </summary>
/// <returns>A JSON string of this object</returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Ants.Web.Areas.HelpPage.ModelDescriptions;
using Ants.Web.Areas.HelpPage.Models;
using Ants.Web.Areas.HelpPage.SampleGeneration;
#pragma warning disable 1591
namespace Ants.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string apiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
var modelId = apiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out object model))
{
var apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
var apiDescription = apiDescriptions.FirstOrDefault(api => string.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
var apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
var modelGenerator = config.GetModelDescriptionGenerator();
var sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
var apiDescription = apiModel.ApiDescription;
foreach (var apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
var parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (var uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
var uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
var defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
var modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
return parameterType != null && TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
var parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
var apiDescription = apiModel.ApiDescription;
foreach (var apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
var parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
var parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
var response = apiModel.ApiDescription.ResponseDescription;
var responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(string.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
var sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
var modelGenerator = new ModelDescriptionGenerator(config);
var apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (var api in apis)
{
if (TryGetResourceParameter(api, config, out ApiParameterDescription parameterDescription, out Type parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
var invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
#if !WINRT || UNITY_EDITOR
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace LiteNetLib
{
internal sealed class NetSocket
{
private Socket _udpSocketv4;
private Socket _udpSocketv6;
private NetEndPoint _localEndPoint;
private Thread _threadv4;
private Thread _threadv6;
private bool _running;
private readonly NetManager.OnMessageReceived _onMessageReceived;
private static readonly IPAddress MulticastAddressV6 = IPAddress.Parse (NetConstants.MulticastGroupIPv6);
private static readonly bool IPv6Support;
private const int SocketReceivePollTime = 100000;
private const int SocketSendPollTime = 5000;
public NetEndPoint LocalEndPoint
{
get { return _localEndPoint; }
}
static NetSocket()
{
try
{
//Unity3d .NET 2.0 throws exception.
IPv6Support = Socket.OSSupportsIPv6;
}
catch
{
IPv6Support = false;
}
}
public NetSocket(NetManager.OnMessageReceived onMessageReceived)
{
_onMessageReceived = onMessageReceived;
}
private void ReceiveLogic(object state)
{
Socket socket = (Socket)state;
EndPoint bufferEndPoint = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
NetEndPoint bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint);
byte[] receiveBuffer = new byte[NetConstants.PacketSizeLimit];
while (_running)
{
//wait for data
if (!socket.Poll(SocketReceivePollTime, SelectMode.SelectRead))
{
continue;
}
int result;
//Reading data
try
{
result = socket.ReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref bufferEndPoint);
if (!bufferNetEndPoint.EndPoint.Equals(bufferEndPoint))
{
bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint);
}
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionReset ||
ex.SocketErrorCode == SocketError.MessageSize)
{
//10040 - message too long
//10054 - remote close (not error)
//Just UDP
NetUtils.DebugWrite(ConsoleColor.DarkRed, "[R] Ingored error: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString() );
continue;
}
NetUtils.DebugWriteError("[R]Error code: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString());
_onMessageReceived(null, 0, (int)ex.SocketErrorCode, bufferNetEndPoint);
continue;
}
//All ok!
NetUtils.DebugWrite(ConsoleColor.Blue, "[R]Recieved data from {0}, result: {1}", bufferNetEndPoint.ToString(), result);
_onMessageReceived(receiveBuffer, result, 0, bufferNetEndPoint);
}
}
public bool Bind(int port, bool reuseAddress)
{
_udpSocketv4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_udpSocketv4.Blocking = false;
_udpSocketv4.ReceiveBufferSize = NetConstants.SocketBufferSize;
_udpSocketv4.SendBufferSize = NetConstants.SocketBufferSize;
_udpSocketv4.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, NetConstants.SocketTTL);
if(reuseAddress)
_udpSocketv4.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
#if !NETCORE
_udpSocketv4.DontFragment = true;
#endif
try
{
_udpSocketv4.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
}
catch (SocketException e)
{
NetUtils.DebugWriteError("Broadcast error: {0}", e.ToString());
}
if (!BindSocket(_udpSocketv4, new IPEndPoint(IPAddress.Any, port)))
{
return false;
}
_localEndPoint = new NetEndPoint((IPEndPoint)_udpSocketv4.LocalEndPoint);
_running = true;
_threadv4 = new Thread(ReceiveLogic);
_threadv4.Name = "SocketThreadv4(" + port + ")";
_threadv4.IsBackground = true;
_threadv4.Start(_udpSocketv4);
//Check IPv6 support
if (!IPv6Support)
return true;
//Use one port for two sockets
port = _localEndPoint.Port;
_udpSocketv6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
_udpSocketv6.Blocking = false;
_udpSocketv6.ReceiveBufferSize = NetConstants.SocketBufferSize;
_udpSocketv6.SendBufferSize = NetConstants.SocketBufferSize;
if (reuseAddress)
_udpSocketv6.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
if (BindSocket(_udpSocketv6, new IPEndPoint(IPAddress.IPv6Any, port)))
{
_localEndPoint = new NetEndPoint((IPEndPoint)_udpSocketv6.LocalEndPoint);
try
{
_udpSocketv6.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.AddMembership,
new IPv6MulticastOption(MulticastAddressV6));
}
catch(Exception)
{
// Unity3d throws exception - ignored
}
_threadv6 = new Thread(ReceiveLogic);
_threadv6.Name = "SocketThreadv6(" + port + ")";
_threadv6.IsBackground = true;
_threadv6.Start(_udpSocketv6);
}
return true;
}
private bool BindSocket(Socket socket, IPEndPoint ep)
{
try
{
socket.Bind(ep);
NetUtils.DebugWrite(ConsoleColor.Blue, "[B]Succesfully binded to port: {0}", ((IPEndPoint)socket.LocalEndPoint).Port);
}
catch (SocketException ex)
{
NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString());
//TODO: very temporary hack for iOS (Unity3D)
if (ex.SocketErrorCode == SocketError.AddressFamilyNotSupported)
{
return true;
}
return false;
}
return true;
}
public bool SendBroadcast(byte[] data, int offset, int size, int port)
{
try
{
int result = _udpSocketv4.SendTo(data, offset, size, SocketFlags.None, new IPEndPoint(IPAddress.Broadcast, port));
if (result <= 0)
return false;
if (IPv6Support)
{
result = _udpSocketv6.SendTo(data, offset, size, SocketFlags.None, new IPEndPoint(MulticastAddressV6, port));
if (result <= 0)
return false;
}
}
catch (Exception ex)
{
NetUtils.DebugWriteError("[S][MCAST]" + ex);
return false;
}
return true;
}
public int SendTo(byte[] data, int offset, int size, NetEndPoint remoteEndPoint, ref int errorCode)
{
try
{
int result = 0;
if (remoteEndPoint.EndPoint.AddressFamily == AddressFamily.InterNetwork)
{
if (!_udpSocketv4.Poll(SocketSendPollTime, SelectMode.SelectWrite))
return -1;
result = _udpSocketv4.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint.EndPoint);
}
else if(IPv6Support)
{
if (!_udpSocketv6.Poll(SocketSendPollTime, SelectMode.SelectWrite))
return -1;
result = _udpSocketv6.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint.EndPoint);
}
NetUtils.DebugWrite(ConsoleColor.Blue, "[S]Send packet to {0}, result: {1}", remoteEndPoint.EndPoint, result);
return result;
}
catch (SocketException ex)
{
if (ex.SocketErrorCode != SocketError.MessageSize)
{
NetUtils.DebugWriteError("[S]" + ex);
}
errorCode = (int)ex.SocketErrorCode;
return -1;
}
catch (Exception ex)
{
NetUtils.DebugWriteError("[S]" + ex);
return -1;
}
}
private void CloseSocket(Socket s)
{
#if NETCORE
s.Dispose();
#else
s.Close();
#endif
}
public void Close()
{
_running = false;
//Close IPv4
if (Thread.CurrentThread != _threadv4)
{
_threadv4.Join();
}
_threadv4 = null;
if (_udpSocketv4 != null)
{
CloseSocket(_udpSocketv4);
_udpSocketv4 = null;
}
//No ipv6
if (_udpSocketv6 == null)
return;
//Close IPv6
if (Thread.CurrentThread != _threadv6)
{
_threadv6.Join();
}
_threadv6 = null;
if (_udpSocketv6 != null)
{
CloseSocket(_udpSocketv6);
_udpSocketv6 = null;
}
}
}
}
#else
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
namespace LiteNetLib
{
internal sealed class NetSocket
{
private DatagramSocket _datagramSocket;
private readonly Dictionary<NetEndPoint, IOutputStream> _peers = new Dictionary<NetEndPoint, IOutputStream>();
private readonly NetManager.OnMessageReceived _onMessageReceived;
private readonly byte[] _byteBuffer = new byte[NetConstants.PacketSizeLimit];
private readonly IBuffer _buffer;
private NetEndPoint _bufferEndPoint;
private NetEndPoint _localEndPoint;
private static readonly HostName BroadcastAddress = new HostName("255.255.255.255");
private static readonly HostName MulticastAddressV6 = new HostName(NetConstants.MulticastGroupIPv6);
public NetEndPoint LocalEndPoint
{
get { return _localEndPoint; }
}
public NetSocket(NetManager.OnMessageReceived onMessageReceived)
{
_onMessageReceived = onMessageReceived;
_buffer = _byteBuffer.AsBuffer();
}
private void OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
var result = args.GetDataStream().ReadAsync(_buffer, _buffer.Capacity, InputStreamOptions.None).AsTask().Result;
int length = (int)result.Length;
if (length <= 0)
return;
if (_bufferEndPoint == null ||
!_bufferEndPoint.HostName.IsEqual(args.RemoteAddress) ||
!_bufferEndPoint.PortStr.Equals(args.RemotePort))
{
_bufferEndPoint = new NetEndPoint(args.RemoteAddress, args.RemotePort);
}
_onMessageReceived(_byteBuffer, length, 0, _bufferEndPoint);
}
public bool Bind(int port, bool reuseAddress)
{
_datagramSocket = new DatagramSocket();
_datagramSocket.Control.InboundBufferSizeInBytes = NetConstants.SocketBufferSize;
_datagramSocket.Control.DontFragment = true;
_datagramSocket.Control.OutboundUnicastHopLimit = NetConstants.SocketTTL;
_datagramSocket.MessageReceived += OnMessageReceived;
try
{
_datagramSocket.BindServiceNameAsync(port.ToString()).AsTask().Wait();
_datagramSocket.JoinMulticastGroup(MulticastAddressV6);
_localEndPoint = new NetEndPoint(_datagramSocket.Information.LocalAddress, _datagramSocket.Information.LocalPort);
}
catch (Exception ex)
{
NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString());
return false;
}
return true;
}
public bool SendBroadcast(byte[] data, int offset, int size, int port)
{
var portString = port.ToString();
try
{
var outputStream =
_datagramSocket.GetOutputStreamAsync(BroadcastAddress, portString)
.AsTask()
.Result;
var writer = outputStream.AsStreamForWrite();
writer.Write(data, offset, size);
writer.Flush();
outputStream =
_datagramSocket.GetOutputStreamAsync(MulticastAddressV6, portString)
.AsTask()
.Result;
writer = outputStream.AsStreamForWrite();
writer.Write(data, offset, size);
writer.Flush();
}
catch (Exception ex)
{
NetUtils.DebugWriteError("[S][MCAST]" + ex);
return false;
}
return true;
}
public int SendTo(byte[] data, int offset, int length, NetEndPoint remoteEndPoint, ref int errorCode)
{
Task<uint> task = null;
try
{
IOutputStream writer;
if (!_peers.TryGetValue(remoteEndPoint, out writer))
{
writer =
_datagramSocket.GetOutputStreamAsync(remoteEndPoint.HostName, remoteEndPoint.PortStr)
.AsTask()
.Result;
_peers.Add(remoteEndPoint, writer);
}
task = writer.WriteAsync(data.AsBuffer(offset, length)).AsTask();
return (int)task.Result;
}
catch (Exception ex)
{
if (task?.Exception?.InnerExceptions != null)
{
ex = task.Exception.InnerException;
}
var errorStatus = SocketError.GetStatus(ex.HResult);
switch (errorStatus)
{
case SocketErrorStatus.MessageTooLong:
errorCode = 10040;
break;
default:
errorCode = (int)errorStatus;
NetUtils.DebugWriteError("[S " + errorStatus + "(" + errorCode + ")]" + ex);
break;
}
return -1;
}
}
internal void RemovePeer(NetEndPoint ep)
{
_peers.Remove(ep);
}
public void Close()
{
_datagramSocket.Dispose();
_datagramSocket = null;
ClearPeers();
}
internal void ClearPeers()
{
_peers.Clear();
}
}
}
#endif
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
namespace Org.BouncyCastle.Security
{
public sealed class PublicKeyFactory
{
private PublicKeyFactory()
{
}
public static IAsymmetricKeyParameter CreateKey(
byte[] keyInfoData)
{
return CreateKey(
SubjectPublicKeyInfo.GetInstance(
Asn1Object.FromByteArray(keyInfoData)));
}
public static IAsymmetricKeyParameter CreateKey(
Stream inStr)
{
return CreateKey(
SubjectPublicKeyInfo.GetInstance(
Asn1Object.FromStream(inStr)));
}
public static IAsymmetricKeyParameter CreateKey(
SubjectPublicKeyInfo keyInfo)
{
AlgorithmIdentifier algID = keyInfo.AlgorithmID;
DerObjectIdentifier algOid = algID.ObjectID;
// TODO See RSAUtil.isRsaOid in Java build
if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption)
|| algOid.Equals(X509ObjectIdentifiers.IdEARsa)
|| algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss)
|| algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
{
RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
keyInfo.GetPublicKey());
return new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent);
}
else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
{
Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());
DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey());
IBigInteger y = dhPublicKey.Y.Value;
if (IsPkcsDHParam(seq))
return ReadPkcsDHParam(algOid, y, seq);
DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq);
IBigInteger p = dhParams.P.Value;
IBigInteger g = dhParams.G.Value;
IBigInteger q = dhParams.Q.Value;
IBigInteger j = null;
if (dhParams.J != null)
{
j = dhParams.J.Value;
}
DHValidationParameters validation = null;
DHValidationParms dhValidationParms = dhParams.ValidationParms;
if (dhValidationParms != null)
{
byte[] seed = dhValidationParms.Seed.GetBytes();
IBigInteger pgenCounter = dhValidationParms.PgenCounter.Value;
// TODO Check pgenCounter size?
validation = new DHValidationParameters(seed, pgenCounter.IntValue);
}
return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
}
else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
{
Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());
DerInteger derY = (DerInteger) keyInfo.GetPublicKey();
return ReadPkcsDHParam(algOid, derY.Value, seq);
}
else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
{
ElGamalParameter para = new ElGamalParameter(
Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
DerInteger derY = (DerInteger) keyInfo.GetPublicKey();
return new ElGamalPublicKeyParameters(
derY.Value,
new ElGamalParameters(para.P, para.G));
}
else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)
|| algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
{
DerInteger derY = (DerInteger) keyInfo.GetPublicKey();
Asn1Encodable ae = algID.Parameters;
DsaParameters parameters = null;
if (ae != null)
{
DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
parameters = new DsaParameters(para.P, para.Q, para.G);
}
return new DsaPublicKeyParameters(derY.Value, parameters);
}
else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
{
X962Parameters para = new X962Parameters(
algID.Parameters.ToAsn1Object());
X9ECParameters ecP;
if (para.IsNamedCurve)
{
ecP = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
}
else
{
ecP = new X9ECParameters((Asn1Sequence)para.Parameters);
}
ECDomainParameters dParams = new ECDomainParameters(
ecP.Curve,
ecP.G,
ecP.N,
ecP.H,
ecP.GetSeed());
DerBitString bits = keyInfo.PublicKeyData;
byte[] data = bits.GetBytes();
Asn1OctetString key = new DerOctetString(data);
X9ECPoint derQ = new X9ECPoint(dParams.Curve, key);
return new ECPublicKeyParameters(derQ.Point, dParams);
}
else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
{
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
(Asn1Sequence) algID.Parameters);
Asn1OctetString key;
try
{
key = (Asn1OctetString) keyInfo.GetPublicKey();
}
catch (IOException)
{
throw new ArgumentException("invalid info structure in GOST3410 public key");
}
byte[] keyEnc = key.GetOctets();
byte[] x = new byte[32];
byte[] y = new byte[32];
for (int i = 0; i != y.Length; i++)
{
x[i] = keyEnc[32 - 1 - i];
}
for (int i = 0; i != x.Length; i++)
{
y[i] = keyEnc[64 - 1 - i];
}
ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);
if (ecP == null)
return null;
ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y), false);
return new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet);
}
else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
{
Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
(Asn1Sequence) algID.Parameters);
DerOctetString derY;
try
{
derY = (DerOctetString) keyInfo.GetPublicKey();
}
catch (IOException)
{
throw new ArgumentException("invalid info structure in GOST3410 public key");
}
byte[] keyEnc = derY.GetOctets();
byte[] keyBytes = new byte[keyEnc.Length];
for (int i = 0; i != keyEnc.Length; i++)
{
keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian
}
IBigInteger y = new BigInteger(1, keyBytes);
return new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet);
}
else
{
throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid);
}
}
private static bool IsPkcsDHParam(Asn1Sequence seq)
{
if (seq.Count == 2)
return true;
if (seq.Count > 3)
return false;
DerInteger l = DerInteger.GetInstance(seq[2]);
DerInteger p = DerInteger.GetInstance(seq[0]);
return l.Value.CompareTo(BigInteger.ValueOf(p.Value.BitLength)) <= 0;
}
private static DHPublicKeyParameters ReadPkcsDHParam(DerObjectIdentifier algOid,
IBigInteger y, Asn1Sequence seq)
{
DHParameter para = new DHParameter(seq);
IBigInteger lVal = para.L;
int l = lVal == null ? 0 : lVal.IntValue;
DHParameters dhParams = new DHParameters(para.P, para.G, null, l);
return new DHPublicKeyParameters(y, dhParams, algOid);
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reactive.Linq;
namespace Avalonia.Markup.Data
{
internal class IndexerNode : ExpressionNode
{
public IndexerNode(IList<string> arguments)
{
Arguments = arguments;
}
public override string Description => "[" + string.Join(",", Arguments) + "]";
protected override IObservable<object> StartListeningCore(WeakReference reference)
{
var target = reference.Target;
var incc = target as INotifyCollectionChanged;
var inpc = target as INotifyPropertyChanged;
var inputs = new List<IObservable<object>>();
if (incc != null)
{
inputs.Add(WeakObservable.FromEventPattern<NotifyCollectionChangedEventArgs>(
target,
nameof(incc.CollectionChanged))
.Where(x => ShouldUpdate(x.Sender, x.EventArgs))
.Select(_ => GetValue(target)));
}
if (inpc != null)
{
inputs.Add(WeakObservable.FromEventPattern<PropertyChangedEventArgs>(
target,
nameof(inpc.PropertyChanged))
.Where(x => ShouldUpdate(x.Sender, x.EventArgs))
.Select(_ => GetValue(target)));
}
return Observable.Merge(inputs).StartWith(GetValue(target));
}
public IList<string> Arguments { get; }
private object GetValue(object target)
{
var typeInfo = target.GetType().GetTypeInfo();
var list = target as IList;
var dictionary = target as IDictionary;
var indexerProperty = GetIndexer(typeInfo);
var indexerParameters = indexerProperty?.GetIndexParameters();
if (indexerProperty != null && indexerParameters.Length == Arguments.Count)
{
var convertedObjectArray = new object[indexerParameters.Length];
for (int i = 0; i < Arguments.Count; i++)
{
object temp = null;
if (!TypeUtilities.TryConvert(indexerParameters[i].ParameterType, Arguments[i], CultureInfo.InvariantCulture, out temp))
{
return AvaloniaProperty.UnsetValue;
}
convertedObjectArray[i] = temp;
}
var intArgs = convertedObjectArray.OfType<int>().ToArray();
// Try special cases where we can validate indicies
if (typeInfo.IsArray)
{
return GetValueFromArray((Array)target, intArgs);
}
else if (Arguments.Count == 1)
{
if (list != null)
{
if (intArgs.Length == Arguments.Count && intArgs[0] >= 0 && intArgs[0] < list.Count)
{
return list[intArgs[0]];
}
return AvaloniaProperty.UnsetValue;
}
else if (dictionary != null)
{
if (dictionary.Contains(convertedObjectArray[0]))
{
return dictionary[convertedObjectArray[0]];
}
return AvaloniaProperty.UnsetValue;
}
else
{
// Fallback to unchecked access
return indexerProperty.GetValue(target, convertedObjectArray);
}
}
else
{
// Fallback to unchecked access
return indexerProperty.GetValue(target, convertedObjectArray);
}
}
// Multidimensional arrays end up here because the indexer search picks up the IList indexer instead of the
// multidimensional indexer, which doesn't take the same number of arguments
else if (typeInfo.IsArray)
{
return GetValueFromArray((Array)target);
}
return AvaloniaProperty.UnsetValue;
}
private object GetValueFromArray(Array array)
{
int[] intArgs;
if (!ConvertArgumentsToInts(out intArgs))
return AvaloniaProperty.UnsetValue;
return GetValueFromArray(array, intArgs);
}
private object GetValueFromArray(Array array, int[] indicies)
{
if (ValidBounds(indicies, array))
{
return array.GetValue(indicies);
}
return AvaloniaProperty.UnsetValue;
}
private bool ConvertArgumentsToInts(out int[] intArgs)
{
intArgs = new int[Arguments.Count];
for (int i = 0; i < Arguments.Count; ++i)
{
object value;
if (!TypeUtilities.TryConvert(typeof(int), Arguments[i], CultureInfo.InvariantCulture, out value))
{
return false;
}
intArgs[i] = (int)value;
}
return true;
}
private static PropertyInfo GetIndexer(TypeInfo typeInfo)
{
PropertyInfo indexer;
for (; typeInfo != null; typeInfo = typeInfo.BaseType?.GetTypeInfo())
{
// Check for the default indexer name first to make this faster.
// This will only be false when a class in VB has a custom indexer name.
if ((indexer = typeInfo.GetDeclaredProperty(CommonPropertyNames.IndexerName)) != null)
{
return indexer;
}
foreach (var property in typeInfo.DeclaredProperties)
{
if (property.GetIndexParameters().Any())
{
return property;
}
}
}
return null;
}
private bool ValidBounds(int[] indicies, Array array)
{
if (indicies.Length == array.Rank)
{
for (var i = 0; i < indicies.Length; ++i)
{
if (indicies[i] >= array.GetLength(i))
{
return false;
}
}
return true;
}
else
{
return false;
}
}
private bool ShouldUpdate(object sender, NotifyCollectionChangedEventArgs e)
{
if (sender is IList)
{
object indexObject;
if (!TypeUtilities.TryConvert(typeof(int), Arguments[0], CultureInfo.InvariantCulture, out indexObject))
{
return false;
}
var index = (int)indexObject;
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
return index >= e.NewStartingIndex;
case NotifyCollectionChangedAction.Remove:
return index >= e.OldStartingIndex;
case NotifyCollectionChangedAction.Replace:
return index >= e.NewStartingIndex &&
index < e.NewStartingIndex + e.NewItems.Count;
case NotifyCollectionChangedAction.Move:
return (index >= e.NewStartingIndex &&
index < e.NewStartingIndex + e.NewItems.Count) ||
(index >= e.OldStartingIndex &&
index < e.OldStartingIndex + e.OldItems.Count);
case NotifyCollectionChangedAction.Reset:
return true;
}
}
return false;
}
private bool ShouldUpdate(object sender, PropertyChangedEventArgs e)
{
var typeInfo = sender.GetType().GetTypeInfo();
return typeInfo.GetDeclaredProperty(e.PropertyName)?.GetIndexParameters().Any() ?? 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.
//-----------------------------------------------------------------------------
//
// Description:
// ContentType class parses and validates the content-type string.
// It provides functionality to compare the type/subtype values.
//
// Details:
// Grammar which this class follows -
//
// Content-type grammar MUST conform to media-type grammar as per
// RFC 2616 (ABNF notation):
//
// media-type = type "/" subtype *( ";" parameter )
// type = token
// subtype = token
// parameter = attribute "=" value
// attribute = token
// value = token | quoted-string
// quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
// qdtext = <any TEXT except <">>
// quoted-pair = "\" CHAR
// token = 1*<any CHAR except CTLs or separators>
// separators = "(" | ")" | "<" | ">" | "@"
// | "," | ";" | ":" | "\" | <">
// | "/" | "[" | "]" | "?" | "="
// | "{" | "}" | SP | HT
// TEXT = <any OCTET except CTLs, but including LWS>
// OCTET = <any 8-bit sequence of data>
// CHAR = <any US-ASCII character (octets 0 - 127)>
// CTL = <any US-ASCII control character(octets 0 - 31)and DEL(127)>
// CR = <US-ASCII CR, carriage return (13)>
// LF = <US-ASCII LF, linefeed (10)>
// SP = <US-ASCII SP, space (32)>
// HT = <US-ASCII HT, horizontal-tab (9)>
// <"> = <US-ASCII double-quote mark (34)>
// LWS = [CRLF] 1*( SP | HT )
// CRLF = CR LF
// Linear white space (LWS) MUST NOT be used between the type and subtype, nor
// between an attribute and its value. Leading and trailing LWS are prohibited.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic; // For Dictionary<string, string>
using System.Text; // For StringBuilder
using System.Diagnostics; // For Debug.Assert
namespace System.IO.Packaging
{
/// <summary>
/// Content Type class
/// </summary>
internal sealed class ContentType
{
//------------------------------------------------------
//
// Internal Constructors
//
//------------------------------------------------------
#region Internal Constructors
/// <summary>
/// This constructor creates a ContentType object that represents
/// the content-type string. At construction time we validate the
/// string as per the grammar specified in RFC 2616.
/// Note: We allow empty strings as valid input. Empty string should
/// we used more as an indication of an absent/unknown ContentType.
/// </summary>
/// <param name="contentType">content-type</param>
/// <exception cref="ArgumentNullException">If the contentType parameter is null</exception>
/// <exception cref="ArgumentException">If the contentType string has leading or
/// trailing Linear White Spaces(LWS) characters</exception>
/// <exception cref="ArgumentException">If the contentType string invalid CR-LF characters</exception>
internal ContentType(string contentType)
{
if (contentType == null)
throw new ArgumentNullException(nameof(contentType));
if (contentType.Length == 0)
{
_contentType = String.Empty;
}
else
{
if (IsLinearWhiteSpaceChar(contentType[0]) || IsLinearWhiteSpaceChar(contentType[contentType.Length - 1]))
throw new ArgumentException(SR.ContentTypeCannotHaveLeadingTrailingLWS);
//Carriage return can be expressed as '\r\n' or '\n\r'
//We need to make sure that a \r is accompanied by \n
ValidateCarriageReturns(contentType);
//Begin Parsing
int semiColonIndex = contentType.IndexOf(SemicolonSeparator);
if (semiColonIndex == -1)
{
// Parse content type similar to - type/subtype
ParseTypeAndSubType(contentType);
}
else
{
// Parse content type similar to - type/subtype ; param1=value1 ; param2=value2 ; param3="value3"
ParseTypeAndSubType(contentType.Substring(0, semiColonIndex));
ParseParameterAndValue(contentType.Substring(semiColonIndex));
}
}
// keep this untouched for return from OriginalString property
_originalString = contentType;
//This variable is used to print out the correct content type string representation
//using the ToString method. This is mainly important while debugging and seeing the
//value of the content type object in the debugger.
_isInitialized = true;
}
#endregion Internal Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// TypeComponent of the Content Type
/// If the content type is "text/xml". This property will return "text"
/// </summary>
internal string TypeComponent
{
get
{
return _type;
}
}
/// <summary>
/// SubType component
/// If the content type is "text/xml". This property will return "xml"
/// </summary>
internal string SubTypeComponent
{
get
{
return _subType;
}
}
/// <summary>
/// Enumerator which iterates over the Parameter and Value pairs which are stored
/// in a dictionary. We hand out just the enumerator in order to make this property
/// ReadOnly
/// Consider following Content type -
/// type/subtype ; param1=value1 ; param2=value2 ; param3="value3"
/// This will return a enumerator over a dictionary of the parameter/value pairs.
/// </summary>
internal Dictionary<string, string>.Enumerator ParameterValuePairs
{
get
{
EnsureParameterDictionary();
return _parameterDictionary.GetEnumerator();
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <summary>
/// This method does a strong comparison of the content types, as parameters are not allowed.
/// We only compare the type and subType values in an ASCII case-insensitive manner.
/// Parameters are not allowed to be present on any of the content type operands.
/// </summary>
/// <param name="contentType">Content type to be compared with</param>
/// <returns></returns>
internal bool AreTypeAndSubTypeEqual(ContentType contentType)
{
return AreTypeAndSubTypeEqual(contentType, false);
}
/// <summary>
/// This method does a weak comparison of the content types. We only compare the
/// type and subType values in an ASCII case-insensitive manner.
/// Parameter and value pairs are not used for the comparison.
/// If you wish to compare the paramters too, then you must get the ParameterValuePairs from
/// both the ContentType objects and compare each parameter entry.
/// The allowParameterValuePairs parameter is used to indicate whether the
/// comparison is tolerant to parameters being present or no.
/// </summary>
/// <param name="contentType">Content type to be compared with</param>
/// <param name="allowParameterValuePairs">If true, allows the presence of parameter value pairs.
/// If false, parameter/value pairs cannot be present in the content type string.
/// In either case, the parameter value pair is not used for the comparison.</param>
/// <returns></returns>
internal bool AreTypeAndSubTypeEqual(ContentType contentType, bool allowParameterValuePairs)
{
bool result = false;
if (contentType != null)
{
if (!allowParameterValuePairs)
{
//Return false if this content type object has parameters
if (_parameterDictionary != null)
{
if (_parameterDictionary.Count > 0)
return false;
}
//Return false if the content type object passed in has parameters
Dictionary<string, string>.Enumerator contentTypeEnumerator;
contentTypeEnumerator = contentType.ParameterValuePairs;
contentTypeEnumerator.MoveNext();
if (contentTypeEnumerator.Current.Key != null)
return false;
}
// Perform a case-insensitive comparison on the type/subtype strings. This is a
// safe comparison because the _type and _subType strings have been restricted to
// ASCII characters, digits, and a small set of symbols. This is not a safe comparison
// for the broader set of strings that have not been restricted in the same way.
result = (String.Equals(_type, contentType.TypeComponent, StringComparison.OrdinalIgnoreCase) &&
String.Equals(_subType, contentType.SubTypeComponent, StringComparison.OrdinalIgnoreCase));
}
return result;
}
/// <summary>
/// ToString - outputs a normalized form of the content type string
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (_contentType == null)
{
//This is needed so that while debugging we get the correct
//string
if (!_isInitialized)
return String.Empty;
Debug.Assert(String.CompareOrdinal(_type, String.Empty) != 0
|| String.CompareOrdinal(_subType, String.Empty) != 0);
StringBuilder stringBuilder = new StringBuilder(_type);
stringBuilder.Append(PackUriHelper.ForwardSlashChar);
stringBuilder.Append(_subType);
if (_parameterDictionary != null && _parameterDictionary.Count > 0)
{
foreach (string parameterKey in _parameterDictionary.Keys)
{
stringBuilder.Append(s_linearWhiteSpaceChars[0]);
stringBuilder.Append(SemicolonSeparator);
stringBuilder.Append(s_linearWhiteSpaceChars[0]);
stringBuilder.Append(parameterKey);
stringBuilder.Append(EqualSeparator);
stringBuilder.Append(_parameterDictionary[parameterKey]);
}
}
_contentType = stringBuilder.ToString();
}
return _contentType;
}
#endregion Internal Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// This method validates if the content type string has
/// valid CR-LF characters. Specifically we test if '\r' is
/// accompanied by a '\n' in the string, else its an error.
/// </summary>
/// <param name="contentType"></param>
private static void ValidateCarriageReturns(string contentType)
{
Debug.Assert(!IsLinearWhiteSpaceChar(contentType[0]) && !IsLinearWhiteSpaceChar(contentType[contentType.Length - 1]));
//Prior to calling this method we have already checked that first and last
//character of the content type are not Linear White Spaces. So its safe to
//assume that the index will be greater than 0 and less that length-2.
int index = contentType.IndexOf(s_linearWhiteSpaceChars[2]);
while (index != -1)
{
if (contentType[index - 1] == s_linearWhiteSpaceChars[1] || contentType[index + 1] == s_linearWhiteSpaceChars[1])
{
index = contentType.IndexOf(s_linearWhiteSpaceChars[2], ++index);
}
else
throw new ArgumentException(SR.InvalidLinearWhiteSpaceCharacter);
}
}
/// <summary>
/// Parses the type and subType tokens from the string.
/// Also verifies if the Tokens are valid as per the grammar.
/// </summary>
/// <param name="typeAndSubType">substring that has the type and subType of the content type</param>
/// <exception cref="ArgumentException">If the typeAndSubType parameter does not have the "/" character</exception>
private void ParseTypeAndSubType(string typeAndSubType)
{
//okay to trim at this point the end of the string as Linear White Spaces(LWS) chars are allowed here.
typeAndSubType = typeAndSubType.TrimEnd(s_linearWhiteSpaceChars);
string[] splitBasedOnForwardSlash = typeAndSubType.Split(PackUriHelper.s_forwardSlashCharArray);
if (splitBasedOnForwardSlash.Length != 2)
throw new ArgumentException(SR.InvalidTypeSubType);
_type = ValidateToken(splitBasedOnForwardSlash[0]);
_subType = ValidateToken(splitBasedOnForwardSlash[1]);
}
/// <summary>
/// Parse the individual parameter=value strings
/// </summary>
/// <param name="parameterAndValue">This string has the parameter and value pair of the form
/// parameter=value</param>
/// <exception cref="ArgumentException">If the string does not have the required "="</exception>
private void ParseParameterAndValue(string parameterAndValue)
{
while (parameterAndValue != string.Empty)
{
//At this point the first character MUST be a semi-colon
//First time through this test is serving more as an assert.
if (parameterAndValue[0] != SemicolonSeparator)
throw new ArgumentException(SR.ExpectingSemicolon);
//At this point if we have just one semicolon, then its an error.
//Also, there can be no trailing LWS characters, as we already checked for that
//in the constructor.
if (parameterAndValue.Length == 1)
throw new ArgumentException(SR.ExpectingParameterValuePairs);
//Removing the leading ; from the string
parameterAndValue = parameterAndValue.Substring(1);
//okay to trim start as there can be spaces before the begining
//of the parameter name.
parameterAndValue = parameterAndValue.TrimStart(s_linearWhiteSpaceChars);
int equalSignIndex = parameterAndValue.IndexOf(EqualSeparator);
if (equalSignIndex <= 0 || equalSignIndex == (parameterAndValue.Length - 1))
throw new ArgumentException(SR.InvalidParameterValuePair);
int parameterStartIndex = equalSignIndex + 1;
//Get length of the parameter value
int parameterValueLength = GetLengthOfParameterValue(parameterAndValue, parameterStartIndex);
EnsureParameterDictionary();
_parameterDictionary.Add(
ValidateToken(parameterAndValue.Substring(0, equalSignIndex)),
ValidateQuotedStringOrToken(parameterAndValue.Substring(parameterStartIndex, parameterValueLength)));
parameterAndValue = parameterAndValue.Substring(parameterStartIndex + parameterValueLength).TrimStart(s_linearWhiteSpaceChars);
}
}
/// <summary>
/// This method returns the length of the first parameter value in the input string.
/// </summary>
/// <param name="s"></param>
/// <param name="startIndex">Starting index for parsing</param>
/// <returns></returns>
private static int GetLengthOfParameterValue(string s, int startIndex)
{
Debug.Assert(s != null);
int length = 0;
//if the parameter value does not start with a '"' then,
//we expect a valid token. So we look for Linear White Spaces or
//a ';' as the terminator for the token value.
if (s[startIndex] != '"')
{
int semicolonIndex = s.IndexOf(SemicolonSeparator, startIndex);
if (semicolonIndex != -1)
{
int lwsIndex = s.IndexOfAny(s_linearWhiteSpaceChars, startIndex);
if (lwsIndex != -1 && lwsIndex < semicolonIndex)
length = lwsIndex;
else
length = semicolonIndex;
}
else
length = semicolonIndex;
//If there is no linear white space found we treat the entire remaining string as
//parameter value.
if (length == -1)
length = s.Length;
}
else
{
//if the parameter value starts with a '"' then, we need to look for the
//pairing '"' that is not preceded by a "\" ["\" is used to escape the '"']
bool found = false;
length = startIndex;
while (!found)
{
length = s.IndexOf('"', ++length);
if (length == -1)
throw new ArgumentException(SR.InvalidParameterValue);
if (s[length - 1] != '\\')
{
found = true;
length++;
}
}
}
return length - startIndex;
}
/// <summary>
/// Validating the given token
/// The following checks are being made -
/// 1. If all the characters in the token are either ASCII letter or digit.
/// 2. If all the characters in the token are either from the remaining allowed cha----ter set.
/// </summary>
/// <param name="token">string token</param>
/// <returns>validated string token</returns>
/// <exception cref="ArgumentException">If the token is Empty</exception>
private static string ValidateToken(string token)
{
if (String.IsNullOrEmpty(token))
throw new ArgumentException(SR.InvalidToken);
for (int i = 0; i < token.Length; i++)
{
if (!IsAsciiLetterOrDigit(token[i]) && !IsAllowedCharacter(token[i]))
{
throw new ArgumentException(SR.InvalidToken);
}
}
return token;
}
/// <summary>
/// Validating if the value of a parameter is either a valid token or a
/// valid quoted string
/// </summary>
/// <param name="parameterValue">paramter value string</param>
/// <returns>validate parameter value string</returns>
/// <exception cref="ArgumentException">If the paramter value is empty</exception>
private static string ValidateQuotedStringOrToken(string parameterValue)
{
if (String.IsNullOrEmpty(parameterValue))
throw new ArgumentException(SR.InvalidParameterValue);
if (parameterValue.Length >= 2 &&
parameterValue.StartsWith(Quote, StringComparison.Ordinal) &&
parameterValue.EndsWith(Quote, StringComparison.Ordinal))
ValidateQuotedText(parameterValue.Substring(1, parameterValue.Length - 2));
else
ValidateToken(parameterValue);
return parameterValue;
}
/// <summary>
/// This method validates if the text in the quoted string
/// </summary>
/// <param name="quotedText"></param>
private static void ValidateQuotedText(string quotedText)
{
//empty is okay
for (int i = 0; i < quotedText.Length; i++)
{
if (IsLinearWhiteSpaceChar(quotedText[i]))
continue;
if (quotedText[i] <= ' ' || quotedText[i] >= 0xFF)
throw new ArgumentException(SR.InvalidParameterValue);
else
if (quotedText[i] == '"' &&
(i == 0 || quotedText[i - 1] != '\\'))
throw new ArgumentException(SR.InvalidParameterValue);
}
}
/// <summary>
/// Returns true if the input character is an allowed character
/// Returns false if the input cha----ter is not an allowed character
/// </summary>
/// <param name="character">input character</param>
/// <returns></returns>
private static bool IsAllowedCharacter(char character)
{
return Array.IndexOf(s_allowedCharacters, character) >= 0;
}
/// <summary>
/// Returns true if the input character is an ASCII digit or letter
/// Returns false if the input character is not an ASCII digit or letter
/// </summary>
/// <param name="character">input character</param>
/// <returns></returns>
private static bool IsAsciiLetterOrDigit(char character)
{
return (IsAsciiLetter(character) || (character >= '0' && character <= '9'));
}
/// <summary>
/// Returns true if the input character is an ASCII letter
/// Returns false if the input character is not an ASCII letter
/// </summary>
/// <param name="character">input character</param>
/// <returns></returns>
private static bool IsAsciiLetter(char character)
{
return
(character >= 'a' && character <= 'z') ||
(character >= 'A' && character <= 'Z');
}
/// <summary>
/// Returns true if the input character is one of the Linear White Space characters -
/// ' ', '\t', '\n', '\r'
/// Returns false if the input character is none of the above
/// </summary>
/// <param name="ch">input character</param>
/// <returns></returns>
private static bool IsLinearWhiteSpaceChar(char ch)
{
if (ch > ' ')
{
return false;
}
int whiteSpaceIndex = Array.IndexOf(s_linearWhiteSpaceChars, ch);
return whiteSpaceIndex != -1;
}
/// <summary>
/// Lazy initialization for the ParameterDictionary
/// </summary>
private void EnsureParameterDictionary()
{
if (_parameterDictionary == null)
{
_parameterDictionary = new Dictionary<string, string>(); //initial size 0
}
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Members
//
//------------------------------------------------------
#region Private Members
private string _contentType = null;
private string _type = String.Empty;
private string _subType = String.Empty;
private string _originalString;
private Dictionary<string, string> _parameterDictionary = null;
private bool _isInitialized = false;
private const string Quote = "\"";
private const char SemicolonSeparator = ';';
private const char EqualSeparator = '=';
//This array is sorted by the ascii value of these characters.
private static readonly char[] s_allowedCharacters =
{ '!' /*33*/, '#' /*35*/ , '$' /*36*/,
'%' /*37*/, '&' /*38*/ , '\'' /*39*/,
'*' /*42*/, '+' /*43*/ , '-' /*45*/,
'.' /*46*/, '^' /*94*/ , '_' /*95*/,
'`' /*96*/, '|' /*124*/, '~' /*126*/,
};
//Linear White Space characters
private static readonly char[] s_linearWhiteSpaceChars =
{ ' ', // space - \x20
'\n', // new line - \x0A
'\r', // carriage return - \x0D
'\t' // horizontal tab - \x09
};
#endregion Private Members
}
}
| |
// 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.Reflection;
using Xunit;
namespace System.Linq.Tests
{
public partial class GroupByTests : EnumerableTests
{
public static void AssertGroupingCorrect<TKey, TElement>(IEnumerable<TKey> keys, IEnumerable<TElement> elements, IEnumerable<IGrouping<TKey, TElement>> grouping)
{
AssertGroupingCorrect<TKey, TElement>(keys, elements, grouping, EqualityComparer<TKey>.Default);
}
public static void AssertGroupingCorrect<TKey, TElement>(IEnumerable<TKey> keys, IEnumerable<TElement> elements, IEnumerable<IGrouping<TKey, TElement>> grouping, IEqualityComparer<TKey> keyComparer)
{
if (grouping == null)
{
Assert.Null(elements);
Assert.Null(keys);
return;
}
Assert.NotNull(elements);
Assert.NotNull(keys);
Dictionary<TKey, List<TElement>> dict = new Dictionary<TKey, List<TElement>>(keyComparer);
List<TElement> groupingForNullKeys = new List<TElement>();
using (IEnumerator<TElement> elEn = elements.GetEnumerator())
using (IEnumerator<TKey> keyEn = keys.GetEnumerator())
{
while (keyEn.MoveNext())
{
Assert.True(elEn.MoveNext());
TKey key = keyEn.Current;
if (key == null)
{
groupingForNullKeys.Add(elEn.Current);
}
else
{
List<TElement> list;
if (!dict.TryGetValue(key, out list))
dict.Add(key, list = new List<TElement>());
list.Add(elEn.Current);
}
}
Assert.False(elEn.MoveNext());
}
foreach (IGrouping<TKey, TElement> group in grouping)
{
Assert.NotEmpty(group);
TKey key = group.Key;
List<TElement> list;
if (key == null)
{
Assert.Equal(groupingForNullKeys, group);
groupingForNullKeys.Clear();
}
else
{
Assert.True(dict.TryGetValue(key, out list));
Assert.Equal(list, group);
dict.Remove(key);
}
}
Assert.Empty(dict);
Assert.Empty(groupingForNullKeys);
}
public struct Record
{
public string Name;
public int Score;
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" }
select x1; ;
var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 }
select x2;
var q = from x3 in q1
from x4 in q2
select new { a1 = x3, a2 = x4 };
Assert.NotNull(q.GroupBy(e => e.a1, e => e.a2));
Assert.Equal(q.GroupBy(e => e.a1, e => e.a2), q.GroupBy(e => e.a1, e => e.a2));
}
[Fact]
public void Grouping_IList_IsReadOnly()
{
IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0);
foreach (IList<int> grouping in oddsEvens)
{
Assert.True(grouping.IsReadOnly);
}
}
[Fact]
public void Grouping_IList_NotSupported()
{
IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0);
foreach (IList<int> grouping in oddsEvens)
{
Assert.Throws<NotSupportedException>(() => grouping.Add(5));
Assert.Throws<NotSupportedException>(() => grouping.Clear());
Assert.Throws<NotSupportedException>(() => grouping.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => grouping.Remove(1));
Assert.Throws<NotSupportedException>(() => grouping.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => grouping[0] = 1);
}
}
[Fact]
public void Grouping_IList_IndexerGetter()
{
IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0);
var e = oddsEvens.GetEnumerator();
Assert.True(e.MoveNext());
IList<int> odds = (IList<int>)e.Current;
Assert.Equal(1, odds[0]);
Assert.Equal(3, odds[1]);
Assert.True(e.MoveNext());
IList<int> evens = (IList<int>)e.Current;
Assert.Equal(2, evens[0]);
Assert.Equal(4, evens[1]);
}
[Fact]
public void Grouping_IList_IndexGetterOutOfRange()
{
IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0);
var e = oddsEvens.GetEnumerator();
Assert.True(e.MoveNext());
IList<int> odds = (IList<int>)e.Current;
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => odds[-1]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => odds[23]);
}
[Fact]
public void Grouping_ICollection_Contains()
{
IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0);
var e = oddsEvens.GetEnumerator();
Assert.True(e.MoveNext());
ICollection<int> odds = (IList<int>)e.Current;
Assert.True(odds.Contains(1));
Assert.True(odds.Contains(3));
Assert.False(odds.Contains(2));
Assert.False(odds.Contains(4));
Assert.True(e.MoveNext());
ICollection<int> evens = (IList<int>)e.Current;
Assert.True(evens.Contains(2));
Assert.True(evens.Contains(4));
Assert.False(evens.Contains(1));
Assert.False(evens.Contains(3));
}
[Fact]
public void Grouping_IList_IndexOf()
{
IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0);
var e = oddsEvens.GetEnumerator();
Assert.True(e.MoveNext());
IList<int> odds = (IList<int>)e.Current;
Assert.Equal(0, odds.IndexOf(1));
Assert.Equal(1, odds.IndexOf(3));
Assert.Equal(-1, odds.IndexOf(2));
Assert.Equal(-1, odds.IndexOf(4));
Assert.True(e.MoveNext());
IList<int> evens = (IList<int>)e.Current;
Assert.Equal(0, evens.IndexOf(2));
Assert.Equal(1, evens.IndexOf(4));
Assert.Equal(-1, evens.IndexOf(1));
Assert.Equal(-1, evens.IndexOf(3));
}
[Fact]
public void SingleNullKeySingleNullElement()
{
string[] key = { null };
string[] element = { null };
AssertGroupingCorrect(key, element, new string[] { null }.GroupBy(e => e, e => e, EqualityComparer<string>.Default), EqualityComparer<string>.Default);
}
[Fact]
public void EmptySource()
{
string[] key = { };
int[] element = { };
Record[] source = { };
Assert.Empty(new Record[] { }.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
}
[Fact]
public void EmptySourceRunOnce()
{
string[] key = { };
int[] element = { };
Record[] source = { };
Assert.Empty(new Record[] { }.RunOnce().GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
}
[Fact]
public void SourceIsNull()
{
Record[] source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, new AnagramEqualityComparer()));
}
[Fact]
public void SourceIsNullResultSelectorUsed()
{
Record[] source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer()));
}
[Fact]
public void SourceIsNullResultSelectorUsedNoComparer()
{
Record[] source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum()));
}
[Fact]
public void SourceIsNullResultSelectorUsedNoComparerOrElementSelector()
{
Record[] source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, (k, es) => es.Sum(e => e.Score)));
}
[Fact]
public void KeySelectorNull()
{
Record[] source = new[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, e => e.Score, new AnagramEqualityComparer()));
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, new AnagramEqualityComparer()));
}
[Fact]
public void KeySelectorNullResultSelectorUsed()
{
Record[] source = new[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer()));
}
[Fact]
public void KeySelectorNullResultSelectorUsedNoComparer()
{
Record[] source = new[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Func<Record, string> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(keySelector, e => e.Score, (k, es) => es.Sum()));
}
[Fact]
public void KeySelectorNullResultSelectorUsedNoElementSelector()
{
string[] key = { "Tim", "Tim", "Tim", "Tim" };
int[] element = { 60, -10, 40, 100 };
var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e });
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, (k, es) => es.Sum(e => e.Score), new AnagramEqualityComparer()));
}
[Fact]
public void ElementSelectorNull()
{
Record[] source = new[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Func<Record, int> elementSelector = null;
AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => source.GroupBy(e => e.Name, elementSelector, new AnagramEqualityComparer()));
}
[Fact]
public void ElementSelectorNullResultSelectorUsedNoComparer()
{
Record[] source = new[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Func<Record, int> elementSelector = null;
AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => source.GroupBy(e => e.Name, elementSelector, (k, es) => es.Sum()));
}
[Fact]
public void ResultSelectorNull()
{
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Func<string, IEnumerable<int>, long> resultSelector = null;
AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, e => e.Score, resultSelector, new AnagramEqualityComparer()));
}
[Fact]
public void ResultSelectorNullNoComparer()
{
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Func<string, IEnumerable<int>, long> resultSelector = null;
AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, e => e.Score, resultSelector));
}
[Fact]
public void ResultSelectorNullNoElementSelector()
{
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Func<string, IEnumerable<Record>, long> resultSelector = null;
AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, resultSelector));
}
[Fact]
public void ResultSelectorNullNoElementSelectorCustomComparer()
{
string[] key = { "Tim", "Tim", "Tim", "Tim" };
int[] element = { 60, -10, 40, 100 };
var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e });
Func<string, IEnumerable<Record>, long> resultSelector = null;
AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, resultSelector, new AnagramEqualityComparer()));
}
[Fact]
public void EmptySourceWithResultSelector()
{
string[] key = { };
int[] element = { };
Record[] source = { };
Assert.Empty(new Record[] { }.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer()));
}
[Fact]
public void DuplicateKeysCustomComparer()
{
string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" };
int[] element = { 55, 25, 49, 24, -100, 9 };
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "miT", Score = 25 }
};
long[] expected = { 240, 365, -600, 63 };
Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer()));
}
[Fact]
public void DuplicateKeysCustomComparerRunOnce()
{
string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" };
int[] element = { 55, 25, 49, 24, -100, 9 };
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "miT", Score = 25 }
};
long[] expected = { 240, 365, -600, 63 };
Assert.Equal(expected, source.RunOnce().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer()));
}
[Fact]
public void NullComparer()
{
string[] key = { "Tim", null, null, "Robert", "Chris", "miT" };
int[] element = { 55, 49, 9, -100, 24, 25 };
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = null, Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = null, Score = 9 },
new Record { Name = "miT", Score = 25 }
};
long[] expected = { 165, 58, -600, 120, 75 };
Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), null));
}
[Fact]
public void NullComparerRunOnce()
{
string[] key = { "Tim", null, null, "Robert", "Chris", "miT" };
int[] element = { 55, 49, 9, -100, 24, 25 };
Record[] source = {
new Record { Name = "Tim", Score = 55 },
new Record { Name = null, Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = null, Score = 9 },
new Record { Name = "miT", Score = 25 }
};
long[] expected = { 165, 58, -600, 120, 75 };
Assert.Equal(expected, source.RunOnce().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), null));
}
[Fact]
public void SingleNonNullElement()
{
string[] key = { "Tim" };
Record[] source = { new Record { Name = key[0], Score = 60 } };
AssertGroupingCorrect(key, source, source.GroupBy(e => e.Name));
}
[Fact]
public void AllElementsSameKey()
{
string[] key = { "Tim", "Tim", "Tim", "Tim" };
int[] scores = { 60, -10, 40, 100 };
var source = key.Zip(scores, (k, e) => new Record { Name = k, Score = e });
AssertGroupingCorrect(key, source, source.GroupBy(e => e.Name, new AnagramEqualityComparer()), new AnagramEqualityComparer());
}
[Fact]
public void AllElementsDifferentKeyElementSelectorUsed()
{
string[] key = { "Tim", "Chris", "Robert", "Prakash" };
int[] element = { 60, -10, 40, 100 };
var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e });
AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score));
}
[Fact]
public void SomeDuplicateKeys()
{
string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" };
int[] element = { 55, 25, 49, 24, -100, 9 };
var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e });
AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score));
}
[Fact]
public void SomeDuplicateKeysIncludingNulls()
{
string[] key = { null, null, "Chris", "Chris", "Prakash", "Prakash" };
int[] element = { 55, 25, 49, 24, 9, 9 };
var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e });
AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score));
}
[Fact]
public void SingleElementResultSelectorUsed()
{
string[] key = { "Tim" };
int[] element = { 60 };
long[] expected = { 180 };
var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e });
Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => (long)(k ?? " ").Length * es.Sum(e => e.Score)));
}
[Fact]
public void GroupedResultCorrectSize()
{
var elements = Enumerable.Repeat('q', 5);
var result = elements.GroupBy(e => e, (e, f) => new { Key = e, Element = f });
Assert.Equal(1, result.Count());
var grouping = result.First();
Assert.Equal(5, grouping.Element.Count());
Assert.Equal('q', grouping.Key);
Assert.True(grouping.Element.All(e => e == 'q'));
}
[Fact]
public void AllElementsDifferentKeyElementSelectorUsedResultSelector()
{
string[] key = { "Tim", "Chris", "Robert", "Prakash" };
int[] element = { 60, -10, 40, 100 };
var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e });
long[] expected = { 180, -50, 240, 700 };
Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum()));
}
[Fact]
public void AllElementsSameKeyResultSelectorUsed()
{
int[] element = { 60, -10, 40, 100 };
long[] expected = { 570 };
Record[] source = {
new Record { Name = "Tim", Score = element[0] },
new Record { Name = "Tim", Score = element[1] },
new Record { Name = "miT", Score = element[2] },
new Record { Name = "miT", Score = element[3] }
};
Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), new AnagramEqualityComparer()));
}
[Fact]
public void NullComparerResultSelectorUsed()
{
int[] element = { 60, -10, 40, 100 };
Record[] source = {
new Record { Name = "Tim", Score = element[0] },
new Record { Name = "Tim", Score = element[1] },
new Record { Name = "miT", Score = element[2] },
new Record { Name = "miT", Score = element[3] },
};
long[] expected = { 150, 420 };
Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), null));
}
[Fact]
public void GroupingToArray()
{
Record[] source = new Record[]
{
new Record{ Name = "Tim", Score = 55 },
new Record{ Name = "Chris", Score = 49 },
new Record{ Name = "Robert", Score = -100 },
new Record{ Name = "Chris", Score = 24 },
new Record{ Name = "Prakash", Score = 9 },
new Record{ Name = "Tim", Score = 25 }
};
IGrouping<string, Record>[] groupedArray = source.GroupBy(r => r.Name).ToArray();
Assert.Equal(4, groupedArray.Length);
Assert.Equal(source.GroupBy(r => r.Name), groupedArray);
}
[Fact]
public void GroupingWithElementSelectorToArray()
{
Record[] source = new Record[]
{
new Record{ Name = "Tim", Score = 55 },
new Record{ Name = "Chris", Score = 49 },
new Record{ Name = "Robert", Score = -100 },
new Record{ Name = "Chris", Score = 24 },
new Record{ Name = "Prakash", Score = 9 },
new Record{ Name = "Tim", Score = 25 }
};
IGrouping<string, int>[] groupedArray = source.GroupBy(r => r.Name, e => e.Score).ToArray();
Assert.Equal(4, groupedArray.Length);
Assert.Equal(source.GroupBy(r => r.Name, e => e.Score), groupedArray);
}
[Fact]
public void GroupingWithResultsToArray()
{
Record[] source = new Record[]
{
new Record{ Name = "Tim", Score = 55 },
new Record{ Name = "Chris", Score = 49 },
new Record{ Name = "Robert", Score = -100 },
new Record{ Name = "Chris", Score = 24 },
new Record{ Name = "Prakash", Score = 9 },
new Record{ Name = "Tim", Score = 25 }
};
IEnumerable<Record>[] groupedArray = source.GroupBy(r => r.Name, (r, e) => e).ToArray();
Assert.Equal(4, groupedArray.Length);
Assert.Equal(source.GroupBy(r => r.Name, (r, e) => e), groupedArray);
}
[Fact]
public void GroupingWithElementSelectorAndResultsToArray()
{
Record[] source = new Record[]
{
new Record{ Name = "Tim", Score = 55 },
new Record{ Name = "Chris", Score = 49 },
new Record{ Name = "Robert", Score = -100 },
new Record{ Name = "Chris", Score = 24 },
new Record{ Name = "Prakash", Score = 9 },
new Record{ Name = "Tim", Score = 25 }
};
IEnumerable<Record>[] groupedArray = source.GroupBy(r => r.Name, e => e, (r, e) => e).ToArray();
Assert.Equal(4, groupedArray.Length);
Assert.Equal(source.GroupBy(r => r.Name, e => e, (r, e) => e), groupedArray);
}
[Fact]
public void GroupingToList()
{
Record[] source = new Record[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
List<IGrouping<string, Record>> groupedList = source.GroupBy(r => r.Name).ToList();
Assert.Equal(4, groupedList.Count);
Assert.Equal(source.GroupBy(r => r.Name), groupedList);
}
[Fact]
public void GroupingWithElementSelectorToList()
{
Record[] source = new Record[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
List<IGrouping<string, int>> groupedList = source.GroupBy(r => r.Name, e => e.Score).ToList();
Assert.Equal(4, groupedList.Count);
Assert.Equal(source.GroupBy(r => r.Name, e => e.Score), groupedList);
}
[Fact]
public void GroupingWithResultsToList()
{
Record[] source = new Record[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
List<IEnumerable<Record>> groupedList = source.GroupBy(r => r.Name, (r, e) => e).ToList();
Assert.Equal(4, groupedList.Count);
Assert.Equal(source.GroupBy(r => r.Name, (r, e) => e), groupedList);
}
[Fact]
public void GroupingWithElementSelectorAndResultsToList()
{
Record[] source = new Record[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
List<IEnumerable<Record>> groupedList = source.GroupBy(r => r.Name, e => e, (r, e) => e).ToList();
Assert.Equal(4, groupedList.Count);
Assert.Equal(source.GroupBy(r => r.Name, e => e, (r, e) => e), groupedList);
}
[Fact]
public void GroupingCount()
{
Record[] source = new Record[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Assert.Equal(4, source.GroupBy(r => r.Name).Count());
}
[Fact]
public void GroupingWithElementSelectorCount()
{
Record[] source = new Record[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Assert.Equal(4, source.GroupBy(r => r.Name, e => e.Score).Count());
}
[Fact]
public void GroupingWithResultsCount()
{
Record[] source = new Record[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Assert.Equal(4, source.GroupBy(r => r.Name, (r, e) => e).Count());
}
[Fact]
public void GroupingWithElementSelectorAndResultsCount()
{
Record[] source = new Record[]
{
new Record { Name = "Tim", Score = 55 },
new Record { Name = "Chris", Score = 49 },
new Record { Name = "Robert", Score = -100 },
new Record { Name = "Chris", Score = 24 },
new Record { Name = "Prakash", Score = 9 },
new Record { Name = "Tim", Score = 25 }
};
Assert.Equal(4, source.GroupBy(r => r.Name, e=> e, (r, e) => e).Count());
}
[Fact]
public void EmptyGroupingToArray()
{
Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i).ToArray());
}
[Fact]
public void EmptyGroupingToList()
{
Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i).ToList());
}
[Fact]
public void EmptyGroupingCount()
{
Assert.Equal(0, Enumerable.Empty<int>().GroupBy(i => i).Count());
}
[Fact]
public void EmptyGroupingWithResultToArray()
{
Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i, (x, y) => x + y.Count()).ToArray());
}
[Fact]
public void EmptyGroupingWithResultToList()
{
Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i, (x, y) => x + y.Count()).ToList());
}
[Fact]
public void EmptyGroupingWithResultCount()
{
Assert.Equal(0, Enumerable.Empty<int>().GroupBy(i => i, (x, y) => x + y.Count()).Count());
}
[Fact]
public static void GroupingKeyIsPublic()
{
// Grouping.Key needs to be public (not explicitly implemented) for the sake of WPF.
object[] objs = { "Foo", 1.0M, "Bar", new { X = "X" }, 2.00M };
object group = objs.GroupBy(x => x.GetType()).First();
Type grouptype = group.GetType();
PropertyInfo key = grouptype.GetProperty("Key", BindingFlags.Instance | BindingFlags.Public);
Assert.NotNull(key);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Nancy.Helpers;
namespace Nancy.ViewEngines.Razor.HtmlHelpersUnofficial.MvcBits
{
public class TagBuilder
{
private static string _idAttributeDotReplacement;
private string _innerHtml;
public static string IdAttributeDotReplacement
{
get
{
if (String.IsNullOrEmpty(_idAttributeDotReplacement))
{
_idAttributeDotReplacement = "_";
}
return _idAttributeDotReplacement;
}
set { _idAttributeDotReplacement = value; }
}
public TagBuilder(string tagName)
{
if (String.IsNullOrEmpty(tagName))
{
throw new ArgumentException("Argument_Cannot_Be_Null_Or_Empty", "tagName");
}
TagName = tagName;
Attributes = new SortedDictionary<string, string>(StringComparer.Ordinal);
}
public IDictionary<string, string> Attributes { get; private set; }
public string InnerHtml
{
get { return _innerHtml ?? String.Empty; }
set { _innerHtml = value; }
}
public string TagName { get; private set; }
public void AddCssClass(string value)
{
string currentValue;
if (Attributes.TryGetValue("class", out currentValue))
{
Attributes["class"] = value + " " + currentValue;
}
else
{
Attributes["class"] = value;
}
}
public static string CreateSanitizedId(string originalId)
{
return CreateSanitizedId(originalId, IdAttributeDotReplacement);
}
public static string CreateSanitizedId(string originalId, string invalidCharReplacement)
{
if (String.IsNullOrEmpty(originalId))
{
return null;
}
if (invalidCharReplacement == null)
{
throw new ArgumentNullException("invalidCharReplacement");
}
char firstChar = originalId[0];
if (!Html401IdUtil.IsLetter(firstChar))
{
// the first character must be a letter
return null;
}
var sb = new StringBuilder(originalId.Length);
sb.Append(firstChar);
for (var i = 1; i < originalId.Length; i++)
{
var thisChar = originalId[i];
if (Html401IdUtil.IsValidIdCharacter(thisChar))
{
sb.Append(thisChar);
}
else
{
sb.Append(invalidCharReplacement);
}
}
return sb.ToString();
}
public void GenerateId(string name)
{
if (Attributes.ContainsKey("id"))
{
return;
}
var sanitizedId = CreateSanitizedId(name, IdAttributeDotReplacement);
if (String.IsNullOrEmpty(sanitizedId))
{
return;
}
Attributes["id"] = sanitizedId;
}
private void AppendAttributes(StringBuilder sb)
{
foreach (var attribute in Attributes)
{
var key = attribute.Key;
if (String.Equals(key, "id", StringComparison.Ordinal /* case-sensitive */) && String.IsNullOrEmpty(attribute.Value))
{
continue; // DevDiv Bugs #227595: don't output empty IDs
}
var value = HttpUtility.HtmlAttributeEncode(attribute.Value);
sb.Append(' ').Append(key).Append("=\"").Append(value).Append('"');
}
}
public void MergeAttribute(string key, string value)
{
MergeAttribute(key, value, false);
}
public void MergeAttribute(string key, string value, bool replaceExisting)
{
if (String.IsNullOrEmpty(key))
{
throw new ArgumentException("Argument_Cannot_Be_Null_Or_Empty", "key");
}
if (replaceExisting || !Attributes.ContainsKey(key))
{
Attributes[key] = value;
}
}
public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes)
{
MergeAttributes(attributes, false);
}
public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes, bool replaceExisting)
{
if (attributes == null) return;
foreach (var entry in attributes)
{
var key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
var value = Convert.ToString(entry.Value, CultureInfo.InvariantCulture);
MergeAttribute(key, value, replaceExisting);
}
}
public void SetInnerText(string innerText)
{
InnerHtml = HttpUtility.HtmlEncode(innerText);
}
internal HtmlString ToHtmlString(TagRenderMode renderMode)
{
return new HtmlString(ToString(renderMode));
}
public override string ToString()
{
return ToString(TagRenderMode.Normal);
}
public string ToString(TagRenderMode renderMode)
{
var sb = new StringBuilder();
switch (renderMode)
{
case TagRenderMode.StartTag:
sb.Append('<')
.Append(TagName);
AppendAttributes(sb);
sb.Append('>');
break;
case TagRenderMode.EndTag:
sb.Append("</")
.Append(TagName)
.Append('>');
break;
case TagRenderMode.SelfClosing:
sb.Append('<')
.Append(TagName);
AppendAttributes(sb);
sb.Append(" />");
break;
default:
sb.Append('<')
.Append(TagName);
AppendAttributes(sb);
sb.Append('>')
.Append(InnerHtml)
.Append("</")
.Append(TagName)
.Append('>');
break;
}
return sb.ToString();
}
// Valid IDs are defined in http://www.w3.org/TR/html401/types.html#type-id
private static class Html401IdUtil
{
private static bool IsAllowableSpecialCharacter(char c)
{
switch (c)
{
case '-':
case '_':
case ':':
// note that we're specifically excluding the '.' character
return true;
default:
return false;
}
}
private static bool IsDigit(char c)
{
return ('0' <= c && c <= '9');
}
public static bool IsLetter(char c)
{
return (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'));
}
public static bool IsValidIdCharacter(char c)
{
return (IsLetter(c) || IsDigit(c) || IsAllowableSpecialCharacter(c));
}
}
}
public enum TagRenderMode
{
Normal,
StartTag,
EndTag,
SelfClosing,
}
}
| |
// 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.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading.Tests;
using Xunit;
namespace System.Threading.Threads.Tests
{
public static class ThreadTests
{
private const int UnexpectedTimeoutMilliseconds = ThreadTestHelpers.UnexpectedTimeoutMilliseconds;
private const int ExpectedTimeoutMilliseconds = ThreadTestHelpers.ExpectedTimeoutMilliseconds;
[Fact]
public static void ConstructorTest()
{
Action<Thread> startThreadAndJoin =
t =>
{
t.IsBackground = true;
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
};
Action<int> verifyStackSize =
stackSizeBytes =>
{
// Try to stack-allocate an array to verify that close to the expected amount of stack space is actually
// available
int bufferSizeBytes = Math.Max(16 << 10, stackSizeBytes - (64 << 10));
unsafe
{
byte* buffer = stackalloc byte[bufferSizeBytes];
Volatile.Write(ref buffer[0], 0xff);
Volatile.Write(ref buffer[bufferSizeBytes - 1], 0xff);
}
};
startThreadAndJoin(new Thread(() => verifyStackSize(0)));
startThreadAndJoin(new Thread(() => verifyStackSize(0), 0));
startThreadAndJoin(new Thread(() => verifyStackSize(64 << 10), 64 << 10)); // 64 KB
startThreadAndJoin(new Thread(() => verifyStackSize(16 << 20), 16 << 20)); // 16 MB
startThreadAndJoin(new Thread(state => verifyStackSize(0)));
startThreadAndJoin(new Thread(state => verifyStackSize(0), 0));
startThreadAndJoin(new Thread(state => verifyStackSize(64 << 10), 64 << 10)); // 64 KB
startThreadAndJoin(new Thread(state => verifyStackSize(16 << 20), 16 << 20)); // 16 MB
Assert.Throws<ArgumentNullException>(() => new Thread((ThreadStart)null));
Assert.Throws<ArgumentNullException>(() => new Thread((ThreadStart)null, 0));
Assert.Throws<ArgumentNullException>(() => new Thread((ParameterizedThreadStart)null));
Assert.Throws<ArgumentNullException>(() => new Thread((ParameterizedThreadStart)null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new Thread(() => { }, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Thread(state => { }, -1));
}
private static IEnumerable<object[]> ApartmentStateTest_MemberData()
{
yield return
new object[]
{
#pragma warning disable 618 // Obsolete members
new Func<Thread, ApartmentState>(t => t.ApartmentState),
#pragma warning restore 618 // Obsolete members
new Func<Thread, ApartmentState, int>(
(t, value) =>
{
try
{
#pragma warning disable 618 // Obsolete members
t.ApartmentState = value;
#pragma warning restore 618 // Obsolete members
return 0;
}
catch (ArgumentOutOfRangeException)
{
return 1;
}
catch (PlatformNotSupportedException)
{
return 3;
}
}),
0
};
yield return
new object[]
{
new Func<Thread, ApartmentState>(t => t.GetApartmentState()),
new Func<Thread, ApartmentState, int>(
(t, value) =>
{
try
{
t.SetApartmentState(value);
return 0;
}
catch (ArgumentOutOfRangeException)
{
return 1;
}
catch (InvalidOperationException)
{
return 2;
}
catch (PlatformNotSupportedException)
{
return 3;
}
}),
1
};
yield return
new object[]
{
new Func<Thread, ApartmentState>(t => t.GetApartmentState()),
new Func<Thread, ApartmentState, int>(
(t, value) =>
{
try
{
return t.TrySetApartmentState(value) ? 0 : 2;
}
catch (ArgumentOutOfRangeException)
{
return 1;
}
catch (PlatformNotSupportedException)
{
return 3;
}
}),
2
};
}
[Theory]
[MemberData(nameof(ApartmentStateTest_MemberData))]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior differs on Unix and Windows
[ActiveIssue(20766,TargetFrameworkMonikers.UapAot)]
public static void GetSetApartmentStateTest_ChangeAfterThreadStarted_Windows(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var t = Thread.CurrentThread;
Assert.Equal(1, setApartmentState(t, ApartmentState.STA - 1));
Assert.Equal(1, setApartmentState(t, ApartmentState.Unknown + 1));
Assert.Equal(ApartmentState.MTA, getApartmentState(t));
Assert.Equal(0, setApartmentState(t, ApartmentState.MTA));
Assert.Equal(ApartmentState.MTA, getApartmentState(t));
Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.STA)); // cannot be changed after thread is started
Assert.Equal(ApartmentState.MTA, getApartmentState(t));
});
}
[Theory]
[MemberData(nameof(ApartmentStateTest_MemberData))]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior differs on Unix and Windows
[ActiveIssue(20766,TargetFrameworkMonikers.UapAot)]
public static void ApartmentStateTest_ChangeBeforeThreadStarted_Windows(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
ApartmentState apartmentStateInThread = ApartmentState.Unknown;
Thread t = null;
t = new Thread(() => apartmentStateInThread = getApartmentState(t));
t.IsBackground = true;
Assert.Equal(0, setApartmentState(t, ApartmentState.STA));
Assert.Equal(ApartmentState.STA, getApartmentState(t));
Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.MTA)); // cannot be changed more than once
Assert.Equal(ApartmentState.STA, getApartmentState(t));
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
if (PlatformDetection.IsWindowsNanoServer)
{
// Nano server threads are always MTA. If you set the thread to STA
// it will read back as STA but when the thread starts it will read back as MTA.
Assert.Equal(ApartmentState.MTA, apartmentStateInThread);
}
else
{
Assert.Equal(ApartmentState.STA, apartmentStateInThread);
}
}
[Theory]
[MemberData(nameof(ApartmentStateTest_MemberData))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior differs on Unix and Windows
public static void ApartmentStateTest_Unix(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
var t = new Thread(() => { });
Assert.Equal(ApartmentState.Unknown, getApartmentState(t));
Assert.Equal(0, setApartmentState(t, ApartmentState.Unknown));
int expectedFailure;
switch (setType)
{
case 0:
expectedFailure = 0; // ApartmentState setter - no exception, but value does not change
break;
case 1:
expectedFailure = 3; // SetApartmentState - InvalidOperationException
break;
default:
expectedFailure = 2; // TrySetApartmentState - returns false
break;
}
Assert.Equal(expectedFailure, setApartmentState(t, ApartmentState.STA));
Assert.Equal(expectedFailure, setApartmentState(t, ApartmentState.MTA));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void CurrentCultureTest_SkipOnDesktopFramework()
{
// Cannot access culture properties on a thread object from a different thread
var t = new Thread(() => { });
Assert.Throws<InvalidOperationException>(() => t.CurrentCulture);
Assert.Throws<InvalidOperationException>(() => t.CurrentUICulture);
}
[Fact]
public static void CurrentCultureTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var t = Thread.CurrentThread;
var originalCulture = CultureInfo.CurrentCulture;
var originalUICulture = CultureInfo.CurrentUICulture;
var otherCulture = CultureInfo.InvariantCulture;
// Culture properties return the same value as those on CultureInfo
Assert.Equal(originalCulture, t.CurrentCulture);
Assert.Equal(originalUICulture, t.CurrentUICulture);
try
{
// Changing culture properties on CultureInfo causes the values of properties on the current thread to change
CultureInfo.CurrentCulture = otherCulture;
CultureInfo.CurrentUICulture = otherCulture;
Assert.Equal(otherCulture, t.CurrentCulture);
Assert.Equal(otherCulture, t.CurrentUICulture);
// Changing culture properties on the current thread causes new values to be returned, and causes the values of
// properties on CultureInfo to change
t.CurrentCulture = originalCulture;
t.CurrentUICulture = originalUICulture;
Assert.Equal(originalCulture, t.CurrentCulture);
Assert.Equal(originalUICulture, t.CurrentUICulture);
Assert.Equal(originalCulture, CultureInfo.CurrentCulture);
Assert.Equal(originalUICulture, CultureInfo.CurrentUICulture);
}
finally
{
CultureInfo.CurrentCulture = originalCulture;
CultureInfo.CurrentUICulture = originalUICulture;
}
Assert.Throws<ArgumentNullException>(() => t.CurrentCulture = null);
Assert.Throws<ArgumentNullException>(() => t.CurrentUICulture = null);
});
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void CurrentPrincipalTest_SkipOnDesktopFramework()
{
ThreadTestHelpers.RunTestInBackgroundThread(() => Assert.Null(Thread.CurrentPrincipal));
}
[Fact]
public static void CurrentPrincipalTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var originalPrincipal = Thread.CurrentPrincipal;
var otherPrincipal =
new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[] { string.Empty });
Thread.CurrentPrincipal = otherPrincipal;
Assert.Equal(otherPrincipal, Thread.CurrentPrincipal);
Thread.CurrentPrincipal = originalPrincipal;
Assert.Equal(originalPrincipal, Thread.CurrentPrincipal);
});
}
[Fact]
public static void CurrentThreadTest()
{
Thread otherThread = null;
var t = new Thread(() => otherThread = Thread.CurrentThread);
t.IsBackground = true;
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.Equal(t, otherThread);
var mainThread = Thread.CurrentThread;
Assert.NotNull(mainThread);
Assert.NotEqual(mainThread, otherThread);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void ExecutionContextTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(
() => Assert.Equal(ExecutionContext.Capture(), Thread.CurrentThread.ExecutionContext));
}
[Fact]
public static void IsAliveTest()
{
var isAliveWhenRunning = false;
Thread t = null;
t = new Thread(() => isAliveWhenRunning = t.IsAlive);
t.IsBackground = true;
Assert.False(t.IsAlive);
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.True(isAliveWhenRunning);
Assert.False(t.IsAlive);
}
[Fact]
public static void IsBackgroundTest()
{
var t = new Thread(() => { });
Assert.False(t.IsBackground);
t.IsBackground = true;
Assert.True(t.IsBackground);
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
// Cannot use this property after the thread is dead
Assert.Throws<ThreadStateException>(() => t.IsBackground);
Assert.Throws<ThreadStateException>(() => t.IsBackground = false);
Assert.Throws<ThreadStateException>(() => t.IsBackground = true);
// Verify that the test process can shut down gracefully with a hung background thread
t = new Thread(() => Thread.Sleep(Timeout.Infinite));
t.IsBackground = true;
t.Start();
}
[Fact]
public static void IsThreadPoolThreadTest()
{
var isThreadPoolThread = false;
Thread t = null;
t = new Thread(() => { isThreadPoolThread = t.IsThreadPoolThread; });
t.IsBackground = true;
Assert.False(t.IsThreadPoolThread);
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.False(isThreadPoolThread);
var e = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(
state =>
{
isThreadPoolThread = Thread.CurrentThread.IsThreadPoolThread;
e.Set();
});
e.CheckedWait();
Assert.True(isThreadPoolThread);
}
[Fact]
public static void ManagedThreadIdTest()
{
var e = new ManualResetEvent(false);
Action waitForThread;
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
t.IsBackground = true;
t.Start();
Assert.NotEqual(Thread.CurrentThread.ManagedThreadId, t.ManagedThreadId);
e.Set();
waitForThread();
}
[Fact]
public static void NameTest()
{
var t = new Thread(() => { });
Assert.Null(t.Name);
t.Name = "a";
Assert.Equal("a", t.Name);
Assert.Throws<InvalidOperationException>(() => t.Name = "b");
Assert.Equal("a", t.Name);
}
[Fact]
public static void PriorityTest()
{
var e = new ManualResetEvent(false);
Action waitForThread;
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
t.IsBackground = true;
Assert.Equal(ThreadPriority.Normal, t.Priority);
t.Priority = ThreadPriority.AboveNormal;
Assert.Equal(ThreadPriority.AboveNormal, t.Priority);
t.Start();
Assert.Equal(ThreadPriority.AboveNormal, t.Priority);
t.Priority = ThreadPriority.Normal;
Assert.Equal(ThreadPriority.Normal, t.Priority);
e.Set();
waitForThread();
}
[Fact]
[ActiveIssue(20766, TargetFrameworkMonikers.UapAot)]
public static void ThreadStateTest()
{
var e0 = new ManualResetEvent(false);
var e1 = new AutoResetEvent(false);
Action waitForThread;
var t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
e0.CheckedWait();
ThreadTestHelpers.WaitForConditionWithoutBlocking(() => e1.WaitOne(0));
});
Assert.Equal(ThreadState.Unstarted, t.ThreadState);
t.IsBackground = true;
Assert.Equal(ThreadState.Unstarted | ThreadState.Background, t.ThreadState);
t.Start();
ThreadTestHelpers.WaitForCondition(() => t.ThreadState == (ThreadState.WaitSleepJoin | ThreadState.Background));
e0.Set();
ThreadTestHelpers.WaitForCondition(() => t.ThreadState == (ThreadState.Running | ThreadState.Background));
e1.Set();
waitForThread();
Assert.Equal(ThreadState.Stopped, t.ThreadState);
t = ThreadTestHelpers.CreateGuardedThread(
out waitForThread,
() => ThreadTestHelpers.WaitForConditionWithoutBlocking(() => e1.WaitOne(0)));
t.Start();
ThreadTestHelpers.WaitForCondition(() => t.ThreadState == ThreadState.Running);
e1.Set();
waitForThread();
Assert.Equal(ThreadState.Stopped, t.ThreadState);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void AbortSuspendTest()
{
var e = new ManualResetEvent(false);
Action waitForThread;
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
t.IsBackground = true;
Action verify = () =>
{
Assert.Throws<PlatformNotSupportedException>(() => t.Abort());
Assert.Throws<PlatformNotSupportedException>(() => t.Abort(t));
#pragma warning disable 618 // Obsolete members
Assert.Throws<PlatformNotSupportedException>(() => t.Suspend());
Assert.Throws<PlatformNotSupportedException>(() => t.Resume());
#pragma warning restore 618 // Obsolete members
};
verify();
t.Start();
verify();
e.Set();
waitForThread();
Assert.Throws<PlatformNotSupportedException>(() => Thread.ResetAbort());
}
private static void VerifyLocalDataSlot(LocalDataStoreSlot slot)
{
Assert.NotNull(slot);
var waitForThreadArray = new Action[2];
var threadArray = new Thread[2];
var barrier = new Barrier(threadArray.Length);
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
Func<bool> barrierSignalAndWait =
() =>
{
try
{
Assert.True(barrier.SignalAndWait(UnexpectedTimeoutMilliseconds, cancellationToken));
}
catch (OperationCanceledException)
{
return false;
}
return true;
};
Action<int> threadMain =
threadIndex =>
{
try
{
Assert.Null(Thread.GetData(slot));
if (!barrierSignalAndWait())
{
return;
}
if (threadIndex == 0)
{
Thread.SetData(slot, threadIndex);
}
if (!barrierSignalAndWait())
{
return;
}
if (threadIndex == 0)
{
Assert.Equal(threadIndex, Thread.GetData(slot));
}
else
{
Assert.Null(Thread.GetData(slot));
}
if (!barrierSignalAndWait())
{
return;
}
if (threadIndex != 0)
{
Thread.SetData(slot, threadIndex);
}
if (!barrierSignalAndWait())
{
return;
}
Assert.Equal(threadIndex, Thread.GetData(slot));
if (!barrierSignalAndWait())
{
return;
}
}
catch (Exception ex)
{
cancellationTokenSource.Cancel();
throw new TargetInvocationException(ex);
}
};
for (int i = 0; i < threadArray.Length; ++i)
{
threadArray[i] = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i], () => threadMain(i));
threadArray[i].IsBackground = true;
threadArray[i].Start();
}
foreach (var waitForThread in waitForThreadArray)
{
waitForThread();
}
}
[Fact]
public static void LocalDataSlotTest()
{
var slot = Thread.AllocateDataSlot();
var slot2 = Thread.AllocateDataSlot();
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
var slotName = "System.Threading.Threads.Tests.LocalDataSlotTest";
var slotName2 = slotName + ".2";
var invalidSlotName = slotName + ".Invalid";
try
{
// AllocateNamedDataSlot allocates
slot = Thread.AllocateNamedDataSlot(slotName);
Assert.Throws<ArgumentException>(() => Thread.AllocateNamedDataSlot(slotName));
slot2 = Thread.AllocateNamedDataSlot(slotName2);
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
// Free the same slot twice, should be fine
Thread.FreeNamedDataSlot(slotName2);
Thread.FreeNamedDataSlot(slotName2);
}
catch (Exception ex)
{
Thread.FreeNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName2);
throw new TargetInvocationException(ex);
}
try
{
// GetNamedDataSlot gets or allocates
var tempSlot = Thread.GetNamedDataSlot(slotName);
Assert.Equal(slot, tempSlot);
tempSlot = Thread.GetNamedDataSlot(slotName2);
Assert.NotEqual(slot2, tempSlot);
slot2 = tempSlot;
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
}
finally
{
Thread.FreeNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName2);
}
try
{
// A named slot can be used after the name is freed, since only the name is freed, not the slot
slot = Thread.AllocateNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName);
slot2 = Thread.AllocateNamedDataSlot(slotName); // same name
Thread.FreeNamedDataSlot(slotName);
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
}
finally
{
Thread.FreeNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName2);
}
}
[Fact]
[ActiveIssue(20766, TargetFrameworkMonikers.UapAot)]
public static void InterruptTest()
{
// Interrupting a thread that is not blocked does not do anything, but once the thread starts blocking, it gets
// interrupted and does not auto-reset the signaled event
var threadReady = new AutoResetEvent(false);
var continueThread = new AutoResetEvent(false);
bool continueThreadBool = false;
Action waitForThread;
var t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
threadReady.Set();
ThreadTestHelpers.WaitForConditionWithoutBlocking(() => Volatile.Read(ref continueThreadBool));
threadReady.Set();
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait());
});
t.IsBackground = true;
t.Start();
threadReady.CheckedWait();
continueThread.Set();
t.Interrupt();
Assert.False(threadReady.WaitOne(ExpectedTimeoutMilliseconds));
Volatile.Write(ref continueThreadBool, true);
waitForThread();
Assert.True(continueThread.WaitOne(0));
// Interrupting a dead thread does nothing
t.Interrupt();
// Interrupting an unstarted thread causes the thread to be interrupted after it is started and starts blocking
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()));
t.IsBackground = true;
t.Interrupt();
t.Start();
waitForThread();
// A thread that is already blocked on a synchronization primitive unblocks immediately
continueThread.Reset();
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()));
t.IsBackground = true;
t.Start();
ThreadTestHelpers.WaitForCondition(() => (t.ThreadState & ThreadState.WaitSleepJoin) != 0);
t.Interrupt();
waitForThread();
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[ActiveIssue(20766,TargetFrameworkMonikers.UapAot)]
public static void InterruptInFinallyBlockTest_SkipOnDesktopFramework()
{
// A wait in a finally block can be interrupted. The desktop framework applies the same rules as thread abort, and
// does not allow thread interrupt in a finally block. There is nothing special about thread interrupt that requires
// not allowing it in finally blocks, so this behavior has changed in .NET Core.
var continueThread = new AutoResetEvent(false);
Action waitForThread;
Thread t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
try
{
}
finally
{
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait());
}
});
t.IsBackground = true;
t.Start();
t.Interrupt();
waitForThread();
}
[Fact]
public static void JoinTest()
{
var threadReady = new ManualResetEvent(false);
var continueThread = new ManualResetEvent(false);
Action waitForThread;
var t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
threadReady.Set();
continueThread.CheckedWait();
Thread.Sleep(ExpectedTimeoutMilliseconds);
});
t.IsBackground = true;
Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(TimeSpan.FromMilliseconds(-2)));
Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(TimeSpan.FromMilliseconds((double)int.MaxValue + 1)));
Assert.Throws<ThreadStateException>(() => t.Join());
Assert.Throws<ThreadStateException>(() => t.Join(UnexpectedTimeoutMilliseconds));
Assert.Throws<ThreadStateException>(() => t.Join(TimeSpan.FromMilliseconds(UnexpectedTimeoutMilliseconds)));
t.Start();
threadReady.CheckedWait();
Assert.False(t.Join(ExpectedTimeoutMilliseconds));
Assert.False(t.Join(TimeSpan.FromMilliseconds(ExpectedTimeoutMilliseconds)));
continueThread.Set();
waitForThread();
Assert.True(t.Join(0));
Assert.True(t.Join(TimeSpan.Zero));
}
[Fact]
public static void SleepTest()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(TimeSpan.FromMilliseconds(-2)));
Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(TimeSpan.FromMilliseconds((double)int.MaxValue + 1)));
Thread.Sleep(0);
var stopwatch = Stopwatch.StartNew();
Thread.Sleep(500);
stopwatch.Stop();
Assert.InRange((int)stopwatch.ElapsedMilliseconds, 100, int.MaxValue);
}
[Fact]
public static void StartTest()
{
var e = new AutoResetEvent(false);
Action waitForThread;
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
t.IsBackground = true;
Assert.Throws<InvalidOperationException>(() => t.Start(null));
Assert.Throws<InvalidOperationException>(() => t.Start(t));
t.Start();
Assert.Throws<ThreadStateException>(() => t.Start());
e.Set();
waitForThread();
Assert.Throws<ThreadStateException>(() => t.Start());
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => e.CheckedWait());
t.IsBackground = true;
t.Start();
Assert.Throws<ThreadStateException>(() => t.Start());
Assert.Throws<ThreadStateException>(() => t.Start(null));
Assert.Throws<ThreadStateException>(() => t.Start(t));
e.Set();
waitForThread();
Assert.Throws<ThreadStateException>(() => t.Start());
Assert.Throws<ThreadStateException>(() => t.Start(null));
Assert.Throws<ThreadStateException>(() => t.Start(t));
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => Assert.Null(parameter));
t.IsBackground = true;
t.Start();
waitForThread();
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => Assert.Null(parameter));
t.IsBackground = true;
t.Start(null);
waitForThread();
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => Assert.Equal(t, parameter));
t.IsBackground = true;
t.Start(t);
waitForThread();
}
[Fact]
[ActiveIssue(20766,TargetFrameworkMonikers.UapAot)]
public static void MiscellaneousTest()
{
Thread.BeginCriticalRegion();
Thread.EndCriticalRegion();
Thread.BeginThreadAffinity();
Thread.EndThreadAffinity();
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
// TODO: Port tests for these once all of the necessary interop APIs are available
Thread.CurrentThread.DisableComObjectEagerCleanup();
Marshal.CleanupUnusedObjectsInCurrentContext();
});
#pragma warning disable 618 // obsolete members
Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.GetCompressedStack());
Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetCompressedStack(CompressedStack.Capture()));
#pragma warning restore 618 // obsolete members
Thread.MemoryBarrier();
var ad = Thread.GetDomain();
Assert.NotNull(ad);
Assert.Equal(AppDomain.CurrentDomain, ad);
Assert.Equal(ad.Id, Thread.GetDomainID());
Thread.SpinWait(int.MinValue);
Thread.SpinWait(-1);
Thread.SpinWait(0);
Thread.SpinWait(1);
Thread.Yield();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Lucene.Net.Store
{
/// <summary> <p>Implements {@link LockFactory} using {@link
/// File#createNewFile()}. This is the default LockFactory
/// for {@link FSDirectory}.</p>
///
/// <p><b>NOTE:</b> the <a target="_top"
/// href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#createNewFile()">javadocs
/// for <code>File.createNewFile</code></a> contain a vague
/// yet spooky warning about not using the API for file
/// locking. This warning was added due to <a target="_top"
/// href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4676183">this
/// bug</a>, and in fact the only known problem with using
/// this API for locking is that the Lucene write lock may
/// not be released when the JVM exits abnormally.</p>
/// <p>When this happens, a {@link LockObtainFailedException}
/// is hit when trying to create a writer, in which case you
/// need to explicitly clear the lock file first. You can
/// either manually remove the file, or use the {@link
/// Lucene.Net.Index.IndexReader#Unlock(Directory)}
/// API. But, first be certain that no writer is in fact
/// writing to the index otherwise you can easily corrupt
/// your index.</p>
///
/// <p>If you suspect that this or any other LockFactory is
/// not working properly in your environment, you can easily
/// test it by using {@link VerifyingLockFactory}, {@link
/// LockVerifyServer} and {@link LockStressTest}.</p>
///
/// </summary>
/// <seealso cref="LockFactory">
/// </seealso>
public class SimpleFSLockFactory : LockFactory
{
/// <summary> Directory specified by <code>Lucene.Net.lockDir</code>
/// system property. If that is not set, then <code>java.io.tmpdir</code>
/// system property is used.
/// </summary>
private System.IO.FileInfo lockDir;
/// <summary> Create a SimpleFSLockFactory instance, with null (unset)
/// lock directory. This is package-private and is only
/// used by FSDirectory when creating this LockFactory via
/// the System property
/// Lucene.Net.Store.FSDirectoryLockFactoryClass.
/// </summary>
internal SimpleFSLockFactory() : this((System.IO.FileInfo) null)
{
}
/// <summary> Instantiate using the provided directory (as a File instance).</summary>
/// <param name="lockDir">where lock files should be created.
/// </param>
public SimpleFSLockFactory(System.IO.FileInfo lockDir)
{
SetLockDir(lockDir);
}
/// <summary> Instantiate using the provided directory name (String).</summary>
/// <param name="lockDirName">where lock files should be created.
/// </param>
public SimpleFSLockFactory(System.String lockDirName)
{
lockDir = new System.IO.FileInfo(lockDirName);
SetLockDir(lockDir);
}
/// <summary> Set the lock directory. This is package-private and is
/// only used externally by FSDirectory when creating this
/// LockFactory via the System property
/// Lucene.Net.Store.FSDirectoryLockFactoryClass.
/// </summary>
internal virtual void SetLockDir(System.IO.FileInfo lockDir)
{
this.lockDir = lockDir;
}
public override Lock MakeLock(System.String lockName)
{
if (lockPrefix != null)
{
lockName = lockPrefix + "-" + lockName;
}
return new SimpleFSLock(lockDir, lockName);
}
public override void ClearLock(System.String lockName)
{
bool tmpBool;
if (System.IO.File.Exists(lockDir.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(lockDir.FullName);
if (tmpBool)
{
if (lockPrefix != null)
{
lockName = lockPrefix + "-" + lockName;
}
System.IO.FileInfo lockFile = new System.IO.FileInfo(System.IO.Path.Combine(lockDir.FullName, lockName));
bool tmpBool2;
if (System.IO.File.Exists(lockFile.FullName))
tmpBool2 = true;
else
tmpBool2 = System.IO.Directory.Exists(lockFile.FullName);
bool tmpBool3;
if (System.IO.File.Exists(lockFile.FullName))
{
System.IO.File.Delete(lockFile.FullName);
tmpBool3 = true;
}
else if (System.IO.Directory.Exists(lockFile.FullName))
{
System.IO.Directory.Delete(lockFile.FullName);
tmpBool3 = true;
}
else
tmpBool3 = false;
if (tmpBool2 && !tmpBool3)
{
throw new System.IO.IOException("Cannot delete " + lockFile);
}
}
}
}
class SimpleFSLock : Lock
{
internal System.IO.FileInfo lockFile;
internal System.IO.FileInfo lockDir;
public SimpleFSLock(System.IO.FileInfo lockDir, System.String lockFileName)
{
this.lockDir = lockDir;
lockFile = new System.IO.FileInfo(System.IO.Path.Combine(lockDir.FullName, lockFileName));
}
public override bool Obtain()
{
// Ensure that lockDir exists and is a directory:
bool tmpBool;
if (System.IO.File.Exists(lockDir.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(lockDir.FullName);
if (!tmpBool)
{
try
{
System.IO.Directory.CreateDirectory(lockDir.FullName);
}
catch
{
throw new System.IO.IOException("Cannot create directory: " + lockDir.FullName);
}
}
else
{
try
{
System.IO.Directory.Exists(lockDir.FullName);
}
catch
{
throw new System.IO.IOException("Found regular file where directory expected: " + lockDir.FullName);
}
}
try
{
System.IO.FileStream createdFile = new System.IO.FileStream(lockFile.FullName, System.IO.FileMode.CreateNew);
createdFile.Close();
return true;
}
catch
{
return false;
}
}
public override void Release()
{
bool tmpBool;
if (System.IO.File.Exists(lockFile.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(lockFile.FullName);
bool tmpBool2;
if (System.IO.File.Exists(lockFile.FullName))
{
System.IO.File.Delete(lockFile.FullName);
tmpBool2 = true;
}
else if (System.IO.Directory.Exists(lockFile.FullName))
{
System.IO.Directory.Delete(lockFile.FullName);
tmpBool2 = true;
}
else
tmpBool2 = false;
if (tmpBool && !tmpBool2)
throw new LockReleaseFailedException("failed to delete " + lockFile);
}
public override bool IsLocked()
{
bool tmpBool;
if (System.IO.File.Exists(lockFile.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(lockFile.FullName);
return tmpBool;
}
public override System.String ToString()
{
return "SimpleFSLock@" + lockFile;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Xml;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
internal class PSClassHelpProvider : HelpProviderWithCache
{
/// <summary>
/// Constructor for PSClassHelpProvider
/// </summary>
internal PSClassHelpProvider(HelpSystem helpSystem)
: base(helpSystem)
{
_context = helpSystem.ExecutionContext;
}
/// <summary>
/// Execution context of the HelpSystem
/// </summary>
private readonly ExecutionContext _context;
/// <summary>
/// This is a hashtable to track which help files are loaded already.
///
/// This will avoid one help file getting loaded again and again.
///
/// </summary>
private readonly Hashtable _helpFiles = new Hashtable();
[TraceSource("PSClassHelpProvider", "PSClassHelpProvider")]
private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("PSClassHelpProvider", "PSClassHelpProvider");
#region common properties
/// <summary>
/// Name of the Help Provider.
/// </summary>
internal override string Name
{
get { return "Powershell Class Help Provider"; }
}
/// <summary>
/// Supported Help Categories
/// </summary>
internal override HelpCategory HelpCategory
{
get { return Automation.HelpCategory.Class; }
}
#endregion
/// <summary>
/// Override SearchHelp to find a class module with help matching a pattern.
/// </summary>
/// <param name="helpRequest">Help request.</param>
/// <param name="searchOnlyContent">Not used.</param>
/// <returns></returns>
internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
{
Debug.Assert(helpRequest != null, "helpRequest cannot be null.");
string target = helpRequest.Target;
Collection<string> patternList = new Collection<string>();
bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target);
if (decoratedSearch)
{
patternList.Add("*" + target + "*");
}
else
patternList.Add(target);
bool useWildCards = true;
foreach (string pattern in patternList)
{
PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards, _context);
foreach (var helpInfo in GetHelpInfo(searcher))
{
if (helpInfo != null)
yield return helpInfo;
}
}
}
/// <summary>
/// Override ExactMatchHelp to find the matching class module matching help request.
/// </summary>
/// <param name="helpRequest">Help Request for the search.</param>
/// <returns>Enumerable of HelpInfo objects.</returns>
internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest)
{
Debug.Assert(helpRequest != null, "helpRequest cannot be null.");
if ((helpRequest.HelpCategory & Automation.HelpCategory.Class) == 0)
{
yield return null;
}
string target = helpRequest.Target;
bool useWildCards = false;
PSClassSearcher searcher = new PSClassSearcher(target, useWildCards, _context);
foreach (var helpInfo in GetHelpInfo(searcher))
{
if (helpInfo != null)
{
yield return helpInfo;
}
}
}
/// <summary>
/// Get the help in for the PS Class Info. ///
/// </summary>
/// <param name="searcher">Searcher for PS Classes.</param>
/// <returns>Next HelpInfo object.</returns>
private IEnumerable<HelpInfo> GetHelpInfo(PSClassSearcher searcher)
{
while (searcher.MoveNext())
{
PSClassInfo current = ((IEnumerator<PSClassInfo>)searcher).Current;
string moduleName = current.Module.Name;
string moduleDir = current.Module.ModuleBase;
if (!String.IsNullOrEmpty(moduleName) && !String.IsNullOrEmpty(moduleDir))
{
string helpFileToFind = moduleName + "-Help.xml";
string helpFileName = null;
Collection<string> searchPaths = new Collection<string>();
searchPaths.Add(moduleDir);
string externalHelpFile = current.HelpFile;
if (!String.IsNullOrEmpty(externalHelpFile))
{
FileInfo helpFileInfo = new FileInfo(externalHelpFile);
DirectoryInfo dirToSearch = helpFileInfo.Directory;
if (dirToSearch.Exists)
{
searchPaths.Add(dirToSearch.FullName);
helpFileToFind = helpFileInfo.Name; //If external help file is specified. Then use it.
}
}
HelpInfo helpInfo = GetHelpInfoFromHelpFile(current, helpFileToFind, searchPaths, true, out helpFileName);
if (helpInfo != null)
{
yield return helpInfo;
}
}
}
}
/// <summary>
/// Check whether a HelpItems node indicates that the help content is
/// authored using maml schema.
///
/// This covers two cases:
/// a. If the help file has an extension .maml.
/// b. If HelpItems node (which should be the top node of any command help file)
/// has an attribute "schema" with value "maml", its content is in maml
/// schema
///
/// </summary>
/// <param name="helpFile">File name.</param>
/// <param name="helpItemsNode">Nodes to check.</param>
/// <returns></returns>
internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode)
{
Debug.Assert(!String.IsNullOrEmpty(helpFile), "helpFile cannot be null.");
if (helpFile.EndsWith(".maml", StringComparison.CurrentCultureIgnoreCase))
return true;
if (helpItemsNode.Attributes == null)
return false;
foreach (XmlNode attribute in helpItemsNode.Attributes)
{
if (attribute.Name.Equals("schema", StringComparison.OrdinalIgnoreCase)
&& attribute.Value.Equals("maml", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
#region private methods
private HelpInfo GetHelpInfoFromHelpFile(PSClassInfo classInfo, string helpFileToFind, Collection<string> searchPaths, bool reportErrors, out string helpFile)
{
Dbg.Assert(classInfo != null, "Caller should verify that classInfo != null");
Dbg.Assert(helpFileToFind != null, "Caller should verify that helpFileToFind != null");
helpFile = MUIFileSearcher.LocateFile(helpFileToFind, searchPaths);
if (!File.Exists(helpFile))
return null;
if (!String.IsNullOrEmpty(helpFile))
{
//Load the help file only once. Then use it from the cache.
if (!_helpFiles.Contains(helpFile))
{
LoadHelpFile(helpFile, helpFile, classInfo.Name, reportErrors);
}
return GetFromPSClassHelpCache(helpFile, Automation.HelpCategory.Class);
}
return null;
}
/// <summary>
/// Gets the HelpInfo object corresponding to the command.
/// </summary>
/// <param name="helpFileIdentifier">help file identifier (either name of PSSnapIn or simply full path to help file)</param>
/// <param name="helpCategory">Help Category for search.</param>
/// <returns>HelpInfo object.</returns>
private HelpInfo GetFromPSClassHelpCache(string helpFileIdentifier, HelpCategory helpCategory)
{
Debug.Assert(!string.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier should not be null or empty.");
HelpInfo result = GetCache(helpFileIdentifier);
if (result != null)
{
MamlClassHelpInfo original = (MamlClassHelpInfo)result;
result = original.Copy(helpCategory);
}
return result;
}
private void LoadHelpFile(string helpFile, string helpFileIdentifier, string commandName, bool reportErrors)
{
Exception e = null;
try
{
LoadHelpFile(helpFile, helpFileIdentifier);
}
catch (IOException ioException)
{
e = ioException;
}
catch (System.Security.SecurityException securityException)
{
e = securityException;
}
catch (XmlException xmlException)
{
e = xmlException;
}
catch (NotSupportedException notSupportedException)
{
e = notSupportedException;
}
catch (UnauthorizedAccessException unauthorizedAccessException)
{
e = unauthorizedAccessException;
}
catch (InvalidOperationException invalidOperationException)
{
e = invalidOperationException;
}
if (e != null)
s_tracer.WriteLine("Error occured in PSClassHelpProvider {0}", e.Message);
if (reportErrors && (e != null))
{
ReportHelpFileError(e, commandName, helpFile);
}
}
/// <summary>
/// Load help file for HelpInfo objects. The HelpInfo objects will be
/// put into help cache.
/// </summary>
/// <remarks>
/// 1. Needs to pay special attention about error handling in this function.
/// Common errors include: file not found and invalid xml. None of these error
/// should cause help search to stop.
/// 2. a helpfile cache is used to avoid same file got loaded again and again.
/// </remarks>
private void LoadHelpFile(string helpFile, string helpFileIdentifier)
{
Dbg.Assert(!String.IsNullOrEmpty(helpFile), "HelpFile cannot be null or empty.");
Dbg.Assert(!String.IsNullOrEmpty(helpFileIdentifier), "helpFileIdentifier cannot be null or empty.");
XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
new FileInfo(helpFile),
false, /* ignore whitespace, comments, etc. */
null); /* default maxCharactersInDocument */
// Add this file into _helpFiles hashtable to prevent it to be loaded again.
_helpFiles[helpFile] = 0;
XmlNode helpItemsNode = null;
if (doc.HasChildNodes)
{
for (int i = 0; i < doc.ChildNodes.Count; i++)
{
XmlNode node = doc.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && String.Compare(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase) == 0)
{
helpItemsNode = node;
break;
}
}
}
if (helpItemsNode == null)
{
s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile);
return;
}
bool isMaml = IsMamlHelp(helpFile, helpItemsNode);
using (this.HelpSystem.Trace(helpFile))
{
if (helpItemsNode.HasChildNodes)
{
for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++)
{
XmlNode node = helpItemsNode.ChildNodes[i];
string nodeLocalName = node.LocalName;
bool isClass = (String.Compare(nodeLocalName, "class", StringComparison.OrdinalIgnoreCase) == 0);
if (node.NodeType == XmlNodeType.Element && isClass)
{
MamlClassHelpInfo helpInfo = null;
if (isMaml)
{
if (isClass)
helpInfo = MamlClassHelpInfo.Load(node, HelpCategory.Class);
}
if (helpInfo != null)
{
this.HelpSystem.TraceErrors(helpInfo.Errors);
AddCache(helpFileIdentifier, helpInfo);
}
}
}
}
}
}
#endregion
}
}
| |
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using WWT.Tours;
/// <summary>
/// Summary description for WWTWebService
/// </summary>
namespace WWTWebservices
{
[WebService(Namespace = "http://research.microsoft.com/WWT/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WWTWebService : System.Web.Services.WebService {
public enum FaultCode
{
Client = 0,
Server = 1
}
public WWTWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
public static SoapException RaiseException(string uri,
string webServiceNamespace,
string errorMessage,
string errorNumber,
string errorSource,
FaultCode code)
{
XmlQualifiedName faultCodeLocation = null;
//Identify the location of the FaultCode
switch (code)
{
case FaultCode.Client:
faultCodeLocation = SoapException.ClientFaultCode;
break;
case FaultCode.Server:
faultCodeLocation = SoapException.ServerFaultCode;
break;
}
XmlDocument xmlDoc = new XmlDocument();
//Create the Detail node
XmlNode rootNode = xmlDoc.CreateNode(XmlNodeType.Element,
SoapException.DetailElementName.Name,
SoapException.DetailElementName.Namespace);
//Build specific details for the SoapException
//Add first child of detail XML element.
XmlNode errorNode = xmlDoc.CreateNode(XmlNodeType.Element, "Error",
webServiceNamespace);
//Create and set the value for the ErrorNumber node
XmlNode errorNumberNode =
xmlDoc.CreateNode(XmlNodeType.Element, "ErrorNumber",
webServiceNamespace);
errorNumberNode.InnerText = errorNumber;
//Create and set the value for the ErrorMessage node
XmlNode errorMessageNode = xmlDoc.CreateNode(XmlNodeType.Element,
"ErrorMessage",
webServiceNamespace);
errorMessageNode.InnerText = errorMessage;
//Create and set the value for the ErrorSource node
XmlNode errorSourceNode =
xmlDoc.CreateNode(XmlNodeType.Element, "ErrorSource",
webServiceNamespace);
errorSourceNode.InnerText = errorSource;
//Append the Error child element nodes to the root detail node.
errorNode.AppendChild(errorNumberNode);
errorNode.AppendChild(errorMessageNode);
errorNode.AppendChild(errorSourceNode);
//Append the Detail node to the root node
rootNode.AppendChild(errorNode);
//Construct the exception
SoapException soapEx = new SoapException(errorMessage,
faultCodeLocation, uri,
rootNode);
//Raise the exception back to the caller
return soapEx;
}
[WebMethod (CacheDuration = 120)]
public AstroObjectsDataset GetAstroObjectsByRaDec(float Ra, float Dec, float PlusMinusArcSecs)
{
AstroObjectServices.AstroObjectDataByRaDec x2 = new AstroObjectServices.AstroObjectDataByRaDec(Ra, Dec, PlusMinusArcSecs);
AstroObjectsDataset dsAstroObjectData = x2.dsAstroObjectData;
return dsAstroObjectData;
}
[WebMethod(CacheDuration = 120)]
public AstroObjectsDataset GetAstroObjectsByName(string AstroObjectName)
{
AstroObjectServices.AstroObjectByName x1 = new AstroObjectServices.AstroObjectByName(AstroObjectName);
AstroObjectsDataset dsAstroObjectData = x1.dsAstroObjectData;
return dsAstroObjectData;
}
[WebMethod(CacheDuration = 120)]
public AstroObjectsDataset GetAstroObjectsInCatalog(string CatalogName)
{
AstroObjectServices.AstroObjectDataInCatalog x3 = new AstroObjectServices.AstroObjectDataInCatalog(CatalogName);
AstroObjectsDataset dsAstroObjectData = x3.dsAstroObjectData;
return dsAstroObjectData;
}
[WebMethod]
[System.Xml.Serialization.XmlInclude(typeof(Tour))]
public List<Tour> ImportTour(string TourXML, byte[] TourBlob, byte[] TourThumbnail, byte[] AuthorThumbnail)
{
TourServices.WWTTour x4 = new TourServices.WWTTour(TourXML, TourBlob, TourThumbnail, AuthorThumbnail);
List<Tour> dsWWTTourData = x4.dsTourFromCache;
return dsWWTTourData;
}
[WebMethod]
[System.Xml.Serialization.XmlInclude(typeof(Tour))]
public List<Tour> UpdateTourWorkFlowStatus(string TourGUID, char WorkFlowStatusCode, string ApprovedRejectedByName)
{
TourServices.WWTTourUpdtStatus x4 = new TourServices.WWTTourUpdtStatus(TourGUID, WorkFlowStatusCode, ApprovedRejectedByName);
List<Tour> dsWWTTourData = x4.dsTourFromCache;
return dsWWTTourData;
}
[WebMethod]
[System.Xml.Serialization.XmlInclude(typeof(Tour))]
public List<Tour> InsertTourRatingOrComment(string UserGUID, string TourGUID, string Rating, string Comment, string UserSelfRatingID, string UserContactInfo, string ObjectionTypeID, string ObjectionComment)
{
int PassRating;
int PassUserSelfRatingID;
int PassObjectionTypeID;
try
{
PassRating = Convert.ToInt32(Rating);
}
catch
{
PassRating = -999;
}
try
{
PassUserSelfRatingID = Convert.ToInt32(UserSelfRatingID);
}
catch
{
PassUserSelfRatingID = -999;
}
try
{
PassObjectionTypeID = Convert.ToInt32(ObjectionTypeID);
}
catch
{
PassObjectionTypeID = -999;
}
TourServices.WWTTourInsertRatingOrComment x4 = new TourServices.WWTTourInsertRatingOrComment(UserGUID, TourGUID.ToUpper(), PassRating, Comment, PassUserSelfRatingID, UserContactInfo, PassObjectionTypeID, ObjectionComment);
List<Tour> dsWWTTourData = x4.dsTourFromCache;
return dsWWTTourData;
}
[WebMethod(CacheDuration = 120)]
[System.Xml.Serialization.XmlInclude(typeof(Tour))]
public List<Tour> GetToursForGUID(string TourGUID)
{
TourServices.WWTTourForGUID x4 = new TourServices.WWTTourForGUID(TourGUID);
List<Tour> dsWWTTourData = x4.dsTourFromCache;
return dsWWTTourData;
}
[WebMethod(CacheDuration = 120)]
[System.Xml.Serialization.XmlInclude(typeof(Tour))]
public List<Tour> GetToursForAuthor(string AuthorName)
{
TourServices.WWTTourForAuthor x4 = new TourServices.WWTTourForAuthor(AuthorName);
List<Tour> dsWWTTourData = x4.dsTourFromCache;
return dsWWTTourData;
}
[WebMethod(CacheDuration = 120)]
[System.Xml.Serialization.XmlInclude(typeof(Tour))]
public List<Tour> GetToursForKeyword(string Keyword)
{
TourServices.WWTTourForKeyword x4 = new TourServices.WWTTourForKeyword(Keyword);
List<Tour> dsWWTTourData = x4.dsTourFromCache;
return dsWWTTourData;
}
[WebMethod(CacheDuration = 120)]
[System.Xml.Serialization.XmlInclude(typeof(Tour))]
public List<Tour> GetToursForDateRange(string BeginDateTime, string EndDateTime)
{
TourServices.WWTTourForDateRange x4 = new TourServices.WWTTourForDateRange(BeginDateTime, EndDateTime);
List<Tour> dsWWTTourData = x4.dsTourFromCache;
return dsWWTTourData;
}
}
}
| |
namespace AdMaiora.Bugghy
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using AdMaiora.AppKit.UI;
using AdMaiora.Bugghy.Api;
using AdMaiora.Bugghy.Model;
#pragma warning disable CS4014
public class GimmicksFragment : AdMaiora.AppKit.UI.App.Fragment
{
#region Inner Classes
class GimmickAdapter : ItemRecyclerAdapter<GimmickAdapter.ChatViewHolder, Gimmick>
{
#region Inner Classes
public class ChatViewHolder : ItemViewHolder
{
[Widget]
public ImageView ThumbImage;
[Widget]
public TextView NameLabel;
[Widget]
public TextView OwnerLabel;
public ChatViewHolder(View itemView)
: base(itemView)
{
}
}
#endregion
#region Costants and Fields
#endregion
#region Constructors
public GimmickAdapter(AdMaiora.AppKit.UI.App.Fragment context, IEnumerable<Gimmick> source)
: base(context, Resource.Layout.CellGimmick, source)
{
}
#endregion
#region Public Methods
public override void GetView(int postion, ChatViewHolder holder, View view, Gimmick item)
{
AppController.Images.SetImageForView(
new Uri(item.ImageUrl), "image_gear", holder.ThumbImage);
holder.NameLabel.Text = item.Name;
holder.OwnerLabel.Text = item.Owner;
}
public void Clear()
{
this.SourceItems.Clear();
}
public void Refresh(IEnumerable<Gimmick> items)
{
this.SourceItems.Clear();
this.SourceItems.AddRange(items);
}
#endregion
#region Methods
#endregion
}
#endregion
#region Constants and Fields
private GimmickAdapter _adapter;
private bool _signOut;
// This flag check if we are already calling the login REST service
private bool _isRefreshingGimmicks;
// This cancellation token is used to cancel the rest send message request
private CancellationTokenSource _cts0;
#endregion
#region Widgets
[Widget]
private ItemRecyclerView GimmickList;
#endregion
#region Constructors
public GimmicksFragment()
{
}
#endregion
#region Properties
#endregion
#region Fragment Methods
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override void OnCreateView(LayoutInflater inflater, ViewGroup container)
{
base.OnCreateView(inflater, container);
#region Desinger Stuff
SetContentView(Resource.Layout.FragmentGimmicks, inflater, container);
this.HasOptionsMenu = true;
#endregion
this.Title = "All Gimmicks";
this.ActionBar.Show();
_adapter = new GimmickAdapter(this, new Gimmick[0]);
this.GimmickList.SetAdapter(_adapter);
this.GimmickList.ItemSelected += GimmickList_ItemSelected;
RefreshGimmicks();
}
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
base.OnCreateOptionsMenu(menu, inflater);
menu.Clear();
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch(item.ItemId)
{
case Android.Resource.Id.Home:
Logout();
return true;
default:
return base.OnOptionsItemSelected(item);
}
}
public override bool OnBackButton()
{
Logout();
return true;
}
public override void OnDestroyView()
{
base.OnDestroyView();
if (_cts0 != null)
_cts0.Cancel();
this.GimmickList.ItemSelected -= GimmickList_ItemSelected;
}
#endregion
#region Public Methods
#endregion
#region Methods
private void RefreshGimmicks()
{
if (_isRefreshingGimmicks)
return;
this.GimmickList.Visibility = ViewStates.Gone;
_isRefreshingGimmicks = true;
((MainActivity)this.Activity).BlockUI();
Gimmick[] gimmicks = null;
_cts0 = new CancellationTokenSource();
AppController.RefreshGimmicks(_cts0,
(newGimmicks) =>
{
gimmicks = newGimmicks;
},
(error) =>
{
Toast.MakeText(this.Activity.ApplicationContext, error, ToastLength.Long).Show();
},
() =>
{
if (gimmicks != null)
{
LoadGimmicks(gimmicks);
if(_adapter?.ItemCount > 0)
this.GimmickList.Visibility = ViewStates.Visible;
_isRefreshingGimmicks = false;
((MainActivity)this.Activity).UnblockUI();
}
else
{
AppController.Utility.ExecuteOnAsyncTask(_cts0.Token,
() =>
{
gimmicks = AppController.GetGimmicks();
},
() =>
{
LoadGimmicks(gimmicks);
if (_adapter?.ItemCount > 0)
this.GimmickList.Visibility = ViewStates.Visible;
_isRefreshingGimmicks = false;
((MainActivity)this.Activity).UnblockUI();
});
}
});
}
private void LoadGimmicks(IEnumerable<Gimmick> gimmicks)
{
if (gimmicks == null)
return;
gimmicks = gimmicks
.OrderBy(x => x.Name)
.ToArray();
_adapter.Refresh(gimmicks);
this.GimmickList.ReloadData();
}
private void Logout()
{
(new AlertDialog.Builder(this.Activity))
.SetTitle("Do you want to logout now?")
.SetMessage("")
.SetPositiveButton("Yes please!",
(s, ea) =>
{
AppController.Settings.AuthAccessToken = null;
AppController.Settings.AuthExpirationDate = null;
this.DismissKeyboard();
this.FragmentManager.PopBackStack();
})
.SetNegativeButton("Not now",
(s, ea) =>
{
})
.Show();
}
#endregion
#region Event Handlers
private void GimmickList_ItemSelected(object sender, ItemListSelectEventArgs e)
{
Gimmick gimmick = e.Item as Gimmick;
var f = new GimmickFragment();
f.Arguments = new Bundle();
f.Arguments.PutObject<Gimmick>("Gimmick", gimmick);
this.FragmentManager.BeginTransaction()
.AddToBackStack("BeforeGimmickFragment")
.Replace(Resource.Id.ContentLayout, f, "GimmickFragment")
.Commit();
}
#endregion
}
}
| |
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using System;
using System.Collections;
using System.Collections.Generic;
using TouchScript.Devices.Display;
using TouchScript.Hit;
using TouchScript.InputSources;
using TouchScript.Layers;
using TouchScript.Utils;
#if TOUCHSCRIPT_DEBUG
using TouchScript.Utils.Debug;
#endif
using UnityEngine;
namespace TouchScript
{
/// <summary>
/// Default implementation of <see cref="ITouchManager"/>.
/// </summary>
internal sealed class TouchManagerInstance : DebuggableMonoBehaviour, ITouchManager
{
#region Events
/// <inheritdoc />
public event EventHandler FrameStarted
{
add { frameStartedInvoker += value; }
remove { frameStartedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler FrameFinished
{
add { frameFinishedInvoker += value; }
remove { frameFinishedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchBegan
{
add { touchBeganInvoker += value; }
remove { touchBeganInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchMoved
{
add { touchMovedInvoker += value; }
remove { touchMovedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchEnded
{
add { touchEndedInvoker += value; }
remove { touchEndedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchCancelled
{
add { touchCancelledInvoker += value; }
remove { touchCancelledInvoker -= value; }
}
// Needed to overcome iOS AOT limitations
private EventHandler<TouchEventArgs> touchBeganInvoker,
touchMovedInvoker,
touchEndedInvoker,
touchCancelledInvoker;
private EventHandler frameStartedInvoker, frameFinishedInvoker;
#endregion
#region Public properties
/// <inheritdoc />
public static TouchManagerInstance Instance
{
get
{
if (shuttingDown) return null;
if (instance == null)
{
if (!Application.isPlaying) return null;
var objects = FindObjectsOfType<TouchManagerInstance>();
if (objects.Length == 0)
{
var go = new GameObject("TouchManager Instance");
instance = go.AddComponent<TouchManagerInstance>();
}
else if (objects.Length >= 1)
{
instance = objects[0];
}
}
return instance;
}
}
/// <inheritdoc />
public IDisplayDevice DisplayDevice
{
get
{
if (displayDevice == null)
{
displayDevice = ScriptableObject.CreateInstance<GenericDisplayDevice>();
}
return displayDevice;
}
set
{
if (value == null)
{
displayDevice = ScriptableObject.CreateInstance<GenericDisplayDevice>();
}
else
{
displayDevice = value;
}
updateDPI();
}
}
/// <inheritdoc />
public float DPI
{
get { return dpi; }
}
/// <inheritdoc />
public bool ShouldCreateCameraLayer
{
get { return shouldCreateCameraLayer; }
set { shouldCreateCameraLayer = value; }
}
/// <inheritdoc />
public bool ShouldCreateStandardInput
{
get { return shouldCreateStandardInput; }
set { shouldCreateStandardInput = value; }
}
/// <inheritdoc />
public IList<TouchLayer> Layers
{
get { return new List<TouchLayer>(layers); }
}
/// <inheritdoc />
public IList<IInputSource> Inputs
{
get { return new List<IInputSource>(inputs); }
}
/// <inheritdoc />
public float DotsPerCentimeter
{
get { return dotsPerCentimeter; }
}
/// <inheritdoc />
public int NumberOfTouches
{
get { return touches.Count; }
}
/// <inheritdoc />
public IList<TouchPoint> ActiveTouches
{
get { return new List<TouchPoint>(touches); }
}
#endregion
#region Private variables
private static bool shuttingDown = false;
private static TouchManagerInstance instance;
private bool shouldCreateCameraLayer = true;
private bool shouldCreateStandardInput = true;
private IDisplayDevice displayDevice;
private float dpi = 96;
private float dotsPerCentimeter = TouchManager.CM_TO_INCH * 96;
private List<TouchLayer> layers = new List<TouchLayer>(10);
private int layerCount = 0;
private List<IInputSource> inputs = new List<IInputSource>(3);
private int inputCount = 0;
private List<TouchPoint> touches = new List<TouchPoint>(30);
private Dictionary<int, TouchPoint> idToTouch = new Dictionary<int, TouchPoint>(30);
// Upcoming changes
private List<TouchPoint> touchesBegan = new List<TouchPoint>(10);
private HashSet<int> touchesUpdated = new HashSet<int>();
private HashSet<int> touchesEnded = new HashSet<int>();
private HashSet<int> touchesCancelled = new HashSet<int>();
private static ObjectPool<TouchPoint> touchPointPool = new ObjectPool<TouchPoint>(10, null, null,
(t) => t.INTERNAL_Reset());
private static ObjectPool<List<TouchPoint>> touchPointListPool = new ObjectPool<List<TouchPoint>>(2,
() => new List<TouchPoint>(10), null, (l) => l.Clear());
private static ObjectPool<List<int>> intListPool = new ObjectPool<List<int>>(3, () => new List<int>(10), null,
(l) => l.Clear());
private int nextTouchId = 0;
private object touchLock = new object();
#endregion
#region Public methods
/// <inheritdoc />
public bool AddLayer(TouchLayer layer)
{
return AddLayer(layer, 0);
}
/// <inheritdoc />
public bool AddLayer(TouchLayer layer, int index, bool addIfExists = true)
{
if (layer == null) return false;
var i = layers.IndexOf(layer);
if (i != -1)
{
if (!addIfExists) return false;
layers.RemoveAt(i);
layerCount--;
}
if (index <= 0)
{
layers.Insert(0, layer);
layerCount++;
return i == -1;
}
if (index >= layerCount)
{
layers.Add(layer);
layerCount++;
return i == -1;
}
if (i != -1)
{
if (index < i) layers.Insert(index, layer);
else layers.Insert(index - 1, layer);
layerCount++;
return false;
}
layers.Insert(index, layer);
layerCount++;
return true;
}
/// <inheritdoc />
public bool RemoveLayer(TouchLayer layer)
{
if (layer == null) return false;
var result = layers.Remove(layer);
if (result) layerCount--;
return result;
}
/// <inheritdoc />
public void ChangeLayerIndex(int at, int to)
{
if (at < 0 || at >= layerCount) return;
if (to < 0 || to >= layerCount) return;
var data = layers[at];
layers.RemoveAt(at);
layers.Insert(to, data);
}
/// <inheritdoc />
public bool AddInput(IInputSource input)
{
if (input == null) return false;
if (inputs.Contains(input)) return true;
inputs.Add(input);
inputCount++;
return true;
}
/// <inheritdoc />
public bool RemoveInput(IInputSource input)
{
if (input == null) return false;
var result = inputs.Remove(input);
if (result) inputCount--;
return result;
}
/// <inheritdoc />
public Transform GetHitTarget(Vector2 position)
{
TouchHit hit;
TouchLayer layer;
if (GetHitTarget(position, out hit, out layer)) return hit.Transform;
return null;
}
/// <inheritdoc />
public bool GetHitTarget(Vector2 position, out TouchHit hit)
{
TouchLayer layer;
return GetHitTarget(position, out hit, out layer);
}
/// <inheritdoc />
public bool GetHitTarget(Vector2 position, out TouchHit hit, out TouchLayer layer)
{
hit = default(TouchHit);
layer = null;
for (var i = 0; i < layerCount; i++)
{
var touchLayer = layers[i];
if (touchLayer == null) continue;
TouchHit _hit;
if (touchLayer.Hit(position, out _hit) == TouchLayer.LayerHitResult.Hit)
{
hit = _hit;
layer = touchLayer;
return true;
}
}
return false;
}
/// <inheritdoc />
public void CancelTouch(int id, bool @return)
{
TouchPoint touch;
if (idToTouch.TryGetValue(id, out touch))
{
touch.InputSource.CancelTouch(touch, @return);
}
}
/// <inheritdoc />
public void CancelTouch(int id)
{
CancelTouch(id, false);
}
#endregion
#region Internal methods
internal TouchPoint INTERNAL_BeginTouch(Vector2 position, IInputSource input)
{
return INTERNAL_BeginTouch(position, input, null);
}
internal TouchPoint INTERNAL_BeginTouch(Vector2 position, IInputSource input, Tags tags)
{
TouchPoint touch;
lock (touchLock)
{
touch = touchPointPool.Get();
touch.INTERNAL_Init(nextTouchId++, position, input, tags);
touchesBegan.Add(touch);
}
return touch;
}
/// <summary>
/// Update touch without moving it
/// </summary>
/// <param name="id">Touch id</param>
internal void INTERNAL_UpdateTouch(int id)
{
lock (touchLock)
{
if (idToTouch.ContainsKey(id))
{
if (!touchesUpdated.Contains(id)) touchesUpdated.Add(id);
}
#if TOUCHSCRIPT_DEBUG
else
Debug.LogWarning("TouchScript > Touch with id [" + id +
"] is requested to UPDATE but no touch with such id found.");
#endif
}
}
internal void INTERNAL_MoveTouch(int id, Vector2 position)
{
lock (touchLock)
{
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
// This touch was added this frame
touch = touchesBegan.Find((t) => t.Id == id);
// No touch with such id
if (touch == null)
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Touch with id [" + id + "] is requested to MOVE to " + position +
" but no touch with such id found.");
#endif
return;
}
}
touch.INTERNAL_SetPosition(position);
if (!touchesUpdated.Contains(id)) touchesUpdated.Add(id);
}
}
/// <inheritdoc />
internal void INTERNAL_EndTouch(int id)
{
lock (touchLock)
{
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
// This touch was added this frame
touch = touchesBegan.Find((t) => t.Id == id);
// No touch with such id
if (touch == null)
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Touch with id [" + id +
"] is requested to END but no touch with such id found.");
#endif
return;
}
}
if (!touchesEnded.Contains(id)) touchesEnded.Add(id);
#if TOUCHSCRIPT_DEBUG
else
Debug.LogWarning("TouchScript > Touch with id [" + id +
"] is requested to END more than once this frame.");
#endif
}
}
/// <inheritdoc />
internal void INTERNAL_CancelTouch(int id)
{
lock (touchLock)
{
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
// This touch was added this frame
touch = touchesBegan.Find((t) => t.Id == id);
// No touch with such id
if (touch == null)
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Touch with id [" + id +
"] is requested to CANCEL but no touch with such id found.");
#endif
return;
}
}
if (!touchesCancelled.Contains(id)) touchesCancelled.Add(touch.Id);
#if TOUCHSCRIPT_DEBUG
else
Debug.LogWarning("TouchScript > Touch with id [" + id +
"] is requested to CANCEL more than once this frame.");
#endif
}
}
#endregion
#region Unity
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(this);
return;
}
gameObject.hideFlags = HideFlags.HideInHierarchy;
DontDestroyOnLoad(gameObject);
updateDPI();
StopAllCoroutines();
StartCoroutine(lateAwake());
touchPointListPool.WarmUp(2);
intListPool.WarmUp(3);
#if TOUCHSCRIPT_DEBUG
DebugMode = true;
#endif
}
private void OnLevelWasLoaded(int value)
{
StopAllCoroutines();
StartCoroutine(lateAwake());
}
private IEnumerator lateAwake()
{
yield return null;
updateLayers();
createCameraLayer();
createTouchInput();
}
private void Update()
{
updateInputs();
updateTouches();
}
private void OnApplicationQuit()
{
shuttingDown = true;
}
#endregion
#region Private functions
private void updateDPI()
{
dpi = DisplayDevice == null ? 96 : DisplayDevice.DPI;
dotsPerCentimeter = TouchManager.CM_TO_INCH * dpi;
#if TOUCHSCRIPT_DEBUG
debugTouchSize = Vector2.one*dotsPerCentimeter;
#endif
}
private void updateLayers()
{
// filter empty layers
layers = layers.FindAll(l => l != null);
layerCount = layers.Count;
}
private void createCameraLayer()
{
if (layerCount == 0 && shouldCreateCameraLayer)
{
if (Camera.main != null)
{
if (Application.isEditor)
Debug.Log(
"[TouchScript] No camera layer found, adding CameraLayer for the main camera. (this message is harmless)");
var layer = Camera.main.gameObject.AddComponent<CameraLayer>();
AddLayer(layer);
}
}
}
private void createTouchInput()
{
if (inputCount == 0 && shouldCreateStandardInput)
{
if (Application.isEditor)
Debug.Log("[TouchScript] No input source found, adding StandardInput. (this message is harmless)");
GameObject obj = null;
var objects = FindObjectsOfType<TouchManager>();
if (objects.Length == 0)
{
obj = GameObject.Find("TouchScript");
if (obj == null) obj = new GameObject("TouchScript");
}
else
{
obj = objects[0].gameObject;
}
obj.AddComponent<StandardInput>();
}
}
private void updateInputs()
{
for (var i = 0; i < inputCount; i++) inputs[i].UpdateInput();
}
private void updateBegan(List<TouchPoint> points)
{
var count = points.Count;
for (var i = 0; i < count; i++)
{
var touch = points[i];
touches.Add(touch);
idToTouch.Add(touch.Id, touch);
for (var j = 0; j < layerCount; j++)
{
var touchLayer = layers[j];
if (touchLayer == null) continue;
if (touchLayer.INTERNAL_BeginTouch(touch)) break;
}
#if TOUCHSCRIPT_DEBUG
addDebugFigureForTouch(touch);
#endif
if (touchBeganInvoker != null)
touchBeganInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(touch));
}
}
private void updateUpdated(List<int> points)
{
var updatedCount = points.Count;
// Need to loop through all touches to reset those which did not move
var count = touches.Count;
for (var i = 0; i < count; i++)
{
touches[i].INTERNAL_ResetPosition();
}
for (var i = 0; i < updatedCount; i++)
{
var id = points[i];
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Id [" + id +
"] was in UPDATED list but no touch with such id found.");
#endif
continue;
}
if (touch.Layer != null) touch.Layer.INTERNAL_UpdateTouch(touch);
#if TOUCHSCRIPT_DEBUG
addDebugFigureForTouch(touch);
#endif
if (touchMovedInvoker != null)
touchMovedInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(touch));
}
}
private void updateEnded(List<int> points)
{
var endedCount = points.Count;
for (var i = 0; i < endedCount; i++)
{
var id = points[i];
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Id [" + id + "] was in ENDED list but no touch with such id found.");
#endif
continue;
}
idToTouch.Remove(id);
touches.Remove(touch);
if (touch.Layer != null) touch.Layer.INTERNAL_EndTouch(touch);
#if TOUCHSCRIPT_DEBUG
removeDebugFigureForTouch(touch);
#endif
if (touchEndedInvoker != null)
touchEndedInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(touch));
touchPointPool.Release(touch);
}
}
private void updateCancelled(List<int> points)
{
var cancelledCount = points.Count;
for (var i = 0; i < cancelledCount; i++)
{
var id = points[i];
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Id [" + id +
"] was in CANCELLED list but no touch with such id found.");
#endif
continue;
}
idToTouch.Remove(id);
touches.Remove(touch);
if (touch.Layer != null) touch.Layer.INTERNAL_CancelTouch(touch);
#if TOUCHSCRIPT_DEBUG
removeDebugFigureForTouch(touch);
#endif
if (touchCancelledInvoker != null)
touchCancelledInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(touch));
touchPointPool.Release(touch);
}
}
private void updateTouches()
{
if (frameStartedInvoker != null) frameStartedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
// need to copy buffers since they might get updated during execution
List<TouchPoint> beganList = null;
List<int> updatedList = null;
List<int> endedList = null;
List<int> cancelledList = null;
lock (touchLock)
{
if (touchesBegan.Count > 0)
{
beganList = touchPointListPool.Get();
beganList.AddRange(touchesBegan);
touchesBegan.Clear();
}
if (touchesUpdated.Count > 0)
{
updatedList = intListPool.Get();
updatedList.AddRange(touchesUpdated);
touchesUpdated.Clear();
}
if (touchesEnded.Count > 0)
{
endedList = intListPool.Get();
endedList.AddRange(touchesEnded);
touchesEnded.Clear();
}
if (touchesCancelled.Count > 0)
{
cancelledList = intListPool.Get();
cancelledList.AddRange(touchesCancelled);
touchesCancelled.Clear();
}
}
if (beganList != null)
{
updateBegan(beganList);
touchPointListPool.Release(beganList);
}
if (updatedList != null)
{
updateUpdated(updatedList);
intListPool.Release(updatedList);
}
if (endedList != null)
{
updateEnded(endedList);
intListPool.Release(endedList);
}
if (cancelledList != null)
{
updateCancelled(cancelledList);
intListPool.Release(cancelledList);
}
if (frameFinishedInvoker != null) frameFinishedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
}
#if TOUCHSCRIPT_DEBUG
private Vector2 debugTouchSize;
private void removeDebugFigureForTouch(TouchPoint touch)
{
GLDebug.RemoveFigure(TouchManager.DEBUG_GL_TOUCH + touch.Id);
}
private void addDebugFigureForTouch(TouchPoint touch)
{
GLDebug.DrawSquareScreenSpace(TouchManager.DEBUG_GL_TOUCH + touch.Id, touch.Position, 0, debugTouchSize,
GLDebug.MULTIPLY, float.PositiveInfinity);
}
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Rawr.CustomControls;
namespace Rawr.ProtPaladin
{
public partial class CalculationOptionsPanelProtPaladin : CalculationOptionsPanelBase
{
private Dictionary<int, string> armorBosses = new Dictionary<int, string>();
public CalculationOptionsPanelProtPaladin()
{
InitializeComponent();
armorBosses.Add((int)StatConversion.NPC_ARMOR[80 - 80], "Level 80 Creatures");
armorBosses.Add((int)StatConversion.NPC_ARMOR[81 - 80], "Level 81 Creatures");
armorBosses.Add((int)StatConversion.NPC_ARMOR[82 - 80], "Level 82 Creatures");
armorBosses.Add((int)StatConversion.NPC_ARMOR[83 - 80], "Bosses and Level 83 Creatures");
}
protected override void LoadCalculationOptions()
{
_loadingCalculationOptions = true;
if (Character.CalculationOptions == null)
Character.CalculationOptions = new CalculationOptionsProtPaladin();
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
PaladinTalents Talents = Character.PaladinTalents;
CK_PTRMode.Checked = calcOpts.PTRMode;
// Attacker Stats
comboBoxTargetType.SelectedItem = calcOpts.TargetType.ToString();
numericUpDownTargetLevel.Value = calcOpts.TargetLevel;
trackBarTargetArmor.Value = calcOpts.TargetArmor;
trackBarBossAttackValue.Value = calcOpts.BossAttackValue;
trackBarBossAttackSpeed.Value = (int)(calcOpts.BossAttackSpeed / 0.25f);
comboBoxMagicDamageType.SelectedItem = calcOpts.MagicDamageType.ToString();
trackBarBossAttackValueMagic.Value = calcOpts.BossAttackValueMagic;
trackBarBossAttackSpeedMagic.Value = (int)(calcOpts.BossAttackSpeedMagic / 0.25f);
checkBoxUseParryHaste.Checked = calcOpts.UseParryHaste;
// Stupid hack since you can't put in newlines into the VS editor properties
extendedToolTipUseParryHaste.ToolTipText =
extendedToolTipUseParryHaste.ToolTipText.Replace("May not", Environment.NewLine + "May not");
extendedToolTipDamageTakenMode.ToolTipText =
extendedToolTipDamageTakenMode.ToolTipText.Replace("10", Environment.NewLine + "10");
extendedToolTipMitigationScale.ToolTipText =
extendedToolTipMitigationScale.ToolTipText.Replace("Mitigation", Environment.NewLine + "Mitigation");
// Ranking System
if (calcOpts.ThreatScale > 30.0f) // Old scale value being saved, reset to default
calcOpts.ThreatScale = 10.0f;
trackBarThreatScale.Value = Convert.ToInt32(calcOpts.ThreatScale * 10.0f);
if (calcOpts.MitigationScale > 51000.0f) // Old scale value being saved, reset to default
calcOpts.MitigationScale = 17000.0f;
trackBarMitigationScale.Value = Convert.ToInt32((calcOpts.MitigationScale / 170.0f));
radioButtonMitigationScale.Checked = (calcOpts.RankingMode == 1);
radioButtonTankPoints.Checked = (calcOpts.RankingMode == 2);
radioButtonBurstTime.Checked = (calcOpts.RankingMode == 3);
radioButtonDamageOutput.Checked = (calcOpts.RankingMode == 4);
radioButtonProtWarrMode.Checked = (calcOpts.RankingMode == 5);
radioButtonDamageTakenMode.Checked = (calcOpts.RankingMode == 6);
trackBarThreatScale.Enabled = labelThreatScale.Enabled = (calcOpts.RankingMode != 4);
trackBarMitigationScale.Enabled = labelMitigationScale.Enabled = (calcOpts.RankingMode == 1) || (calcOpts.RankingMode == 5) || (calcOpts.RankingMode == 6);
comboBoxTrinketOnUseHandling.SelectedItem = calcOpts.TrinketOnUseHandling.ToString();
numericUpDownSurvivalSoftCap.Value = calcOpts.SurvivalSoftCap;
// Seal Choice
radioButtonSoR.Checked = (calcOpts.SealChoice == "Seal of Righteousness");
radioButtonSoV.Checked = (calcOpts.SealChoice == "Seal of Vengeance");
calcOpts.UseHolyShield = checkBoxUseHolyShield.Checked;
labelTargetArmorDescription.Text = trackBarTargetArmor.Value.ToString() + (armorBosses.ContainsKey(trackBarTargetArmor.Value) ? ": " + armorBosses[trackBarTargetArmor.Value] : "");
labelBossAttackValue.Text = trackBarBossAttackValue.Value.ToString();
labelBossAttackSpeed.Text = String.Format("{0:0.00}s", ((float)(trackBarBossAttackSpeed.Value) * 0.25f));
labelBossMagicalDamage.Text = trackBarBossAttackValueMagic.Value.ToString(); ;
labelBossMagicSpeed.Text = String.Format("{0:0.00}s", ((float)(trackBarBossAttackSpeedMagic.Value) * 0.25f));
labelThreatScale.Text = String.Format("{0:0.00}", ((float)(trackBarThreatScale.Value) * 0.01f));
labelMitigationScale.Text = String.Format("{0:0.00}", ((float)(trackBarMitigationScale.Value) * 0.01f));
switch (numericUpDownSurvivalSoftCap.Value.ToString()) {
case "90000": comboBoxSurvivalSoftCap.SelectedIndex = 0; break; //Normal Dungeons
case "110000": comboBoxSurvivalSoftCap.SelectedIndex = 1; break; //Heroic Dungeons
case "120000": comboBoxSurvivalSoftCap.SelectedIndex = 2; break; //T7 Raids (10)
case "140000": comboBoxSurvivalSoftCap.SelectedIndex = 3; break; //T7 Raids (25)
case "170000": comboBoxSurvivalSoftCap.SelectedIndex = 4; break; //T8 Raids (10)
case "195000": comboBoxSurvivalSoftCap.SelectedIndex = 5; break; //T8 Raids (10, Hard)
case "185000": comboBoxSurvivalSoftCap.SelectedIndex = 6; break; //T8 Raids (25)
case "215000": comboBoxSurvivalSoftCap.SelectedIndex = 7; break; //T8 Raids (25, Hard)
case "180000": comboBoxSurvivalSoftCap.SelectedIndex = 8; break; //T9 Raids (10)
case "210000": comboBoxSurvivalSoftCap.SelectedIndex = 9; break; //T9 Raids (10, Heroic)
case "190000": comboBoxSurvivalSoftCap.SelectedIndex = 10; break; //T9 Raids (25)
case "225000": comboBoxSurvivalSoftCap.SelectedIndex = 11; break; //T9 Raids (25, Heroic)
case "300000": comboBoxSurvivalSoftCap.SelectedIndex = 12; break; //T10 Raids (10)
case "355000": comboBoxSurvivalSoftCap.SelectedIndex = 13; break; //T10 Raids (10, Heroic)
case "350000": comboBoxSurvivalSoftCap.SelectedIndex = 14; break; //T10 Raids (25)
case "400000": comboBoxSurvivalSoftCap.SelectedIndex = 15; break; //T10 Raids (25, Heroic)
case "360000": comboBoxSurvivalSoftCap.SelectedIndex = 16; break; //Lich King (10)
case "410000": comboBoxSurvivalSoftCap.SelectedIndex = 17; break; //Lich King (10, Heroic)
case "405000": comboBoxSurvivalSoftCap.SelectedIndex = 18; break; //Lich King (25)
case "500000": comboBoxSurvivalSoftCap.SelectedIndex = 19; break; //Lich King (25, Heroic)
default: comboBoxSurvivalSoftCap.SelectedIndex = 20; break;
}
numericUpDownSurvivalSoftCap.Enabled = comboBoxSurvivalSoftCap.SelectedIndex == 20;
_loadingCalculationOptions = false;
}
private bool _loadingCalculationOptions = false;
private void calculationOptionControl_Changed(object sender, EventArgs e)
{
if (!_loadingCalculationOptions)
{
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
// Attacker Stats
labelTargetArmorDescription.Text = trackBarTargetArmor.Value.ToString() + (armorBosses.ContainsKey(trackBarTargetArmor.Value) ? ": " + armorBosses[trackBarTargetArmor.Value] : "");
trackBarBossAttackValue.Value = 500 * (trackBarBossAttackValue.Value / 500);
labelBossAttackValue.Text = trackBarBossAttackValue.Value.ToString();
labelBossAttackSpeed.Text = String.Format("{0:0.00}s", ((float)(trackBarBossAttackSpeed.Value) * 0.25f));
labelBossMagicalDamage.Text = trackBarBossAttackValueMagic.Value.ToString(); ;
labelBossMagicSpeed.Text = String.Format("{0:0.00}s", ((float)(trackBarBossAttackSpeedMagic.Value) * 0.25f));
// Ranking System
labelThreatScale.Text = String.Format("{0:0.00}", ((float)(trackBarThreatScale.Value) * 0.01f));
labelMitigationScale.Text = String.Format("{0:0.00}", ((float)(trackBarMitigationScale.Value) * 0.01f));
//c alcOpts.TargetLevel = int.Parse(comboBoxTargetLevel.SelectedItem.ToString());
calcOpts.TargetLevel = (int)numericUpDownTargetLevel.Value;
calcOpts.TargetArmor = trackBarTargetArmor.Value;
calcOpts.BossAttackValue = trackBarBossAttackValue.Value;
calcOpts.BossAttackSpeed = ((float)(trackBarBossAttackSpeed.Value) * 0.25f);
calcOpts.ThreatScale = ((float)(trackBarThreatScale.Value / 10.0f));
calcOpts.MitigationScale = ((float)(trackBarMitigationScale.Value) * 170.0f);
calcOpts.SurvivalSoftCap = (int)numericUpDownSurvivalSoftCap.Value;
Character.OnCalculationsInvalidated();
}
}
private void checkBoxUseParryHaste_CheckedChanged(object sender, EventArgs e)
{
if (!_loadingCalculationOptions)
{
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
calcOpts.UseParryHaste = checkBoxUseParryHaste.Checked;
Character.OnCalculationsInvalidated();
}
}
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
if (!_loadingCalculationOptions)
{
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
if (radioButtonTankPoints.Checked)
{
calcOpts.RankingMode = 2;
trackBarThreatScale.Value = 100;
}
else if (radioButtonBurstTime.Checked)
{
calcOpts.RankingMode = 3;
trackBarThreatScale.Value = 0;
}
else if (radioButtonDamageOutput.Checked)
{
calcOpts.RankingMode = 4;
trackBarThreatScale.Value = 100;
}
else if (radioButtonProtWarrMode.Checked)
{
calcOpts.RankingMode = 5;
trackBarThreatScale.Value = 100;
}
else if (radioButtonDamageTakenMode.Checked)
{
calcOpts.RankingMode = 6;
trackBarThreatScale.Value = 100;
}
else
{
calcOpts.RankingMode = 1;
trackBarThreatScale.Value = 100;
}
trackBarThreatScale.Enabled = labelThreatScale.Enabled = (calcOpts.RankingMode != 4);
trackBarMitigationScale.Enabled = labelMitigationScale.Enabled = (calcOpts.RankingMode == 1) || (calcOpts.RankingMode == 5) || (calcOpts.RankingMode == 6);
Character.OnCalculationsInvalidated();
}
}
private void extendedToolTipMitigtionScale_Click(object sender, EventArgs e)
{
if (!radioButtonMitigationScale.Checked)
radioButtonMitigationScale.Checked = true;
}
private void extendedToolTipTankPoints_Click(object sender, EventArgs e)
{
if (!radioButtonTankPoints.Checked)
radioButtonTankPoints.Checked = true;
}
private void extendedToolTipBurstTime_Click(object sender, EventArgs e)
{
if (!radioButtonBurstTime.Checked)
radioButtonBurstTime.Checked = true;
}
private void extendedToolTipDamageOutput_Click(object sender, EventArgs e)
{
if (!radioButtonDamageOutput.Checked)
radioButtonDamageOutput.Checked = true;
}
private void extendedToolProtWarrMode_Click(object sender, EventArgs e)
{
if (!radioButtonProtWarrMode.Checked)
radioButtonProtWarrMode.Checked = true;
}
private void extendedToolTipDamageTakenMode_Click(object sender, EventArgs e)
{
if (!radioButtonDamageTakenMode.Checked)
radioButtonDamageTakenMode.Checked = true;
}
private void radioButtonSealChoice_CheckedChanged(object sender, EventArgs e)
{
if (!_loadingCalculationOptions)
{
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
if (radioButtonSoR.Checked)
{
calcOpts.SealChoice = "Seal of Righteousness";
}
else
{
calcOpts.SealChoice = "Seal of Vengeance";
}
Character.OnCalculationsInvalidated();
}
}
private void checkBoxUseHolyShield_CheckedChanged(object sender, EventArgs e)
{
if (!_loadingCalculationOptions)
{
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
calcOpts.UseHolyShield = checkBoxUseHolyShield.Checked;
Character.OnCalculationsInvalidated();
}
}
private void numericUpDownTargetLevel_ValueChanged(object sender, EventArgs e)
{
if (!_loadingCalculationOptions)
{
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
calcOpts.TargetLevel = (int)numericUpDownTargetLevel.Value;
trackBarTargetArmor.Value = (int)StatConversion.NPC_ARMOR[calcOpts.TargetLevel-80];
Character.OnCalculationsInvalidated();
}
}
private void comboBoxTargetType_SelectedIndexChanged(object sender, EventArgs e)
{
if (!_loadingCalculationOptions)
{
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
calcOpts.TargetType = comboBoxTargetType.SelectedItem.ToString();
Character.OnCalculationsInvalidated();
}
}
private void comboBoxMagicDamageType_SelectedIndexChanged(object sender, EventArgs e)
{
if (!_loadingCalculationOptions)
{
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
calcOpts.MagicDamageType = comboBoxMagicDamageType.SelectedItem.ToString();
Character.OnCalculationsInvalidated();
}
}
private void ComboBoxTrinketOnUseHandling_SelectedIndexChanged(object sender, EventArgs e)
{
if (!_loadingCalculationOptions)
{
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
calcOpts.TrinketOnUseHandling = comboBoxTrinketOnUseHandling.SelectedItem.ToString();
Character.OnCalculationsInvalidated();
}
}
private void CK_PTRMode_CheckedChanged(object sender, EventArgs e) {
if (!_loadingCalculationOptions) {
CalculationOptionsProtPaladin calcOpts = Character.CalculationOptions as CalculationOptionsProtPaladin;
calcOpts.PTRMode = CK_PTRMode.Checked;
Character.OnCalculationsInvalidated();
}
}
private void comboBoxTargetDamage_SelectedIndexChanged(object sender, EventArgs e)
{
numericUpDownSurvivalSoftCap.Enabled = comboBoxSurvivalSoftCap.SelectedIndex == 20;
if (comboBoxSurvivalSoftCap.SelectedIndex < 20)
numericUpDownSurvivalSoftCap.Value =
(new decimal[] { 90000, 110000, 120000, 140000, 170000, 195000, 185000, 215000, 180000, 210000, 190000, 225000, 300000, 355000, 350000, 400000, 360000, 410000, 405000, 500000 })
[comboBoxSurvivalSoftCap.SelectedIndex];
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
[TestFixture]
[Category("group1")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientRegionInterestListTests : ThinClientRegionSteps
{
#region Private members and methods
private UnitProcess m_client1, m_client2, m_client3, m_feeder;
private static string[] m_regexes = { "Key-*1", "Key-*2",
"Key-*3", "Key-*4" };
private const string m_regex23 = "Key-[23]";
private const string m_regexWildcard = "Key-.*";
private const int m_numUnicodeStrings = 5;
private static string[] m_keysNonRegex = { "key-1", "key-2", "key-3" };
private static string[] m_keysForRegex = {"key-regex-1",
"key-regex-2", "key-regex-3" };
private static string[] RegionNamesForInterestNotify =
{ "RegionTrue", "RegionFalse", "RegionOther" };
string GetUnicodeString(int index)
{
return new string('\x0905', 40) + index.ToString("D10");
}
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
m_client3 = new UnitProcess();
m_feeder = new UnitProcess();
return new ClientBase[] { m_client1, m_client2, m_client3, m_feeder };
}
[TestFixtureTearDown]
public override void EndTests()
{
CacheHelper.StopJavaServers();
base.EndTests();
}
[TearDown]
public override void EndTest()
{
try
{
m_client1.Call(DestroyRegions);
m_client2.Call(DestroyRegions);
CacheHelper.ClearEndpoints();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
#region Steps for Thin Client IRegion<object, object> with Interest
public void StepFourIL()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepFourRegex3()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
try
{
Util.Log("Registering empty regular expression.");
region0.GetSubscriptionService().RegisterRegex(string.Empty);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering null regular expression.");
region1.GetSubscriptionService().RegisterRegex(null);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering non-existent regular expression.");
region1.GetSubscriptionService().UnregisterRegex("Non*Existent*Regex*");
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
}
public void StepFourFailoverRegex()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
UpdateEntry(m_regionNames[1], m_keys[1], m_vals[1], true);
UnregisterRegexes(null, m_regexes[2]);
}
public void StepFiveIL()
{
VerifyCreated(m_regionNames[0], m_keys[1]);
VerifyCreated(m_regionNames[1], m_keys[3]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
}
public void StepFiveRegex()
{
CreateEntry(m_regionNames[0], m_keys[2], m_vals[2]);
CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void CreateAllEntries(string regionName)
{
CreateEntry(regionName, m_keys[0], m_vals[0]);
CreateEntry(regionName, m_keys[1], m_vals[1]);
CreateEntry(regionName, m_keys[2], m_vals[2]);
CreateEntry(regionName, m_keys[3], m_vals[3]);
}
public void VerifyAllEntries(string regionName, bool newVal, bool checkVal)
{
string[] vals = newVal ? m_nvals : m_vals;
VerifyEntry(regionName, m_keys[0], vals[0], checkVal);
VerifyEntry(regionName, m_keys[1], vals[1], checkVal);
VerifyEntry(regionName, m_keys[2], vals[2], checkVal);
VerifyEntry(regionName, m_keys[3], vals[3], checkVal);
}
public void VerifyInvalidAll(string regionName, params string[] keys)
{
if (keys != null)
{
foreach (string key in keys)
{
VerifyInvalid(regionName, key);
}
}
}
public void UpdateAllEntries(string regionName, bool checkVal)
{
UpdateEntry(regionName, m_keys[0], m_nvals[0], checkVal);
UpdateEntry(regionName, m_keys[1], m_nvals[1], checkVal);
UpdateEntry(regionName, m_keys[2], m_nvals[2], checkVal);
UpdateEntry(regionName, m_keys[3], m_nvals[3], checkVal);
}
public void DoNetsearchAllEntries(string regionName, bool newVal,
bool checkNoKey)
{
string[] vals;
if (newVal)
{
vals = m_nvals;
}
else
{
vals = m_vals;
}
DoNetsearch(regionName, m_keys[0], vals[0], checkNoKey);
DoNetsearch(regionName, m_keys[1], vals[1], checkNoKey);
DoNetsearch(regionName, m_keys[2], vals[2], checkNoKey);
DoNetsearch(regionName, m_keys[3], vals[3], checkNoKey);
}
public void StepFiveFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1], false);
}
public void StepSixIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(m_regionNames[1]);
region0.Remove(m_keys[1]);
region1.Remove(m_keys[3]);
}
public void StepSixRegex()
{
CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]);
CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UnregisterRegexes(null, m_regexes[3]);
}
public void StepSixFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], false);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], false);
}
public void StepSevenIL()
{
VerifyDestroyed(m_regionNames[0], m_keys[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void StepSevenRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
UpdateEntry(m_regionNames[0], m_keys[2], m_nvals[2], true);
UpdateEntry(m_regionNames[1], m_keys[3], m_nvals[3], true);
UnregisterRegexes(null, m_regexes[1]);
}
public void StepSevenRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
DoNetsearch(m_regionNames[0], m_keys[0], m_vals[0], true);
DoNetsearch(m_regionNames[0], m_keys[3], m_vals[3], true);
UpdateAllEntries(m_regionNames[1], true);
}
public void StepSevenInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().RegisterRegex(m_regex23);
VerifyInvalidAll(m_regionNames[0], m_keys[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3], true);
}
public void StepSevenFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
VerifyEntry(m_regionNames[1], m_keys[1], m_nvals[1]);
}
public void StepEightIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]);
}
public void StepEightRegex()
{
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], true);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], true);
}
public void StepEightInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region.GetSubscriptionService().RegisterAllKeys();
VerifyInvalidAll(m_regionNames[1], m_keys[0], m_keys[1],
m_keys[2], m_keys[3]);
UpdateAllEntries(m_regionNames[0], true);
}
public void StepEightFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepNineRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
}
public void StepNineRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3]);
}
public void StepNineInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().UnregisterRegex(m_regex23);
List<Object> keys = new List<Object>();
keys.Add(m_keys[0]);
keys.Add(m_keys[1]);
keys.Add(m_keys[2]);
region.GetSubscriptionService().RegisterKeys(keys);
VerifyInvalidAll(m_regionNames[0], m_keys[0], m_keys[1], m_keys[2]);
}
public void PutUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object val;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
val = index + 100;
}
else
{
val = (float)index + 20.0F;
}
region[key] = val;
}
}
public void RegisterUnicodeKeys(string regionName)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string[] keys = new string[m_numUnicodeStrings];
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
keys[m_numUnicodeStrings - index - 1] = GetUnicodeString(index);
}
region.GetSubscriptionService().RegisterKeys(keys);
}
public void VerifyUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object expectedVal;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
expectedVal = index + 100;
Assert.AreEqual(expectedVal, region.GetEntry(key).Value,
"Got unexpected value");
}
else
{
expectedVal = (float)index + 20.0F;
Assert.AreEqual(expectedVal, region[key],
"Got unexpected value");
}
}
}
public void CreateRegionsInterestNotify_Pool(string[] regionNames,
string locators, string poolName, bool notify, string nbs)
{
Properties<string, string> props = Properties<string, string>.Create<string, string>();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion_Pool(regionNames[0], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[1], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[2], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
}
/*
public void CreateRegionsInterestNotify(string[] regionNames,
string endpoints, bool notify, string nbs)
{
Properties props = Properties.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion(regionNames[0], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[1], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[2], true, false,
new TallyListener(), endpoints, notify);
}
* */
public void DoFeed()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "00";
}
foreach (string key in m_keysForRegex)
{
region[key] = "00";
}
}
}
public void DoFeederOps()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
foreach (string key in m_keysForRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
}
}
public void DoRegister()
{
DoRegisterInterests(RegionNamesForInterestNotify[0], true);
DoRegisterInterests(RegionNamesForInterestNotify[1], false);
// We intentionally do not register interest in Region3
//DoRegisterInterestsBlah(RegionNamesForInterestNotifyBlah[2]);
}
public void DoRegisterInterests(string regionName, bool receiveValues)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
region.GetSubscriptionService().RegisterKeys(keys.ToArray(), false, false, receiveValues);
region.GetSubscriptionService().RegisterRegex("key-regex.*", false, false, receiveValues);
}
public void DoUnregister()
{
DoUnregisterInterests(RegionNamesForInterestNotify[0]);
DoUnregisterInterests(RegionNamesForInterestNotify[1]);
}
public void DoUnregisterInterests(string regionName)
{
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
region.GetSubscriptionService().UnregisterKeys(keys.ToArray());
region.GetSubscriptionService().UnregisterRegex("key-regex.*");
}
public void DoValidation(string clientName, string regionName,
int creates, int updates, int invalidates, int destroys)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
TallyListener<object, object> listener = region.Attributes.CacheListener as TallyListener<object, object>;
Util.Log(clientName + ": " + regionName + ": creates expected=" + creates +
", actual=" + listener.Creates);
Util.Log(clientName + ": " + regionName + ": updates expected=" + updates +
", actual=" + listener.Updates);
Util.Log(clientName + ": " + regionName + ": invalidates expected=" + invalidates +
", actual=" + listener.Invalidates);
Util.Log(clientName + ": " + regionName + ": destroys expected=" + destroys +
", actual=" + listener.Destroys);
Assert.AreEqual(creates, listener.Creates, clientName + ": " + regionName);
Assert.AreEqual(updates, listener.Updates, clientName + ": " + regionName);
Assert.AreEqual(invalidates, listener.Invalidates, clientName + ": " + regionName);
Assert.AreEqual(destroys, listener.Destroys, clientName + ": " + regionName);
}
#endregion
[Test]
public void InterestList()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client1.Call(StepThree);
m_client1.Call(RegisterKeys, m_keys[1], m_keys[3]);
Util.Log("StepThree complete.");
m_client2.Call(StepFour);
m_client2.Call(RegisterKeys, m_keys[0], (string)null);
Util.Log("StepFour complete.");
m_client1.Call(StepFiveIL);
m_client1.Call(UnregisterKeys, (string)null, m_keys[3]);
Util.Log("StepFive complete.");
m_client2.Call(StepSixIL);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenIL);
Util.Log("StepSeven complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// Static class that contains static glm functions
/// </summary>
public static partial class glm
{
/// <summary>
/// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy)
/// </summary>
public static swizzle_decvec2 swizzle(decvec2 v) => v.swizzle;
/// <summary>
/// Returns an array with all values
/// </summary>
public static decimal[] Values(decvec2 v) => v.Values;
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
public static IEnumerator<decimal> GetEnumerator(decvec2 v) => v.GetEnumerator();
/// <summary>
/// Returns a string representation of this vector using ', ' as a seperator.
/// </summary>
public static string ToString(decvec2 v) => v.ToString();
/// <summary>
/// Returns a string representation of this vector using a provided seperator.
/// </summary>
public static string ToString(decvec2 v, string sep) => v.ToString(sep);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format provider for each component.
/// </summary>
public static string ToString(decvec2 v, string sep, IFormatProvider provider) => v.ToString(sep, provider);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format for each component.
/// </summary>
public static string ToString(decvec2 v, string sep, string format) => v.ToString(sep, format);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format and format provider for each component.
/// </summary>
public static string ToString(decvec2 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider);
/// <summary>
/// Returns the number of components (2).
/// </summary>
public static int Count(decvec2 v) => v.Count;
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool Equals(decvec2 v, decvec2 rhs) => v.Equals(rhs);
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public static bool Equals(decvec2 v, object obj) => v.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public static int GetHashCode(decvec2 v) => v.GetHashCode();
/// <summary>
/// Returns true iff distance between lhs and rhs is less than or equal to epsilon
/// </summary>
public static bool ApproxEqual(decvec2 lhs, decvec2 rhs, decimal eps = 0.1m) => decvec2.ApproxEqual(lhs, rhs, eps);
/// <summary>
/// Returns a bvec2 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bvec2 Equal(decvec2 lhs, decvec2 rhs) => decvec2.Equal(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bvec2 NotEqual(decvec2 lhs, decvec2 rhs) => decvec2.NotEqual(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec2 GreaterThan(decvec2 lhs, decvec2 rhs) => decvec2.GreaterThan(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec2 GreaterThanEqual(decvec2 lhs, decvec2 rhs) => decvec2.GreaterThanEqual(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bvec2 LesserThan(decvec2 lhs, decvec2 rhs) => decvec2.LesserThan(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec2 LesserThanEqual(decvec2 lhs, decvec2 rhs) => decvec2.LesserThanEqual(lhs, rhs);
/// <summary>
/// Returns a decvec2 from component-wise application of Abs (Math.Abs(v)).
/// </summary>
public static decvec2 Abs(decvec2 v) => decvec2.Abs(v);
/// <summary>
/// Returns a decvec2 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v).
/// </summary>
public static decvec2 HermiteInterpolationOrder3(decvec2 v) => decvec2.HermiteInterpolationOrder3(v);
/// <summary>
/// Returns a decvec2 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v).
/// </summary>
public static decvec2 HermiteInterpolationOrder5(decvec2 v) => decvec2.HermiteInterpolationOrder5(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Sqr (v * v).
/// </summary>
public static decvec2 Sqr(decvec2 v) => decvec2.Sqr(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Pow2 (v * v).
/// </summary>
public static decvec2 Pow2(decvec2 v) => decvec2.Pow2(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Pow3 (v * v * v).
/// </summary>
public static decvec2 Pow3(decvec2 v) => decvec2.Pow3(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Step (v >= 0m ? 1m : 0m).
/// </summary>
public static decvec2 Step(decvec2 v) => decvec2.Step(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Sqrt ((decimal)Math.Sqrt((double)v)).
/// </summary>
public static decvec2 Sqrt(decvec2 v) => decvec2.Sqrt(v);
/// <summary>
/// Returns a decvec2 from component-wise application of InverseSqrt ((decimal)(1.0 / Math.Sqrt((double)v))).
/// </summary>
public static decvec2 InverseSqrt(decvec2 v) => decvec2.InverseSqrt(v);
/// <summary>
/// Returns a ivec2 from component-wise application of Sign (Math.Sign(v)).
/// </summary>
public static ivec2 Sign(decvec2 v) => decvec2.Sign(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Max (Math.Max(lhs, rhs)).
/// </summary>
public static decvec2 Max(decvec2 lhs, decvec2 rhs) => decvec2.Max(lhs, rhs);
/// <summary>
/// Returns a decvec2 from component-wise application of Min (Math.Min(lhs, rhs)).
/// </summary>
public static decvec2 Min(decvec2 lhs, decvec2 rhs) => decvec2.Min(lhs, rhs);
/// <summary>
/// Returns a decvec2 from component-wise application of Pow ((decimal)Math.Pow((double)lhs, (double)rhs)).
/// </summary>
public static decvec2 Pow(decvec2 lhs, decvec2 rhs) => decvec2.Pow(lhs, rhs);
/// <summary>
/// Returns a decvec2 from component-wise application of Log ((decimal)Math.Log((double)lhs, (double)rhs)).
/// </summary>
public static decvec2 Log(decvec2 lhs, decvec2 rhs) => decvec2.Log(lhs, rhs);
/// <summary>
/// Returns a decvec2 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)).
/// </summary>
public static decvec2 Clamp(decvec2 v, decvec2 min, decvec2 max) => decvec2.Clamp(v, min, max);
/// <summary>
/// Returns a decvec2 from component-wise application of Mix (min * (1-a) + max * a).
/// </summary>
public static decvec2 Mix(decvec2 min, decvec2 max, decvec2 a) => decvec2.Mix(min, max, a);
/// <summary>
/// Returns a decvec2 from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static decvec2 Lerp(decvec2 min, decvec2 max, decvec2 a) => decvec2.Lerp(min, max, a);
/// <summary>
/// Returns a decvec2 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()).
/// </summary>
public static decvec2 Smoothstep(decvec2 edge0, decvec2 edge1, decvec2 v) => decvec2.Smoothstep(edge0, edge1, v);
/// <summary>
/// Returns a decvec2 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()).
/// </summary>
public static decvec2 Smootherstep(decvec2 edge0, decvec2 edge1, decvec2 v) => decvec2.Smootherstep(edge0, edge1, v);
/// <summary>
/// Returns a decvec2 from component-wise application of Fma (a * b + c).
/// </summary>
public static decvec2 Fma(decvec2 a, decvec2 b, decvec2 c) => decvec2.Fma(a, b, c);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static decmat2 OuterProduct(decvec2 c, decvec2 r) => decvec2.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static decmat3x2 OuterProduct(decvec2 c, decvec3 r) => decvec2.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static decmat4x2 OuterProduct(decvec2 c, decvec4 r) => decvec2.OuterProduct(c, r);
/// <summary>
/// Returns a decvec2 from component-wise application of Add (lhs + rhs).
/// </summary>
public static decvec2 Add(decvec2 lhs, decvec2 rhs) => decvec2.Add(lhs, rhs);
/// <summary>
/// Returns a decvec2 from component-wise application of Sub (lhs - rhs).
/// </summary>
public static decvec2 Sub(decvec2 lhs, decvec2 rhs) => decvec2.Sub(lhs, rhs);
/// <summary>
/// Returns a decvec2 from component-wise application of Mul (lhs * rhs).
/// </summary>
public static decvec2 Mul(decvec2 lhs, decvec2 rhs) => decvec2.Mul(lhs, rhs);
/// <summary>
/// Returns a decvec2 from component-wise application of Div (lhs / rhs).
/// </summary>
public static decvec2 Div(decvec2 lhs, decvec2 rhs) => decvec2.Div(lhs, rhs);
/// <summary>
/// Returns a decvec2 from component-wise application of Modulo (lhs % rhs).
/// </summary>
public static decvec2 Modulo(decvec2 lhs, decvec2 rhs) => decvec2.Modulo(lhs, rhs);
/// <summary>
/// Returns a decvec2 from component-wise application of Degrees (Radians-To-Degrees Conversion).
/// </summary>
public static decvec2 Degrees(decvec2 v) => decvec2.Degrees(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Radians (Degrees-To-Radians Conversion).
/// </summary>
public static decvec2 Radians(decvec2 v) => decvec2.Radians(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Acos ((decimal)Math.Acos((double)v)).
/// </summary>
public static decvec2 Acos(decvec2 v) => decvec2.Acos(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Asin ((decimal)Math.Asin((double)v)).
/// </summary>
public static decvec2 Asin(decvec2 v) => decvec2.Asin(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Atan ((decimal)Math.Atan((double)v)).
/// </summary>
public static decvec2 Atan(decvec2 v) => decvec2.Atan(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Cos ((decimal)Math.Cos((double)v)).
/// </summary>
public static decvec2 Cos(decvec2 v) => decvec2.Cos(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Cosh ((decimal)Math.Cosh((double)v)).
/// </summary>
public static decvec2 Cosh(decvec2 v) => decvec2.Cosh(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Exp ((decimal)Math.Exp((double)v)).
/// </summary>
public static decvec2 Exp(decvec2 v) => decvec2.Exp(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Log ((decimal)Math.Log((double)v)).
/// </summary>
public static decvec2 Log(decvec2 v) => decvec2.Log(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Log2 ((decimal)Math.Log((double)v, 2)).
/// </summary>
public static decvec2 Log2(decvec2 v) => decvec2.Log2(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Log10 ((decimal)Math.Log10((double)v)).
/// </summary>
public static decvec2 Log10(decvec2 v) => decvec2.Log10(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Floor ((decimal)Math.Floor(v)).
/// </summary>
public static decvec2 Floor(decvec2 v) => decvec2.Floor(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Ceiling ((decimal)Math.Ceiling(v)).
/// </summary>
public static decvec2 Ceiling(decvec2 v) => decvec2.Ceiling(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Round ((decimal)Math.Round(v)).
/// </summary>
public static decvec2 Round(decvec2 v) => decvec2.Round(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Sin ((decimal)Math.Sin((double)v)).
/// </summary>
public static decvec2 Sin(decvec2 v) => decvec2.Sin(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Sinh ((decimal)Math.Sinh((double)v)).
/// </summary>
public static decvec2 Sinh(decvec2 v) => decvec2.Sinh(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Tan ((decimal)Math.Tan((double)v)).
/// </summary>
public static decvec2 Tan(decvec2 v) => decvec2.Tan(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Tanh ((decimal)Math.Tanh((double)v)).
/// </summary>
public static decvec2 Tanh(decvec2 v) => decvec2.Tanh(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Truncate ((decimal)Math.Truncate((double)v)).
/// </summary>
public static decvec2 Truncate(decvec2 v) => decvec2.Truncate(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Fract ((decimal)(v - Math.Floor(v))).
/// </summary>
public static decvec2 Fract(decvec2 v) => decvec2.Fract(v);
/// <summary>
/// Returns a decvec2 from component-wise application of Trunc ((long)(v)).
/// </summary>
public static decvec2 Trunc(decvec2 v) => decvec2.Trunc(v);
/// <summary>
/// Returns the minimal component of this vector.
/// </summary>
public static decimal MinElement(decvec2 v) => v.MinElement;
/// <summary>
/// Returns the maximal component of this vector.
/// </summary>
public static decimal MaxElement(decvec2 v) => v.MaxElement;
/// <summary>
/// Returns the euclidean length of this vector.
/// </summary>
public static decimal Length(decvec2 v) => v.Length;
/// <summary>
/// Returns the squared euclidean length of this vector.
/// </summary>
public static decimal LengthSqr(decvec2 v) => v.LengthSqr;
/// <summary>
/// Returns the sum of all components.
/// </summary>
public static decimal Sum(decvec2 v) => v.Sum;
/// <summary>
/// Returns the euclidean norm of this vector.
/// </summary>
public static decimal Norm(decvec2 v) => v.Norm;
/// <summary>
/// Returns the one-norm of this vector.
/// </summary>
public static decimal Norm1(decvec2 v) => v.Norm1;
/// <summary>
/// Returns the two-norm (euclidean length) of this vector.
/// </summary>
public static decimal Norm2(decvec2 v) => v.Norm2;
/// <summary>
/// Returns the max-norm of this vector.
/// </summary>
public static decimal NormMax(decvec2 v) => v.NormMax;
/// <summary>
/// Returns the p-norm of this vector.
/// </summary>
public static double NormP(decvec2 v, double p) => v.NormP(p);
/// <summary>
/// Returns a copy of this vector with length one (undefined if this has zero length).
/// </summary>
public static decvec2 Normalized(decvec2 v) => v.Normalized;
/// <summary>
/// Returns a copy of this vector with length one (returns zero if length is zero).
/// </summary>
public static decvec2 NormalizedSafe(decvec2 v) => v.NormalizedSafe;
/// <summary>
/// Returns the vector angle (atan2(y, x)) in radians.
/// </summary>
public static double Angle(decvec2 v) => v.Angle;
/// <summary>
/// Returns a 2D vector that was rotated by a given angle in radians (CAUTION: result is casted and may be truncated).
/// </summary>
public static decvec2 Rotated(decvec2 v, double angleInRad) => v.Rotated(angleInRad);
/// <summary>
/// Returns the inner product (dot product, scalar product) of the two vectors.
/// </summary>
public static decimal Dot(decvec2 lhs, decvec2 rhs) => decvec2.Dot(lhs, rhs);
/// <summary>
/// Returns the euclidean distance between the two vectors.
/// </summary>
public static decimal Distance(decvec2 lhs, decvec2 rhs) => decvec2.Distance(lhs, rhs);
/// <summary>
/// Returns the squared euclidean distance between the two vectors.
/// </summary>
public static decimal DistanceSqr(decvec2 lhs, decvec2 rhs) => decvec2.DistanceSqr(lhs, rhs);
/// <summary>
/// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result).
/// </summary>
public static decvec2 Reflect(decvec2 I, decvec2 N) => decvec2.Reflect(I, N);
/// <summary>
/// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result).
/// </summary>
public static decvec2 Refract(decvec2 I, decvec2 N, decimal eta) => decvec2.Refract(I, N, eta);
/// <summary>
/// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N).
/// </summary>
public static decvec2 FaceForward(decvec2 N, decvec2 I, decvec2 Nref) => decvec2.FaceForward(N, I, Nref);
/// <summary>
/// Returns the length of the outer product (cross product, vector product) of the two vectors.
/// </summary>
public static decimal Cross(decvec2 l, decvec2 r) => decvec2.Cross(l, r);
/// <summary>
/// Returns a decvec2 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
/// </summary>
public static decvec2 Random(Random random, decvec2 minValue, decvec2 maxValue) => decvec2.Random(random, minValue, maxValue);
/// <summary>
/// Returns a decvec2 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
/// </summary>
public static decvec2 RandomUniform(Random random, decvec2 minValue, decvec2 maxValue) => decvec2.RandomUniform(random, minValue, maxValue);
/// <summary>
/// Returns a decvec2 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
/// </summary>
public static decvec2 RandomNormal(Random random, decvec2 mean, decvec2 variance) => decvec2.RandomNormal(random, mean, variance);
/// <summary>
/// Returns a decvec2 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
/// </summary>
public static decvec2 RandomGaussian(Random random, decvec2 mean, decvec2 variance) => decvec2.RandomGaussian(random, mean, variance);
}
}
| |
// 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 FloorScalarDouble()
{
var test = new SimpleBinaryOpTest__FloorScalarDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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__FloorScalarDouble
{
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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, 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 Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__FloorScalarDouble testClass)
{
var result = Sse41.FloorScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__FloorScalarDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse41.FloorScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__FloorScalarDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleBinaryOpTest__FloorScalarDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.FloorScalar(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_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 = Sse41.FloorScalar(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_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 = Sse41.FloorScalar(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_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(Sse41).GetMethod(nameof(Sse41.FloorScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.FloorScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.FloorScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.FloorScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse41.FloorScalar(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(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<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse41.FloorScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse41.FloorScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse41.FloorScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__FloorScalarDouble();
var result = Sse41.FloorScalar(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__FloorScalarDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse41.FloorScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.FloorScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse41.FloorScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(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 = Sse41.FloorScalar(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 = Sse41.FloorScalar(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&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(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Floor(right[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(left[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.FloorScalar)}<Double>(Vector128<Double>, Vector128<Double>): {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 (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 Microsoft.Azure.Management.Dns
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
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>
/// ZonesOperations operations.
/// </summary>
internal partial class ZonesOperations : IServiceOperations<DnsManagementClient>, IZonesOperations
{
/// <summary>
/// Initializes a new instance of the ZonesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ZonesOperations(DnsManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DnsManagementClient
/// </summary>
public DnsManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates a DNS zone. Does not modify DNS records within the zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of the DNS zone. Omit this value to always overwrite the current
/// zone. Specify the last-seen etag value to prevent accidentally overwritting
/// any concurrent changes.
/// </param>
/// <param name='ifNoneMatch'>
/// Set to '*' to allow a new DNS zone to be created, but to prevent updating
/// an existing zone. Other values will be ignored.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Zone>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, Zone parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("ifNoneMatch", ifNoneMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", System.Uri.EscapeDataString(zoneName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new 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 (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (ifNoneMatch != null)
{
if (_httpRequest.Headers.Contains("If-None-Match"))
{
_httpRequest.Headers.Remove("If-None-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
}
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;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new 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 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Zone>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Zone>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Zone>(_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>
/// Deletes a DNS zone. WARNING: All DNS records in the zone will also be
/// deleted. This operation cannot be undone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='ifMatch'>
/// The etag of the DNS zone. Omit this value to always delete the current
/// zone. Specify the last-seen etag value to prevent accidentally deleting any
/// concurrent changes.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, zoneName, ifMatch, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a DNS zone. Retrieves the zone properties, but not the record sets
/// within the zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Zone>> GetWithHttpMessagesAsync(string resourceGroupName, string zoneName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", System.Uri.EscapeDataString(zoneName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + 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 (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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Zone>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Zone>(_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>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='top'>
/// The maximum number of record sets to return. If not specified, returns up
/// to 100 record sets.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Zone>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("top", top);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
}
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + 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 (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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Zone>>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Zone>>(_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>
/// Lists the DNS zones in all resource groups in a subscription.
/// </summary>
/// <param name='top'>
/// The maximum number of DNS zones to return. If not specified, returns up to
/// 100 zones.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Zone>>> ListWithHttpMessagesAsync(int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("top", top);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
}
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + 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 (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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Zone>>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Zone>>(_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>
/// Deletes a DNS zone. WARNING: All DNS records in the zone will also be
/// deleted. This operation cannot be undone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the DNS zone (without a terminating dot).
/// </param>
/// <param name='ifMatch'>
/// The etag of the DNS zone. Omit this value to always delete the current
/// zone. Specify the last-seen etag value to prevent accidentally deleting any
/// concurrent changes.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", System.Uri.EscapeDataString(zoneName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_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 (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
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 != 204 && (int)_statusCode != 202 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
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>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Zone>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + 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 (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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Zone>>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Zone>>(_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>
/// Lists the DNS zones in all resource groups in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Zone>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + 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 (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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Zone>>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Zone>>(_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;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.